// Messages / Campaigns — email/SMS/push campaigns to attendees

const Messages = ({ setRoute }) => {
  const [tab, setTab] = React.useState('all');
  const [composerOpen, setComposerOpen] = React.useState(false);

  const campaigns = [
    { id: 1, subject: 'Dein Apparat Ticket ist bereit 🎟', event: 'Apparat · Berghain', audience: 'All ticketholders', channel: 'email', sent: 3240, opened: 2284, clicked: 842, status: 'sent', when: '2h ago' },
    { id: 2, subject: '⚡ Last 200 Balkon tickets', event: 'Apparat · Berghain', audience: 'Newsletter subscribers', channel: 'email', sent: 12400, opened: 6820, clicked: 1640, status: 'sent', when: 'yesterday' },
    { id: 3, subject: 'Hot Chip — Early Bird endet Sonntag', event: 'Hot Chip · Astra', audience: 'Past buyers', channel: 'email', sent: 8400, opened: 4284, clicked: 1260, status: 'sent', when: '3d ago' },
    { id: 4, subject: 'Dein Festivalband — bitte aufbewahren', event: 'Tempelhof Sounds', audience: 'All ticketholders', channel: 'email+sms', sent: 48200, opened: 33740, clicked: 4820, status: 'sent', when: '1w ago' },
    { id: 5, subject: '48h to go — event day checklist', event: 'Roosevelt · Columbiahalle', audience: 'All ticketholders', channel: 'email', scheduled: '27. Apr, 18:00', status: 'scheduled', when: 'in 2 days' },
    { id: 6, subject: 'Pre-sale access for members', event: 'Fred again.. · Ziggo', audience: 'Premium members', channel: 'email+push', status: 'draft', when: 'Draft' },
    { id: 7, subject: 'Waitlist opening — tiered access', event: 'Open Air · Tempelhof', audience: 'Waitlist', channel: 'email', scheduled: '28. Apr, 10:00', status: 'scheduled', when: 'in 3 days' },
  ];

  const filtered = tab === 'all' ? campaigns : campaigns.filter(c => c.status === tab);

  return (
    <div style={{ padding: '24px 36px 60px', maxWidth: 1400, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', marginBottom: 20 }}>
        <div>
          <h1 className="display" style={{ margin: 0, fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em' }}>Messages</h1>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>Reach attendees via email, SMS and push. Automated reminders live on each event.</div>
        </div>
        <div style={{ flex: 1 }}/>
        <Button variant="secondary" size="md" icon="file">Templates</Button>
        <Button variant="primary" size="md" icon="plus" onClick={() => setComposerOpen(true)} style={{ marginLeft: 8 }}>New campaign</Button>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
        <Card><Stat label="Sent this month" value="184k" delta="+12%" icon="send"/></Card>
        <Card><Stat label="Avg. open rate" value="68.4%" delta="+3.2%" icon="mail" positive/></Card>
        <Card><Stat label="Avg. click rate" value="22.1%" delta="+1.8%" icon="link"/></Card>
        <Card><Stat label="Remaining credits" value="412k" sub="Email + 18k SMS" icon="bank"/></Card>
      </div>

      <Tabs value={tab} onChange={setTab} options={[
        { value: 'all', label: 'All', count: campaigns.length },
        { value: 'scheduled', label: 'Scheduled', count: campaigns.filter(c=>c.status==='scheduled').length },
        { value: 'sent', label: 'Sent', count: campaigns.filter(c=>c.status==='sent').length },
        { value: 'draft', label: 'Drafts', count: campaigns.filter(c=>c.status==='draft').length },
      ]}/>

      <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 320px', gap: 14 }}>
        <Card pad={0}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-sunken)', borderBottom: '1px solid var(--line)' }}>
                {['Campaign','Audience','Channel','Performance','Status',''].map(h => (
                  <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((c, i) => (
                <tr key={c.id} style={{ borderBottom: i < filtered.length - 1 ? '1px solid var(--line)' : 'none', height: 72 }}>
                  <td style={{ padding: '10px 14px', maxWidth: 320 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.subject}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 4 }}>
                      <Icon name="calendar" size={10}/>{c.event}
                    </div>
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ fontSize: 12.5 }}>{c.audience}</div>
                    {c.sent && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}><span className="mono">{c.sent.toLocaleString()}</span> recipients</div>}
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                      {c.channel.split('+').map(ch => (
                        <Badge key={ch} variant="neutral"><Icon name={ch==='email'?'mail':ch==='sms'?'phone':'bell'} size={10} style={{ marginRight: 4 }}/>{ch}</Badge>
                      ))}
                    </div>
                  </td>
                  <td style={{ padding: '10px 14px', minWidth: 190 }}>
                    {c.status === 'sent' ? (
                      <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
                          <span style={{ color: 'var(--ink-3)' }}>Open {Math.round((c.opened/c.sent)*100)}% · Click {Math.round((c.clicked/c.sent)*100)}%</span>
                        </div>
                        <div style={{ height: 5, borderRadius: 99, background: 'var(--bg-muted)', position: 'relative', overflow: 'hidden' }}>
                          <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(c.opened/c.sent)*100}%`, background: 'var(--success)' }}/>
                          <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(c.clicked/c.sent)*100}%`, background: 'var(--accent)' }}/>
                        </div>
                      </div>
                    ) : c.status === 'scheduled' ? (
                      <span style={{ fontSize: 12, color: 'var(--ink-3)', display:'flex', alignItems:'center', gap: 5 }}>
                        <Icon name="clock" size={11}/>{c.scheduled}
                      </span>
                    ) : (
                      <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>—</span>
                    )}
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <StatusBadge status={c.status}/>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3 }}>{c.when}</div>
                  </td>
                  <td style={{ padding: '10px 14px', textAlign: 'right' }}>
                    <Button variant="ghost" size="sm" icon="more" style={{ padding: '0 8px' }}/>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>Top-performing campaign</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 12 }}>Last 30 days</div>
            <div style={{ padding: 12, borderRadius: 10, background: 'var(--bg-sunken)' }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 2 }}>Your Coldplay wristband — keep it safe</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 10 }}>Sent to 48,200 · 1 week ago</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                <div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>70%</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Open</div>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>10%</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Click</div>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>1.8%</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Unsub</div>
                </div>
              </div>
            </div>
          </Card>

          <Card>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Templates</div>
            {[
              { i: 'sparkle', n: 'Announce new event', d: '5 sections, cover hero' },
              { i: 'clock', n: 'Last call — 24h', d: 'Urgency banner, CTA' },
              { i: 'ticket', n: 'Order confirmation', d: 'Ticket + QR inline' },
              { i: 'heart', n: 'Post-event thank you', d: 'Feedback CTA' },
            ].map((t, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: i<3?'1px solid var(--line)':'none', cursor: 'pointer' }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-sunken)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={t.i} size={14}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{t.n}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t.d}</div>
                </div>
                <Icon name="arrowRight" size={12} style={{ color: 'var(--ink-4)' }}/>
              </div>
            ))}
          </Card>

          <Card>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Sending rules</div>
            {[
              { l: 'Quiet hours', s: '22:00 – 08:00 MEZ', on: true },
              { l: 'Throttle (SMS)', s: 'Max 10k / hr', on: true },
              { l: 'Auto-suppress bounces', s: 'After 2 hard bounces', on: true },
            ].map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '8px 0', borderBottom: i<2?'1px solid var(--line)':'none' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{r.l}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.s}</div>
                </div>
                <Toggle checked={r.on} onChange={()=>{}}/>
              </div>
            ))}
          </Card>
        </div>
      </div>

      {composerOpen && <ComposerModal onClose={() => setComposerOpen(false)}/>}
    </div>
  );
};

const ComposerModal = ({ onClose }) => {
  const [channel, setChannel] = React.useState('email');
  const [audience, setAudience] = React.useState('all');
  const [subject, setSubject] = React.useState('Quick update about your Apparat tickets');

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,17,14,0.35)', zIndex: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 960, maxWidth: '100%', maxHeight: '90vh', background: 'var(--bg)',
        borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,0.3)', overflow: 'hidden',
        display: 'grid', gridTemplateRows: 'auto 1fr auto',
      }}>
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center' }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>New campaign</h3>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>Message attendees directly from their booking channel.</div>
          </div>
          <div style={{ flex: 1 }}/>
          <Button variant="ghost" size="sm" icon="close" onClick={onClose}/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', overflow: 'auto' }}>
          {/* Setup */}
          <div style={{ padding: 20, borderRight: '1px solid var(--line)', overflow: 'auto' }}>
            <Field label="Channel">
              <div style={{ display: 'flex', gap: 6 }}>
                {[
                  { k: 'email', i: 'mail', l: 'Email' },
                  { k: 'sms', i: 'phone', l: 'SMS' },
                  { k: 'push', i: 'bell', l: 'Push' },
                ].map(o => (
                  <button key={o.k} onClick={() => setChannel(o.k)} style={{
                    flex: 1, padding: '10px 6px', borderRadius: 8,
                    border: `1px solid ${channel===o.k?'var(--accent)':'var(--line)'}`,
                    background: channel===o.k?'color-mix(in oklch, var(--accent) 6%, var(--bg-raised))':'var(--bg-raised)',
                    color: channel===o.k?'var(--accent)':'var(--ink-2)',
                    fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                  }}><Icon name={o.i} size={14}/>{o.l}</button>
                ))}
              </div>
            </Field>

            <Field label="Event" style={{ marginTop: 14 }}>
              <Select value="apparat" options={[
                { value: 'apparat', label: 'Apparat · Berghain · 24. Mai' },
                { value: 'hotchip', label: 'Hot Chip · Astra · 12. Jun' },
                { value: 'tempelhof', label: 'Open Air · Tempelhof · 28. Jul' },
                { value: 'all', label: 'All events (cross-event)' },
              ]}/>
            </Field>

            <Field label="Audience" style={{ marginTop: 14 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {[
                  { k: 'all', l: 'All ticketholders', sub: '3,240 people' },
                  { k: 'tier', l: 'Specific tiers', sub: 'VIP / GA / Balkon / Oberrang' },
                  { k: 'unchecked', l: 'Not yet checked-in', sub: '— (use on event day)' },
                  { k: 'waitlist', l: 'Waitlist', sub: '842 people' },
                  { k: 'custom', l: 'Custom segment', sub: 'Build by filters' },
                ].map(o => (
                  <button key={o.k} onClick={() => setAudience(o.k)} style={{
                    textAlign: 'left', padding: '10px 12px', borderRadius: 8,
                    border: `1px solid ${audience===o.k?'var(--accent)':'var(--line)'}`,
                    background: audience===o.k?'color-mix(in oklch, var(--accent) 6%, var(--bg-raised))':'var(--bg-raised)',
                    fontFamily: 'inherit', cursor: 'pointer',
                  }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: audience===o.k?'var(--accent)':'var(--ink)' }}>{o.l}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{o.sub}</div>
                  </button>
                ))}
              </div>
            </Field>

            <Field label="Send" style={{ marginTop: 14 }}>
              <Select value="now" options={[
                { value: 'now', label: 'Send immediately' },
                { value: 'schedule', label: 'Schedule for later' },
                { value: 'optimal', label: 'Send at optimal time' },
              ]}/>
            </Field>
          </div>

          {/* Editor + preview */}
          <div style={{ display: 'grid', gridTemplateRows: '1fr auto', overflow: 'hidden' }}>
            <div style={{ padding: 20, overflow: 'auto' }}>
              {channel === 'email' && (
                <>
                  <Field label="Subject line">
                    <Input value={subject} onChange={e => setSubject(e.target.value)}/>
                  </Field>
                  <Field label="Preview text" style={{ marginTop: 12 }}>
                    <Input value="Event day essentials — gates, entry, prohibited items"/>
                  </Field>
                  <Field label="Message" style={{ marginTop: 12 }}>
                    <div style={{ border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
                      <div style={{ display: 'flex', gap: 2, padding: 6, background: 'var(--bg-sunken)', borderBottom: '1px solid var(--line)' }}>
                        {['B','I','U','·','H1','H2','·','link','image','·','{{name}}','{{event}}'].map((t, i) => (
                          <button key={i} style={{ padding: '4px 8px', border: 0, background: 'transparent', borderRadius: 5, cursor: 'pointer', fontSize: 11, fontFamily: t.startsWith('{{')?'var(--font-mono)':'inherit', color: 'var(--ink-2)' }}>{t}</button>
                        ))}
                      </div>
                      <div style={{ padding: 14, fontSize: 13, lineHeight: 1.6, minHeight: 180 }}>
                        Hey {'{{first_name}}'}, <br/><br/>
                        We can't wait to see you at Apparat · LP5 Live this Saturday at Berghain.<br/><br/>
                        <strong>Einlass ab 21:00.</strong> Please carry a valid photo ID matching your booking name.<br/><br/>
                        <em style={{ color: 'var(--ink-3)' }}>[+ Add section]</em>
                      </div>
                    </div>
                  </Field>
                </>
              )}
              {channel === 'sms' && (
                <Field label="Message (160 char limit per SMS)">
                  <Textarea rows={4} value="Tixwerk: Dein Apparat Ticket für Sa 24. Mai, Berghain. Einlass 21:00. Ticket beim Einlass zeigen. Info: tixwerk.de/help"/>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: 'var(--ink-3)' }}>
                    <span>133 / 160 chars · 1 SMS</span>
                    <span>Est. cost 259,20 € · 3.240 × 0,08 €</span>
                  </div>
                </Field>
              )}
              {channel === 'push' && (
                <>
                  <Field label="Title"><Input value="Dein Apparat Ticket ist bereit"/></Field>
                  <Field label="Body" style={{ marginTop: 12 }}><Textarea rows={3} value="Einlass Samstag 21:00. Tippe, um Ticket und Gate zu sehen."/></Field>
                  <Field label="Tap action" style={{ marginTop: 12 }}>
                    <Select value="ticket" options={[
                      { value: 'ticket', label: 'Open ticket' },
                      { value: 'event', label: 'Open event page' },
                      { value: 'url', label: 'Custom URL' },
                    ]}/>
                  </Field>
                </>
              )}
            </div>
          </div>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-raised)' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            Sending to <strong style={{ color: 'var(--ink-2)' }}>3,240 people</strong> · estimated delivery under 4 minutes
          </div>
          <div style={{ flex: 1 }}/>
          <Button variant="secondary" size="md">Save as draft</Button>
          <Button variant="secondary" size="md" icon="eye">Send test</Button>
          <Button variant="primary" size="md" icon="send">Send campaign</Button>
        </div>
      </div>
    </div>
  );
};

window.Messages = Messages;
