// screen-campaigns.jsx — Campaign list + multi-step composer modal
// Exports: CampaignsScreen

const CAMPAIGNS_NOUR = [
  { id: 1, name: 'Summer Flash Sale', type: 'Promotional', audience: 'All subscribers · Cairo', sent: 1240, tap: '18.4%', revenue: 'EGP 4,380', status: 'sent', date: 'Jun 6, 8:00 PM' },
  { id: 2, name: 'Cart abandonment · 1h delay', type: 'Transactional', audience: 'Abandoned carts', sent: 312, tap: '22.1%', revenue: 'EGP 1,840', status: 'live', date: 'Always on' },
  { id: 3, name: 'New arrivals — Linen edit', type: 'Promotional', audience: 'VIP segment', sent: null, tap: null, revenue: null, status: 'scheduled', date: 'Jun 14, 7:00 PM' },
  { id: 4, name: 'Eid Al-Fitr preview drop', type: 'Promotional', audience: 'All subscribers', sent: null, tap: null, revenue: null, status: 'draft', date: null },
  { id: 5, name: 'Order shipped confirmation', type: 'Transactional', audience: 'Order placed', sent: 88, tap: '41.2%', revenue: null, status: 'live', date: 'Always on' },
];

const CAMPAIGNS_MARCUS = [
  { id: 1, name: 'Studio Speaker launch', type: 'Promotional', audience: 'All subscribers', sent: 3847, tap: '12.6%', revenue: '$14,200', status: 'sent', date: 'Jun 4, 12:00 PM' },
  { id: 2, name: 'Weekend deal — earbuds', type: 'Promotional', audience: 'Segments: Deal hunters', sent: 1920, tap: '9.8%', revenue: '$6,400', status: 'sent', date: 'Jun 1, 9:00 AM' },
  { id: 3, name: 'Cart abandonment · 1h', type: 'Transactional', audience: 'Abandoned carts', sent: 624, tap: '24.3%', revenue: '$3,100', status: 'live', date: 'Always on' },
  { id: 4, name: 'Back-to-school promo', type: 'Promotional', audience: 'All subscribers', sent: null, tap: null, revenue: null, status: 'scheduled', date: 'Aug 12, 8:00 AM' },
  { id: 5, name: 'Back-in-stock: MagSafe', type: 'Transactional', audience: 'Waitlist subscribers', sent: 218, tap: '38.1%', revenue: '$2,900', status: 'sent', date: 'May 28' },
];

const SEGMENTS_NOUR = ['All app subscribers', 'VIP customers (500+)', 'Cairo — all', 'Cart abandoners', 'First-time buyers', 'Fashion VIP segment'];
const SEGMENTS_MARCUS = ['All app subscribers', 'Deal hunters', 'Austin — local', 'Cart abandoners', 'High-value buyers (>$200)', 'New arrivals waitlist'];

// Campaign composer — multi-step modal
const CampaignComposer = ({ open, onClose, persona }) => {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    name: '', type: 'promotional', audience: '', title: '', body: '',
    scheduleType: 'now', scheduleDate: '', scheduleTime: '08:00',
  });
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);

  const segments = persona.id === 'nour' ? SEGMENTS_NOUR : SEGMENTS_MARCUS;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const STEPS = ['Audience', 'Content', 'Schedule', 'Review & send'];

  const handleSend = () => {
    setSending(true);
    setTimeout(() => { setSending(false); setSent(true); }, 1800);
    setTimeout(() => { setSent(false); onClose(); setStep(1); setForm({ name: '', type: 'promotional', audience: '', title: '', body: '', scheduleType: 'now', scheduleDate: '', scheduleTime: '08:00' }); }, 3200);
  };

  const audienceCount = form.audience.includes('All') ? (persona.id === 'nour' ? '1,240' : '3,847') : (persona.id === 'nour' ? '~340' : '~920');

  const stepContent = {
    1: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <window.Input label="Campaign name" value={form.name} onChange={e => set('name', e.target.value)} placeholder={persona.id === 'nour' ? 'e.g. Ramadan collection drop' : 'e.g. Product launch push'} help="Internal name — not shown to customers." />
        <window.Select label="Campaign type" value={form.type} onChange={e => set('type', e.target.value)} options={[{ value: 'promotional', label: 'Promotional' }, { value: 'transactional', label: 'Transactional' }, { value: 'scheduled', label: 'Scheduled' }]} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>Audience segment</label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            {segments.map(seg => (
              <div key={seg} onClick={() => set('audience', seg)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 8, cursor: 'pointer', background: form.audience === seg ? 'var(--ink-08)' : 'var(--white)', border: `1px solid ${form.audience === seg ? 'var(--hairline-bold)' : 'var(--hairline)'}`, transition: 'all 120ms' }}>
                <div style={{ width: 14, height: 14, borderRadius: '50%', border: `2px solid ${form.audience === seg ? 'var(--ink)' : 'var(--sand-300)'}`, background: form.audience === seg ? 'var(--ink)' : 'transparent', flexShrink: 0 }}></div>
                <span style={{ fontSize: 13, fontWeight: form.audience === seg ? 500 : 400 }}>{seg}</span>
                {seg.includes('All') && <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>{persona.id === 'nour' ? '1,240' : '3,847'} subs</span>}
              </div>
            ))}
          </div>
        </div>
      </div>
    ),
    2: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <window.Input label="Notification title" value={form.title} onChange={e => set('title', e.target.value)} placeholder={persona.id === 'nour' ? 'New arrivals just landed ✨' : 'Studio Speaker is here 🎵'} help="Keep under 50 characters for best results." />
        <window.Textarea label="Message body" value={form.body} onChange={e => set('body', e.target.value)} placeholder={persona.id === 'nour' ? 'Shop our new linen edit — free shipping on orders over EGP 800.' : 'Introducing the Studio Speaker. 40h battery. Free shipping.'} rows={3} help="140 characters max. Be direct — your customers are busy." />

        {/* Live preview */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>Preview</div>
          <div style={{ background: '#1A1A1A', borderRadius: 14, padding: '12px 14px', maxWidth: 320 }}>
            <div style={{ display: 'flex', align: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{ width: 36, height: 36, borderRadius: 9, background: persona.color, flexShrink: 0 }}></div>
              <div>
                <div style={{ fontSize: 12, fontWeight: 600, color: '#F5F1E8', marginBottom: 2 }}>{form.title || 'Notification title'}</div>
                <div style={{ fontSize: 11, color: 'rgba(245,241,232,0.7)', lineHeight: 1.4 }}>{form.body || 'Your message will appear here.'}</div>
              </div>
            </div>
            <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.4)', textAlign: 'right' }}>{persona.appName} · now</div>
          </div>
        </div>

        <div>
          <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)', marginBottom: 8 }}>Deep link (optional)</div>
          <window.Select value="Homepage" options={['Homepage', 'Featured collection', 'Product page', 'Sale collection', 'Custom URL']} />
        </div>
      </div>
    ),
    3: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>Send time</div>
          {[{ id: 'now', label: 'Send immediately' }, { id: 'scheduled', label: 'Schedule for later' }].map(opt => (
            <div key={opt.id} onClick={() => set('scheduleType', opt.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 8, cursor: 'pointer', background: form.scheduleType === opt.id ? 'var(--ink-08)' : 'var(--white)', border: `1px solid ${form.scheduleType === opt.id ? 'var(--hairline-bold)' : 'var(--hairline)'}` }}>
              <div style={{ width: 14, height: 14, borderRadius: '50%', border: `2px solid ${form.scheduleType === opt.id ? 'var(--ink)' : 'var(--sand-300)'}`, background: form.scheduleType === opt.id ? 'var(--ink)' : 'transparent', flexShrink: 0 }}></div>
              <span style={{ fontSize: 13, fontWeight: form.scheduleType === opt.id ? 500 : 400 }}>{opt.label}</span>
            </div>
          ))}
        </div>
        {form.scheduleType === 'scheduled' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <window.Input type="date" label="Date" value={form.scheduleDate} onChange={e => set('scheduleDate', e.target.value)} />
            <window.Input type="time" label="Time" value={form.scheduleTime} onChange={e => set('scheduleTime', e.target.value)} help={persona.id === 'nour' ? 'Cairo time (EET)' : 'Austin time (CDT)'} />
          </div>
        )}
        <div style={{ background: 'var(--sand-50)', borderRadius: 8, padding: '12px 14px', fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.6 }}>
          <strong style={{ color: 'var(--fg-1)' }}>Delivery estimate:</strong> {audienceCount} subscribers will receive this notification. Average delivery time is under 30 seconds.
        </div>
      </div>
    ),
    4: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '32px 0', display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--mint-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <i data-lucide="check" style={{ width: 24, height: 24, color: 'var(--mint)' }}></i>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 28, color: 'var(--ink)' }}>Sent.</div>
            <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>Campaign sent to {audienceCount} subscribers.</div>
          </div>
        ) : (
          <>
            {[
              { label: 'Campaign', value: form.name || '(untitled)' },
              { label: 'Audience', value: form.audience || '—' },
              { label: 'Reach', value: `~${audienceCount} subscribers` },
              { label: 'Title', value: form.title || '—' },
              { label: 'Message', value: form.body || '—' },
              { label: 'Send time', value: form.scheduleType === 'now' ? 'Immediately' : `${form.scheduleDate} at ${form.scheduleTime}` },
            ].map(row => (
              <div key={row.label} style={{ display: 'flex', gap: 16, paddingBottom: 12, borderBottom: '1px solid var(--hairline)' }}>
                <div style={{ width: 100, fontSize: 12, color: 'var(--fg-3)', flexShrink: 0 }}>{row.label}</div>
                <div style={{ fontSize: 13, color: 'var(--fg-1)', fontWeight: 500 }}>{row.value}</div>
              </div>
            ))}
            <window.Button size="lg" style={{ justifyContent: 'center' }} onClick={handleSend} disabled={sending}>
              {sending ? <><window.Spinner size={14} /> Sending…</> : form.scheduleType === 'now' ? 'Send now →' : 'Schedule campaign →'}
            </window.Button>
          </>
        )}
      </div>
    ),
  };

  return (
    <window.Modal open={open} onClose={onClose} title="New campaign" width={520}>
      {/* Step indicator */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 24 }}>
        {STEPS.map((s, i) => (
          <div key={s} onClick={() => i + 1 < step && setStep(i + 1)} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 5, cursor: i + 1 < step ? 'pointer' : 'default' }}>
            <div style={{ height: 3, borderRadius: 999, background: step > i + 1 ? 'var(--mint)' : step === i + 1 ? 'var(--ink)' : 'var(--sand-100)', transition: 'background 250ms' }}></div>
            <div style={{ fontSize: 10, color: step === i + 1 ? 'var(--fg-1)' : 'var(--fg-3)', fontWeight: step === i + 1 ? 600 : 400 }}>{s}</div>
          </div>
        ))}
      </div>

      {stepContent[step]}

      {!sent && step < 4 && (
        <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
          {step > 1 && <window.Button variant="secondary" onClick={() => setStep(s => s - 1)}>← Back</window.Button>}
          <window.Button onClick={() => setStep(s => s + 1)}>Continue →</window.Button>
        </div>
      )}
    </window.Modal>
  );
};

const CampaignsScreen = ({ persona, tweaks }) => {
  const [composerOpen, setComposerOpen] = React.useState(false);
  const [filter, setFilter] = React.useState('All');
  const { dark } = tweaks;

  const campaigns = persona.id === 'nour' ? CAMPAIGNS_NOUR : CAMPAIGNS_MARCUS;
  const filters = ['All', 'Live', 'Sent', 'Scheduled', 'Draft'];
  const filtered = filter === 'All' ? campaigns : campaigns.filter(c => c.status.toLowerCase() === filter.toLowerCase());

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1100 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: textColor, margin: 0, lineHeight: 1.1 }}>Campaigns</h1>
          <div style={{ fontSize: 13, color: subColor, marginTop: 6 }}>Push notifications, transactional alerts, and scheduled drops.</div>
        </div>
        <window.Button icon="plus" onClick={() => setComposerOpen(true)}>New campaign</window.Button>
      </div>

      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { label: 'Total sent · 30d', value: persona.id === 'nour' ? '1,640' : '6,609', sub: null },
          { label: 'Avg tap-through', value: persona.id === 'nour' ? '18.4%' : '12.6%', sub: 'vs 3.2% industry avg' },
          { label: 'Push revenue · 30d', value: persona.id === 'nour' ? 'EGP 6,220' : '$26,600', sub: null },
          { label: 'Active automations', value: persona.id === 'nour' ? '2' : '3', sub: 'Always-on campaigns' },
        ].map((k, i) => (
          <div key={i} style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 10, padding: '16px 18px' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: subColor, fontWeight: 500, marginBottom: 8 }}>{k.label}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 30, lineHeight: 1, color: i === 2 ? 'var(--honey)' : textColor, marginBottom: k.sub ? 6 : 0 }}>{k.value}</div>
            {k.sub && <div style={{ fontSize: 11, color: subColor }}>{k.sub}</div>}
          </div>
        ))}
      </div>

      {/* Campaigns table */}
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: `1px solid ${cardBorder}`, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>All campaigns</div>
          <window.FilterPills options={filters} active={filter} onSelect={setFilter} />
          <div style={{ flex: 1 }}></div>
          <window.Button variant="secondary" size="sm" icon="download">Export</window.Button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>
              {['Campaign', 'Type', 'Audience', 'Sent', 'Tap-through', 'Revenue', 'Schedule', 'Status'].map(h => (
                <th key={h} style={{ textAlign: 'left', padding: '10px 16px', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, borderBottom: `1px solid ${cardBorder}`, background: dark ? 'rgba(0,0,0,0.15)' : 'var(--paper-bright)', whiteSpace: 'nowrap' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((c, i) => (
              <tr key={c.id} style={{ borderBottom: i < filtered.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none', cursor: 'pointer' }}
                onMouseEnter={e => e.currentTarget.style.background = dark ? 'rgba(255,255,255,0.03)' : 'var(--sand-50)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <td style={{ padding: '13px 16px', fontWeight: 500, color: textColor, maxWidth: 200 }}>{c.name}</td>
                <td style={{ padding: '13px 16px', color: subColor, fontSize: 12 }}>{c.type}</td>
                <td style={{ padding: '13px 16px', color: subColor, fontSize: 12, maxWidth: 160 }}>{c.audience}</td>
                <td style={{ padding: '13px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{c.sent?.toLocaleString() ?? '—'}</td>
                <td style={{ padding: '13px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: c.tap ? 'var(--mint)' : subColor, fontWeight: c.tap ? 500 : 400 }}>{c.tap ?? '—'}</td>
                <td style={{ padding: '13px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{c.revenue ?? '—'}</td>
                <td style={{ padding: '13px 16px', fontSize: 12, color: subColor }}>{c.date ?? '—'}</td>
                <td style={{ padding: '13px 16px' }}><window.StatusPill status={c.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <window.EmptyState icon="bell-off" title={`No ${filter.toLowerCase()} campaigns`} description="Create your first campaign to start driving revenue from push notifications." action={<window.Button size="sm" onClick={() => setComposerOpen(true)}>New campaign →</window.Button>} />
        )}
      </div>

      <CampaignComposer open={composerOpen} onClose={() => setComposerOpen(false)} persona={persona} />
    </div>
  );
};

window.CampaignsScreen = CampaignsScreen;
