// screen-overview.jsx — Dashboard home: KPIs, checklist, recent campaigns, quick actions
// Exports: OverviewScreen

const CHECKLIST_ITEMS = [
  { id: 'connect',  label: 'Connect your Shopify store',      done: true,  screen: null },
  { id: 'theme',    label: 'Choose an app theme',              done: true,  screen: 'editor' },
  { id: 'preview',  label: 'Preview your app',                 done: true,  screen: 'editor' },
  { id: 'push',     label: 'Set up push notifications',        done: false, screen: 'campaigns' },
  { id: 'publish',  label: 'Publish to App Store & Google Play', done: false, screen: 'publishing' },
];

const RECENT_CAMPAIGNS_NOUR = [
  { id: 1, name: 'Summer Flash Sale', audience: 'All subscribers', sent: '1,240', tap: '18.4%', revenue: 'EGP 4,380', status: 'sent' },
  { id: 2, name: 'New arrivals — Linen edit', audience: 'VIP customers', sent: '—', tap: '—', revenue: '—', status: 'scheduled' },
  { id: 3, name: 'Cart abandonment · 1h', audience: 'Abandoned carts', sent: '312', tap: '22.1%', revenue: 'EGP 1,840', status: 'live' },
];

const RECENT_CAMPAIGNS_MARCUS = [
  { id: 1, name: 'Studio Speaker launch', audience: 'All subscribers', sent: '3,847', tap: '12.6%', revenue: '$14,200', status: 'sent' },
  { id: 2, name: 'Weekend deal — earbuds', audience: 'Segments: Deal hunters', sent: '1,920', tap: '9.8%', revenue: '$6,400', status: 'sent' },
  { id: 3, name: 'Back-to-school promo', audience: 'All subscribers', sent: '—', tap: '—', revenue: '—', status: 'scheduled' },
];

const OverviewScreen = ({ persona, onNav, tweaks }) => {
  const { dark } = tweaks;
  const campaigns = persona.id === 'nour' ? RECENT_CAMPAIGNS_NOUR : RECENT_CAMPAIGNS_MARCUS;
  const s = persona.stats;
  const fmt = (n) => n >= 1000 ? `${(n/1000).toFixed(1)}k` : n;
  const completedCount = CHECKLIST_ITEMS.filter(c => c.done).length;
  const allDone = completedCount === CHECKLIST_ITEMS.length;

  const greeting = () => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 17) return 'Good afternoon';
    return 'Good evening';
  };

  const cardStyle = { background: dark ? 'rgba(255,255,255,0.06)' : 'var(--white)', border: `1px solid ${dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)'}`, borderRadius: 12 };
  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: 32, maxWidth: 1100 }}>

      {/* Greeting */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24 }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, marginBottom: 6 }}>{greeting()}</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 38, lineHeight: 1.0, letterSpacing: '-0.02em', color: textColor, margin: 0 }}>
            {persona.id === 'nour' ? 'مرحبا, Nour.' : `Back, Marcus.`}
          </h1>
          <div style={{ fontSize: 14, color: subColor, marginTop: 8 }}>
            {persona.id === 'nour'
              ? `Your app has ${fmt(s.installs)} installs and ${s.trialDays || '18'} trial days remaining.`
              : `Your app is live. ${fmt(s.installs)} installs this month, up 23%.`}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          <window.Button variant="secondary" size="sm" icon="eye" onClick={() => onNav('editor')}>Preview app</window.Button>
          <window.Button size="sm" icon="bell" onClick={() => onNav('campaigns')}>New campaign</window.Button>
        </div>
      </div>

      {/* KPI cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { label: 'App installs · 30d', value: fmt(s.installs), delta: '+23%', dir: 'up', sub: null },
          { label: 'Sessions · 30d', value: fmt(s.sessions), delta: '+18%', dir: 'up', sub: null },
          { label: 'Conversion rate', value: `${s.conversion}%`, delta: '+0.4pp', dir: 'up', sub: 'vs mobile web' },
          { label: 'Push revenue · 30d', value: persona.id === 'nour' ? `EGP ${fmt(s.revenue)}` : `$${fmt(s.revenue)}`, delta: null, sub: `${s.pushSent} campaigns · ${s.pushOpen} open rate` },
        ].map((k, i) => (
          <div key={i} style={{ ...cardStyle, padding: 20 }}>
            <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: subColor, fontWeight: 500, marginBottom: 10 }}>{k.label}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 34, lineHeight: 1, letterSpacing: '-0.02em', color: i === 3 ? 'var(--honey)' : textColor, marginBottom: 8 }}>{k.value}</div>
            {k.delta && <div style={{ fontSize: 12, color: 'var(--mint)', fontWeight: 500 }}>↗ {k.delta}</div>}
            {k.sub && <div style={{ fontSize: 11, color: subColor }}>{k.sub}</div>}
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: allDone ? '1fr' : '320px 1fr', gap: 20 }}>

        {/* Onboarding checklist */}
        {!allDone && (
          <div style={{ ...cardStyle, padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Getting started</div>
                <div style={{ fontSize: 12, color: subColor, marginTop: 2 }}>{completedCount} of {CHECKLIST_ITEMS.length} complete</div>
              </div>
              <div style={{ width: 40, height: 40, position: 'relative' }}>
                <svg viewBox="0 0 40 40" style={{ width: 40, height: 40, transform: 'rotate(-90deg)' }}>
                  <circle cx="20" cy="20" r="17" fill="none" stroke="var(--sand-100)" strokeWidth="3" />
                  <circle cx="20" cy="20" r="17" fill="none" stroke="var(--honey)" strokeWidth="3"
                    strokeDasharray={`${(completedCount / CHECKLIST_ITEMS.length) * 107} 107`}
                    strokeLinecap="round" style={{ transition: 'stroke-dasharray 500ms var(--ease)' }} />
                </svg>
                <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600, color: textColor }}>{Math.round((completedCount / CHECKLIST_ITEMS.length) * 100)}%</div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {CHECKLIST_ITEMS.map(item => (
                <div key={item.id} onClick={() => item.screen && onNav(item.screen)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 8, cursor: item.screen ? 'pointer' : 'default', background: !item.done ? (dark ? 'rgba(232,184,58,0.08)' : 'var(--honey-tint)') : 'transparent', border: !item.done ? '1px solid var(--honey-tint)' : '1px solid transparent', transition: 'background 150ms' }}>
                  <div style={{ width: 20, height: 20, borderRadius: '50%', background: item.done ? 'var(--mint)' : 'var(--white)', border: `2px solid ${item.done ? 'var(--mint)' : 'var(--hairline-bold)'}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {item.done && <i data-lucide="check" style={{ width: 11, height: 11, color: 'white' }}></i>}
                  </div>
                  <span style={{ fontSize: 13, color: item.done ? subColor : textColor, textDecoration: item.done ? 'line-through' : 'none', flex: 1, fontWeight: !item.done ? 500 : 400 }}>{item.label}</span>
                  {!item.done && item.screen && <i data-lucide="arrow-right" style={{ width: 13, height: 13, color: 'var(--honey-deep)' }}></i>}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Recent campaigns */}
        <div style={{ ...cardStyle, padding: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Recent campaigns</div>
            <window.Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => onNav('campaigns')}>View all</window.Button>
          </div>

          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr>
                {['Campaign', 'Audience', 'Sent', 'Tap-through', 'Revenue', 'Status'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '0 12px 10px 0', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, borderBottom: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'var(--hairline)'}` }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {campaigns.map((c, i) => (
                <tr key={c.id} style={{ borderBottom: i < campaigns.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}>
                  <td style={{ padding: '12px 12px 12px 0', fontWeight: 500, color: textColor }}>{c.name}</td>
                  <td style={{ padding: '12px 12px 12px 0', color: subColor, fontSize: 12 }}>{c.audience}</td>
                  <td style={{ padding: '12px 12px 12px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{c.sent}</td>
                  <td style={{ padding: '12px 12px 12px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: c.tap !== '—' ? 'var(--mint)' : subColor }}>{c.tap}</td>
                  <td style={{ padding: '12px 12px 12px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{c.revenue}</td>
                  <td style={{ padding: '12px 0 12px 0' }}><window.StatusPill status={c.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>

          <div style={{ marginTop: 16, paddingTop: 16, borderTop: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'var(--hairline)'}` }}>
            <window.Button variant="secondary" size="sm" icon="plus" onClick={() => onNav('campaigns')}>New campaign</window.Button>
          </div>
        </div>
      </div>

      {/* App status bar */}
      <div style={{ ...cardStyle, padding: '16px 24px', display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <i data-lucide="smartphone" style={{ width: 16, height: 16, color: subColor }}></i>
          <span style={{ fontSize: 12, fontWeight: 500, color: textColor }}>{persona.appName}</span>
        </div>
        <div style={{ width: 1, height: 16, background: 'var(--hairline)', flexShrink: 0 }}></div>
        {[
          { label: 'iOS', status: persona.id === 'nour' ? 'In review' : 'Live', ok: persona.id !== 'nour' },
          { label: 'Android', status: persona.id === 'nour' ? 'Building' : 'Live', ok: persona.id !== 'nour' },
          { label: 'Data sync', status: 'Synced', ok: true },
          { label: 'Last sync', status: '2 min ago', ok: true },
        ].map(item => (
          <div key={item.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
            <span style={{ color: subColor }}>{item.label}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: item.ok ? 'var(--mint)' : 'var(--amber)' }}></div>
              <span style={{ color: item.ok ? 'var(--mint)' : 'var(--amber)', fontWeight: 500 }}>{item.status}</span>
            </div>
          </div>
        ))}
        <div style={{ flex: 1 }}></div>
        <window.Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => onNav('publishing')}>View publishing status</window.Button>
      </div>
    </div>
  );
};

window.OverviewScreen = OverviewScreen;
