// ============================================================
// ShieldTech Secret Weapon — Mission screens
// Today's Mission · Task Slide Deck · Outcome · AI Debrief
// ============================================================

// ─────────────────────────────────────────────────────────────
// LOGIN / ONBOARDING
// ─────────────────────────────────────────────────────────────
function ScreenLogin({ onSignIn }) {
  const [googleConnected, setGoogleConnected] = React.useState(false);
  return (
    <div style={{ padding: '0 0 120px', color: C.fg1, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Brand mark */}
      <div style={{ padding: '40px 24px 20px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 18 }}>
        <div style={{
          width: 84, height: 84, borderRadius: 24,
          background: 'linear-gradient(135deg, rgba(0,163,255,0.18), rgba(168,85,247,0.12))',
          border: '1px solid rgba(0,163,255,0.35)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 32px rgba(0,163,255,0.32)',
          position: 'relative',
        }}>
          <img src="assets/logo-shield.png" alt="ShieldTech" style={{ width: 56, height: 56, objectFit: 'contain', filter: 'drop-shadow(0 2px 10px rgba(0,163,255,0.45))' }} />
        </div>
        <div>
          <div style={{ font: '500 11px/1 Inter, system-ui, sans-serif', letterSpacing: '0.24em', color: C.blueElectric, textTransform: 'uppercase' }}>ShieldTech</div>
          <div style={{ font: '700 32px/1.05 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '0.02em', marginTop: 6, textTransform: 'uppercase' }}>Secret Weapon</div>
          <div style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 10, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>
            Your private AI sales assistant for leads, bids, follow-ups, and growth.
          </div>
        </div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999,
          background: 'rgba(168,85,247,0.10)', border: '1px solid rgba(168,85,247,0.30)',
          color: C.assistantSoft, font: '600 11px/1 Inter, system-ui, sans-serif', letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>
          <Icon name="lock" size={12} color={C.assistantSoft}/> Built for ShieldTech only
        </span>
      </div>

      {/* Sign in card */}
      <div style={{ padding: '8px 16px 0' }}>
        <GlassCard style={{ padding: 20 }}>
          <div style={{ font: '700 17px/1.2 Rajdhani, "Inter", system-ui, sans-serif' }}>Sign in</div>
          <div style={{ font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 4 }}>
            Use the Google account that owns ShieldTech’s Tasks + Calendar.
          </div>
          <button onClick={() => window.ShieldTechApi?.connectGoogle?.()} type="button" style={{
            marginTop: 14, width: '100%', height: 52, borderRadius: 16,
            background: '#FFFFFF', color: '#1F2937', border: 0,
            font: '600 16px/1 Inter, system-ui, sans-serif',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, cursor: 'pointer',
            boxShadow: '0 6px 20px rgba(255,255,255,0.08)',
          }}>
            <svg width="20" height="20" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.84 14.09a6.6 6.6 0 0 1 0-4.18V7.07H2.18a11 11 0 0 0 0 9.86l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/></svg>
            Continue with Google
          </button>
          <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="lock" size={14} color={C.fgMuted}/>
            <span style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted }}>
              Connect Google to sync Tasks and Calendar.
            </span>
          </div>
        </GlassCard>
      </div>

      {/* Setup checklist */}
      <div style={{ padding: '16px 16px 0' }}>
        <div style={{ padding: '8px 4px' }}><Caption>Setup</Caption></div>
        <Card style={{ padding: 8 }}>
          <SetupRow icon="google" tint="rgba(0,163,255,0.10)" tintIcon={C.blueElectric}
            title="Google account" detail={googleConnected ? 'daniel@shieldtechpa.com' : 'Not connected'}
            state={googleConnected ? 'connected' : 'disconnected'} stateLabel={googleConnected ? 'Connected' : 'Connect'}/>
          <SetupRow icon="check" tint="rgba(34,197,94,0.10)" tintIcon="#86EFAC"
            title="Google Tasks" detail="Auto-create on task completion"
            state={googleConnected ? 'connected' : 'disconnected'} stateLabel={googleConnected ? 'Ready' : 'Pending'}/>
          <SetupRow icon="calendar" tint="rgba(0,163,255,0.10)" tintIcon={C.blueElectric}
            title="Google Calendar" detail="Auto-create follow-up reminders"
            state={googleConnected ? 'connected' : 'disconnected'} stateLabel={googleConnected ? 'Ready' : 'Pending'}/>
          <SetupRow icon="sparkles" tint="rgba(168,85,247,0.10)" tintIcon={C.assistantSoft}
            title="OpenRouter" detail="Debrief + email drafts"
            state="pending" stateLabel="Check" last/>
        </Card>
      </div>

      {/* Promise list */}
      <div style={{ padding: '16px 24px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { i: 'play', t: 'Start every day with a guided mission' },
          { i: 'phone', t: 'One task, one button — act, then move on' },
          { i: 'sparkles', t: 'AI debriefs every outcome into the next step' },
        ].map((p, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: C.cardElev, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: C.blueElectric }}>
              <Icon name={p.i} size={14}/>
            </div>
            <span style={{ font: '500 14px/20px Inter, system-ui, sans-serif', color: C.fg2 }}>{p.t}</span>
          </div>
        ))}
      </div>

      {/* Sticky bottom CTA */}
      <div style={{ marginTop: 'auto', padding: '20px 16px 24px' }}>
        <PrimaryButton full glow leadingIcon="zap" onClick={onSignIn}>
          Enter command center
        </PrimaryButton>
        <div style={{ textAlign: 'center', marginTop: 10, font: '400 11px/16px Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          PWA v2.4.1 · production
        </div>
      </div>
    </div>
  );
}

function SetupRow({ icon, tint, tintIcon, title, detail, state, stateLabel, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 10px',
      borderBottom: last ? 'none' : `1px solid ${C.border}`,
    }}>
      <div style={{ width: 32, height: 32, borderRadius: 10, background: tint, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
        <Icon name={icon} size={16} color={tintIcon}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{title}</div>
        <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>{detail}</div>
      </div>
      <SyncChip state={state} label={stateLabel} size="sm"/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TODAY — Mission summary
// ─────────────────────────────────────────────────────────────
function ScreenToday({ goto }) {
  return (
    <div className="slide-up" style={{ padding: '0 0 120px', color: C.fg1 }}>
      <MobileHeader subtitle="TUESDAY · MAY 28" title="Your mission is ready."
        leading={
          <div style={{ width: 40, height: 40, borderRadius: 12, background: C.cardElev, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src="assets/logo-shield.png" style={{ width: 26, height: 26, objectFit: 'contain' }} alt="" />
          </div>
        }
        trailing={
          <button onClick={() => goto('assistant')} style={{
            width: 40, height: 40, borderRadius: 12, background: 'rgba(168,85,247,0.10)',
            border: '1px solid rgba(168,85,247,0.30)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', position: 'relative', boxShadow: '0 0 14px rgba(168,85,247,0.24)',
          }}>
            <Icon name="sparkles" size={18} color={C.assistantSoft}/>
            <span style={{ position: 'absolute', top: 6, right: 6, width: 8, height: 8, borderRadius: 999, background: C.danger, border: '2px solid #05070A' }}/>
          </button>
        }
      />
      <div style={{ padding: '4px 20px 0', font: '400 16px/22px Inter, system-ui, sans-serif', color: C.fg2 }}>
        Start with Hot follow-ups. <span style={{ color: '#FCD34D', fontWeight: 600 }}>4 haven’t been touched in 8+ days.</span>
      </div>

      {/* Hero mission card */}
      <div style={{ padding: '20px' }}>
        <GlassCard style={{ padding: 20, overflow: 'hidden' }}>
          <span className="scan-line"/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <ProgressRing value={0} total={12} size={96}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <Caption>Daily sales score · <span style={{ color: '#FCD34D' }}>0/100</span></Caption>
              <div style={{ font: '700 24px/1.05 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '0.005em', marginTop: 4 }}>
                12 tasks · 2h 40m
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                <StatusPill kind="hot" size="sm">4 Hot</StatusPill>
                <StatusPill kind="warm" size="sm">5 Warm</StatusPill>
                <StatusPill kind="approval" size="sm">3 Approvals</StatusPill>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 18 }}>
            <PrimaryButton full glow leadingIcon="play" onClick={() => goto('task')}>Start mission</PrimaryButton>
          </div>
        </GlassCard>
      </div>

      {/* Top 3 money actions */}
      <SectionHeader title="Top 3 money actions" right={<Caption>By expected value</Caption>}/>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { rank: 1, label: 'Call Hot follow-ups first', sub: '4 leads cooling — Penn Valley, Bayonne, Sigma, Lehigh', value: '$340K open' },
          { rank: 2, label: 'Push the active bid + vendor work', sub: 'Tri-County bid decision · Wachter W2 question', value: '8 hrs at stake' },
          { rank: 3, label: 'Convert warm contacts before admin', sub: 'Keystone pricing reply · Bayonne walkthrough confirm', value: '2 deals warm' },
        ].map(m => (
          <Card key={m.rank} hover style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: 'linear-gradient(135deg, rgba(0,163,255,0.20), rgba(0,163,255,0.05))', border: `1px solid ${C.border}`, color: C.blueElectric, font: '700 14px/1 Rajdhani, "Inter", system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>{m.rank}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{m.label}</div>
              <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 2 }}>{m.sub}</div>
            </div>
            <div style={{ font: '700 11px/1 Inter, system-ui, sans-serif', color: C.blueElectric, letterSpacing: '0.04em', flex: 'none' }}>{m.value}</div>
          </Card>
        ))}
      </div>

      {/* Stat row */}
      <SectionHeader title="Day at a glance"/>
      <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <MiniStat label="Calls today" value="0 / 12" sub="Behind pace" warn/>
        <MiniStat label="Hot follow-ups" value="4" sub="2 untouched 8+ days"/>
        <MiniStat label="Bids due" value="2" sub="Tri-County · Jun 4"/>
        <MiniStat label="Approvals" value="3" sub="1 email · 1 bid · 1 dead"/>
      </div>

      {/* Top bid opportunities — matched to selected trades */}
      <TodayOpportunities goto={goto}/>

      {/* Next up preview */}
      <SectionHeader title="Next up" right={<Caption>3 of 12 →</Caption>}/>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {TASKS.slice(0, 3).map((t, i) => (
          <Card key={t.id} hover onClick={() => goto('task', i)} style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <StatusPill kind={t.lead} size="sm">{cap(t.lead)}</StatusPill>
              <span style={{ font: '500 11px/1 Inter, system-ui, sans-serif', color: C.fgMuted }}>{t.type}</span>
              <Caption style={{ marginLeft: 'auto' }}>{t.dueLabel.replace('Due ', '')}</Caption>
            </div>
            <div style={{ font: '700 17px/1.2 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.005em' }}>{t.company}</div>
            <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 3 }}>{t.opportunity} · {t.city}</div>
          </Card>
        ))}
      </div>

      {/* Pace nudge */}
      <div style={{ padding: '20px' }}>
        <Card style={{ padding: 16, borderColor: '#92400E', background: '#1A1306' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: '#3A2506', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Icon name="flame" size={18} color="#FCD34D"/>
            </div>
            <div>
              <div style={{ font: '700 15px/1.2 Inter, system-ui, sans-serif', color: '#FCD34D' }}>You’re behind on calls.</div>
              <div style={{ font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 4 }}>
                Do the next 3 before admin work. The Penn Valley walkthrough goes cold by tomorrow.
              </div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

function MiniStat({ label, value, sub, warn }) {
  return (
    <Card style={{ padding: 14 }}>
      <Caption>{label}</Caption>
      <div className="tabular" style={{ font: '700 24px/1 Rajdhani, "Inter", system-ui, sans-serif', marginTop: 6, color: warn ? '#FCD34D' : C.fg1 }}>{value}</div>
      <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 4 }}>{sub}</div>
    </Card>
  );
}

function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); }

// Compact "top opportunities" strip for Today — matched to selected trades.
function TodayOpportunities({ goto }) {
  const [trades] = useSelectedTrades();
  const top = React.useMemo(() => {
    const all = [...BIDS, ...INBOX_OPPS].map(o => enrichOpportunity(o, trades));
    return rankOpportunities(all.filter(o => o.isFit)).slice(0, 2);
  }, [trades]);

  return (
    <>
      <SectionHeader title="Top bid opportunities"
        right={<button onClick={() => goto('bids')} type="button" style={{ background: 'transparent', border: 0, color: C.blueElectric, font: '600 12px/1 Inter, system-ui, sans-serif', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 3 }}>View all <Icon name="arrowRight" size={12} color={C.blueElectric}/></button>}/>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {top.map(o => {
          const fitColor = o.fit >= 75 ? '#86EFAC' : o.fit >= 50 ? '#FCD34D' : '#FCA5A5';
          return (
            <Card key={o.id} hover onClick={() => goto('bids')} style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
                    {o.labels[0] && <StatusPill kind={o.labels[0].tone} size="sm" dot={false}>{o.labels[0].t}</StatusPill>}
                    <span style={{ font: '500 10px/1 Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{o.state} · {o.market}</span>
                  </div>
                  <div style={{ font: '700 15px/1.25 Inter, system-ui, sans-serif', color: C.fg1, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{o.name}</div>
                  <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginTop: 8 }}>
                    {o.matchedLabels.slice(0, 3).map(t => (
                      <span key={t} style={{ padding: '3px 8px', borderRadius: 999, background: 'rgba(0,163,255,0.08)', border: '1px solid rgba(0,163,255,0.22)', color: C.blueElectric, font: '600 10px/1 Inter, system-ui, sans-serif' }}>{t}</span>
                    ))}
                  </div>
                </div>
                <div style={{ textAlign: 'center', flex: 'none' }}>
                  <div className="tabular" style={{ font: '700 22px/1 Rajdhani, "Inter", system-ui, sans-serif', color: fitColor }}>{o.fit}</div>
                  <div style={{ font: '500 8px/1 Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.1em', marginTop: 3 }}>FIT</div>
                </div>
              </div>
            </Card>
          );
        })}
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// TASK SLIDE DECK
// ─────────────────────────────────────────────────────────────
function ScreenTask({ goto, taskIndex = 0, setTaskIndex }) {
  const t = TASKS[taskIndex];
  const [scriptOpen, setScriptOpen] = React.useState(false);
  const [view, setView] = React.useState(() => localStorage.getItem('stw:taskview') || 'deck');
  React.useEffect(() => { localStorage.setItem('stw:taskview', view); }, [view]);
  const telHref = t.phoneTelHref || (() => {
    const digits = String(t.phone || '').replace(/[^\d+]/g, '');
    if (/^\+1\d{10}$/.test(digits)) return `tel:${digits}`;
    if (/^1\d{10}$/.test(digits)) return `tel:+${digits}`;
    if (/^\d{10}$/.test(digits)) return `tel:+1${digits}`;
    return null;
  })();

  const viewToggle = (
    <div style={{ display: 'flex', gap: 2, padding: 3, borderRadius: 10, background: C.card, border: `1px solid ${C.border}` }}>
      {[{ id: 'deck', icon: 'layers' }, { id: 'calendar', icon: 'calendar' }].map(v => {
        const on = view === v.id;
        return (
          <button key={v.id} onClick={() => setView(v.id)} type="button" title={v.id === 'deck' ? 'Deck view' : 'Calendar view'} style={{
            width: 32, height: 28, borderRadius: 8, cursor: 'pointer',
            background: on ? C.cardElev : 'transparent',
            border: on ? `1px solid ${C.borderStrong}` : '1px solid transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
          }}>
            <Icon name={v.icon} size={16} color={on ? C.blueElectric : C.fgMuted}/>
          </button>
        );
      })}
    </div>
  );

  if (view === 'calendar') {
    return (
      <div className="slide-right" style={{ padding: '0 0 120px', color: C.fg1 }}>
        <BackRow onBack={() => goto('today')} label="Mission" center="Schedule" trailing={viewToggle}/>
        <TaskCalendar goto={goto} setTaskIndex={setTaskIndex} setView={setView}/>
      </div>
    );
  }

  return (
    <div className="slide-right" style={{ padding: '0 0 220px', color: C.fg1 }}>
      <BackRow onBack={() => goto('today')} label="Mission"
        center={`Task ${taskIndex + 1} of ${TASKS.length}`}
        trailing={viewToggle}/>

      {/* Slide progress dots */}
      <div style={{ padding: '0 20px 8px', display: 'flex', gap: 4 }}>
        {TASKS.map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 3, borderRadius: 999,
            background: i < taskIndex ? C.blueElectric : i === taskIndex ? C.blue : C.cardElev,
            boxShadow: i === taskIndex ? '0 0 8px rgba(0,163,255,0.6)' : 'none',
          }}/>
        ))}
      </div>

      {/* Main card */}
      <div style={{ padding: '8px 20px 0' }}>
        <Card style={{ padding: 22, overflow: 'hidden' }}>
          <span className="scan-line"/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
            <StatusPill kind={t.lead}>{cap(t.lead)}</StatusPill>
            <PriorityPill level={t.priority}/>
            <span style={{ font: '600 12px/1 Inter, system-ui, sans-serif', color: C.assistantSoft, padding: '4px 9px', borderRadius: 999, background: 'rgba(168,85,247,0.10)', border: '1px solid rgba(168,85,247,0.30)' }}>
              {t.taskType}
            </span>
            <Caption style={{ marginLeft: 'auto' }}>{t.dueLabel}</Caption>
          </div>

          <div style={{ font: '500 13px/1 Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{t.type}</div>
          <div style={{ font: '700 26px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.015em', marginTop: 6 }}>{t.company}</div>
          <div style={{ font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 4 }}>{t.opportunity} · {t.city}</div>

          {/* Why row */}
          <div style={{ marginTop: 14, padding: '10px 14px', background: 'rgba(0,163,255,0.06)', border: '1px solid rgba(0,163,255,0.18)', borderRadius: 14 }}>
            <Caption color={C.blue}>Why now</Caption>
            <div style={{ font: '500 14px/20px Inter, system-ui, sans-serif', color: C.fg1, marginTop: 4 }}>{t.why}</div>
          </div>

          {/* Goal */}
          <div style={{ marginTop: 12, padding: '14px 16px', background: C.cardElev, borderRadius: 16 }}>
            <Caption color={C.blue}>Goal</Caption>
            <div style={{ font: '600 15px/22px Inter, system-ui, sans-serif', color: C.fg1, marginTop: 4 }}>{t.goal}</div>
          </div>

          {/* Contact route */}
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 999, background: C.cardElev, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Icon name="user" size={20} color={C.fgMuted}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ font: '600 15px/1.2 Inter, system-ui, sans-serif' }}>Ask for <span style={{ color: C.blueElectric }}>{t.contactName}</span></div>
              <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2 }}>
                {t.contactTitle} · <span style={{ fontFamily: 'JetBrains Mono, ui-monospace, monospace', fontWeight: 500 }}>{t.phone}</span>
              </div>
            </div>
          </div>

          {/* Script (collapsible) */}
          {t.script && (
            <>
              <button onClick={() => setScriptOpen(!scriptOpen)} type="button" style={{
                marginTop: 14, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 14px', background: 'transparent', border: `1px solid ${C.border}`, borderRadius: 14,
                color: C.fg1, font: '600 14px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
              }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <Icon name="mic" size={16} color={C.assistant}/> Call script
                </span>
                <Icon name={scriptOpen ? 'chevronDown' : 'chevron'} size={18} color={C.fgMuted}/>
              </button>
              {scriptOpen && (
                <div style={{ marginTop: 8, padding: 14, background: 'rgba(168,85,247,0.06)', border: '1px solid rgba(168,85,247,0.22)', borderRadius: 14, font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2 }}>
                  “{t.script}”
                </div>
              )}
            </>
          )}

          {/* Sync row */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 14 }}>
            <SyncChip state="pending" label="Google Task pending"/>
            <SyncChip state="pending" label="Calendar pending"/>
          </div>
        </Card>
      </div>

      {/* Slide nav */}
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button disabled={taskIndex === 0} onClick={() => setTaskIndex(Math.max(0, taskIndex - 1))} style={{
          background: 'transparent', color: taskIndex === 0 ? C.fgMuted : C.fg1, border: 0,
          display: 'inline-flex', alignItems: 'center', gap: 4, cursor: taskIndex === 0 ? 'not-allowed' : 'pointer',
          font: '600 14px/1 Inter, system-ui, sans-serif',
        }}>
          <Icon name="chevronLeft" size={18}/>Prev
        </button>
        <button disabled={taskIndex >= TASKS.length - 1} onClick={() => setTaskIndex(Math.min(TASKS.length - 1, taskIndex + 1))} style={{
          background: 'transparent', color: taskIndex >= TASKS.length - 1 ? C.fgMuted : C.fg1, border: 0,
          display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
          font: '600 14px/1 Inter, system-ui, sans-serif',
        }}>
          Skip<Icon name="chevron" size={18}/>
        </button>
      </div>

      {/* Sticky bottom actions */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 92, padding: '12px 16px 0',
        background: 'linear-gradient(to top, rgba(5,7,10,0.96) 60%, rgba(5,7,10,0))', zIndex: 50,
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 8 }}>
          {telHref ? (
            <PrimaryButton glow leadingIcon="phone" href={telHref}
              onClick={async (event) => {
                event.preventDefault();
                try {
                  const data = await window.ShieldTechApi?.startCall?.(t.id);
                  window.location.href = data?.telHref || telHref;
                  setTimeout(() => goto('outcome', taskIndex), 80);
                } catch (error) {
                  window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'START_CALL_FAILED' } }));
                }
              }} full>
              Make call
            </PrimaryButton>
          ) : (
            <SecondaryButton leadingIcon="phone" onClick={() => {
              navigator.clipboard?.writeText(t.phone || '');
              window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: 'No valid phone number saved. Route text copied if available.', code: 'NO_VALID_PHONE' } }));
            }} full>
              No phone saved
            </SecondaryButton>
          )}
          <SecondaryButton leadingIcon="mail"
            href={`mailto:${t.email}?subject=${encodeURIComponent(`ShieldTech — ${t.opportunity}`)}`}
            onClick={() => goto('outcome', taskIndex)} full>
            Email
          </SecondaryButton>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <ResultButton onClick={() => goto('outcome', taskIndex)}>Snooze</ResultButton>
          <ResultButton onClick={() => goto('outcome', taskIndex)}>Tomorrow</ResultButton>
          <ResultButton tone="warn" onClick={() => goto('outcome', taskIndex)}>Not a fit</ResultButton>
        </div>
      </div>
    </div>
  );
}

function ResultButton({ children, onClick, tone = 'default' }) {
  const map = {
    default: { bg: C.cardElev, fg: C.fg1, br: C.border },
    warn:    { bg: '#3B0D0D', fg: '#FCA5A5', br: '#7F1D1D' },
  }[tone];
  return (
    <button onClick={onClick} type="button" style={{
      flex: 1, height: 44, borderRadius: 12,
      background: map.bg, color: map.fg, border: `1px solid ${map.br}`,
      font: '600 13px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
    }}>{children}</button>
  );
}

// ─────────────────────────────────────────────────────────────
// OUTCOME — "what happened?" capture
// ─────────────────────────────────────────────────────────────
function ScreenOutcome({ goto, taskIndex = 0 }) {
  const t = TASKS[taskIndex];
  const [outcome, setOutcome] = React.useState('completed');
  const [note, setNote] = React.useState('Mike picked up. Confirmed Thu 10 AM walkthrough. He wants me to bring the Avigilon rep and the channel pricing.');
  const [chips, setChips] = React.useState(['Got direct email', 'Active project mentioned']);
  const [saving, setSaving] = React.useState(false);

  const outcomes = [
    { id: 'completed', label: 'Completed', tone: 'success' },
    { id: 'voicemail', label: 'Left voicemail', tone: 'default' },
    { id: 'noanswer', label: 'No answer', tone: 'default' },
    { id: 'email', label: 'Asked for email', tone: 'default' },
    { id: 'wrong', label: 'Wrong contact', tone: 'warn-soft' },
    { id: 'unfit', label: 'Not a fit', tone: 'warn' },
    { id: 'snooze', label: 'Snooze', tone: 'muted' },
    { id: 'tomorrow', label: 'Tomorrow', tone: 'muted' },
  ];

  const quickChips = [
    'Got direct email', 'Left voicemail', 'Asked for capability statement',
    'Call back later', 'Wrong contact', 'No current work',
    'Active project mentioned', 'Vendor packet requested', 'Bid list contact found',
  ];

  const toneMap = {
    success: { bg: '#052E16', fg: '#86EFAC', br: '#166534' },
    'warn-soft': { bg: '#3A2506', fg: '#FCD34D', br: '#92400E' },
    warn: { bg: '#3B0D0D', fg: '#FCA5A5', br: '#7F1D1D' },
    default: { bg: C.cardElev, fg: C.fg1, br: C.border },
    muted: { bg: C.cardElev, fg: C.fgMuted, br: C.border },
  };

  const toggleChip = (c) => setChips(p => p.includes(c) ? p.filter(x => x !== c) : [...p, c]);

  return (
    <div className="slide-right" style={{ padding: '0 0 140px', color: C.fg1 }}>
      <BackRow onBack={() => goto('task', taskIndex)} label="Back" center="Step 1 of 2"/>

      <div style={{ padding: '12px 20px 0' }}>
        <Caption>{t.company}</Caption>
        <div style={{ font: '700 28px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em', marginTop: 8 }}>What happened?</div>
        <div style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
          Tap the closest match. I’ll do the paperwork.
        </div>
      </div>

      {/* Outcome buttons */}
      <div style={{ padding: '16px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {outcomes.map(o => {
          const m = toneMap[o.tone];
          const on = outcome === o.id;
          return (
            <button key={o.id} onClick={() => setOutcome(o.id)} type="button" style={{
              height: 52, borderRadius: 14,
              background: m.bg, color: m.fg, border: `1px solid ${on ? C.blueElectric : m.br}`,
              font: '600 14px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
              transition: 'all 120ms ease',
              boxShadow: on ? '0 0 18px rgba(0,163,255,0.32)' : 'none',
              outline: 'none', position: 'relative',
            }}>
              {o.label}
              {on && <span style={{ position: 'absolute', top: 6, right: 6, color: C.blueElectric }}><Icon name="check" size={12} strokeWidth={3}/></span>}
            </button>
          );
        })}
      </div>

      {/* Assistant prompts — quick chips */}
      <div style={{ padding: '20px 20px 0' }}>
        <Caption>Quick context</Caption>
        <div style={{ marginTop: 10, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {quickChips.map(c => {
            const on = chips.includes(c);
            return (
              <button key={c} onClick={() => toggleChip(c)} type="button" style={{
                padding: '7px 12px', borderRadius: 999,
                background: on ? 'rgba(0,163,255,0.12)' : C.cardElev,
                color: on ? C.blueElectric : C.fg2,
                border: `1px solid ${on ? 'rgba(0,163,255,0.36)' : C.border}`,
                font: '500 12px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
              }}>{c}</button>
            );
          })}
        </div>
      </div>

      {/* Note */}
      <div style={{ padding: '16px 20px 0' }}>
        <Caption>Note</Caption>
        <div style={{ marginTop: 8, padding: 14, background: C.card, border: `1px solid ${C.border}`, borderRadius: 18 }}>
          <textarea value={note} onChange={e => setNote(e.target.value)} rows={4}
            style={{ width: '100%', resize: 'none', background: 'transparent', border: 0, outline: 'none', color: C.fg1, font: '400 15px/22px Inter, system-ui, sans-serif' }}/>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
            <Caption>{note.split(' ').length} words · 8 sec</Caption>
            <button type="button" onClick={() => window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: 'Voice capture is not configured in this browser build. Type the note here and it will still save to the backend.', code: 'VOICE_NOT_CONFIGURED' } }))} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 12px', borderRadius: 999,
              background: 'rgba(168,85,247,0.12)', border: '1px solid rgba(168,85,247,0.32)', color: C.assistantSoft,
              font: '600 12px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
            }}>
              <Icon name="mic" size={14} color={C.assistantSoft}/>Voice note
            </button>
          </div>
        </div>
      </div>

      <div style={{ padding: '20px 20px 0' }}>
        <PrimaryButton full glow trailingIcon="arrowRight" disabled={saving} onClick={async () => {
          setSaving(true);
          try {
            await window.ShieldTechApi?.saveTaskOutcome?.(t.id, outcome, note, chips);
            goto('debrief', taskIndex);
          } catch (error) {
            window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'OUTCOME_FAILED' } }));
          } finally {
            setSaving(false);
          }
        }}>
          {saving ? 'Saving…' : 'Send to assistant'}
        </PrimaryButton>
        <div style={{ textAlign: 'center', marginTop: 10 }}>
          <button onClick={() => goto('today')} type="button" style={{ background: 'transparent', border: 0, color: C.fgMuted, font: '500 13px/1 Inter, system-ui, sans-serif', cursor: 'pointer' }}>
            Skip — finish later
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DEBRIEF — AI debrief result
// ─────────────────────────────────────────────────────────────
function ScreenDebrief({ goto, taskIndex = 0 }) {
  const t = TASKS[taskIndex];
  const [score, setScore] = React.useState(t.score);
  const [thinking, setThinking] = React.useState(true);
  const [debrief, setDebrief] = React.useState(() => window.ShieldTechApi?.state?.lastDebrief || null);

  React.useEffect(() => {
    const id = setTimeout(() => {
      setDebrief(window.ShieldTechApi?.state?.lastDebrief || null);
      setThinking(false);
    }, 900);
    return () => clearTimeout(id);
  }, []);

  return (
    <div className="slide-up" style={{ padding: '0 0 140px', color: C.fg1 }}>
      <BackRow onBack={() => goto('today')} label="Done" center="AI debrief"/>

      <div style={{ padding: '8px 20px 0' }}>
        <Card glow="purple" style={{ padding: 22, overflow: 'hidden' }}>
          {thinking && <span className="scan-line"/>}

          {/* Avatar row */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div className="glow-purple" style={{
              width: 36, height: 36, borderRadius: 12,
              background: 'rgba(168,85,247,0.14)', border: '1px solid rgba(168,85,247,0.40)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="sparkles" size={18} color={C.assistantSoft}/>
            </div>
            <Caption color={C.assistantSoft}>Assistant · {thinking ? 'thinking…' : 'just now'}</Caption>
            {thinking && <TypingDots/>}
          </div>

          {thinking ? (
            <div style={{ marginTop: 14 }}>
              <div className="ai-shimmer" style={{ font: '700 24px/1.15 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.015em' }}>
                Reading your note and the lead history…
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14 }}>
                <LoadingShimmer height={24}/>
                <LoadingShimmer height={24} style={{ width: '80%' }}/>
                <LoadingShimmer height={48}/>
              </div>
            </div>
          ) : (
            <>
              {debrief?.error ? (
                <div className="fade-in" style={{ marginTop: 14, padding: 14, background: '#1A1306', border: '1px solid #92400E', borderRadius: 14 }}>
                  <div style={{ font: '700 18px/1.2 Rajdhani, "Inter", system-ui, sans-serif', color: '#FCD34D' }}>Debrief setup required</div>
                  <div style={{ font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>{debrief.error.message}</div>
                </div>
              ) : (
              <>
              <div className="fade-in" style={{ font: '700 26px/1.15 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.015em', marginTop: 14 }}>
                {debrief?.outcome_summary || 'Debrief result saved.'}
              </div>
              <div className="fade-in" style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 8 }}>
                {debrief?.recommended_improvement || 'No external Google, calendar, or email action is claimed here unless its backend route actually completed.'}
              </div>

              <div className="fade-in" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 16 }}>
                <DebriefStat label="Lead status" valueNode={<StatusPill kind={(debrief?.lead_status_after || 'Warm').toLowerCase()}>{debrief?.lead_status_after || 'Warm'}</StatusPill>}/>
                <DebriefStat label="Lead score" valueNode={
                  <span style={{ font: '700 22px/1 Rajdhani, "Inter", system-ui, sans-serif', fontVariantNumeric: 'tabular-nums' }}>
                    {debrief?.lead_score_after ?? score}
                  </span>
                }/>
                <DebriefStat label="Next action" value={debrief?.next_action || 'Review saved outcome'}/>
                <DebriefStat label="Next follow-up" value={debrief?.next_follow_up_at ? new Date(debrief.next_follow_up_at).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : 'None set'}/>
              </div>

              <div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 16 }}>
                <CheckRow pending>Google Task request prepared only if Google route succeeds.</CheckRow>
                <CheckRow pending>Calendar reminder request prepared only if Google route succeeds.</CheckRow>
                <CheckRow pending>{debrief?.email_draft?.needed ? 'Email draft prepared for approval.' : 'No email draft requested.'}</CheckRow>
              </div>

              <div className="fade-in" style={{ marginTop: 16, padding: '14px 16px', background: 'rgba(0,163,255,0.06)', border: '1px solid rgba(0,163,255,0.18)', borderRadius: 14 }}>
                <Caption color={C.blue}>Lesson learned</Caption>
                <div style={{ font: '500 14px/20px Inter, system-ui, sans-serif', color: C.fg1, marginTop: 4 }}>
                  {debrief?.lesson_learned || 'Outcome was saved; AI lesson will appear after OpenRouter is configured.'}
                </div>
              </div>
              </>
              )}
            </>
          )}
        </Card>
      </div>

      <div style={{ padding: '14px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        <SecondaryButton full leadingIcon="edit" onClick={() => goto('outcome', taskIndex)}>Edit</SecondaryButton>
        <SecondaryButton full leadingIcon="inbox" onClick={() => goto('approvals')}>Review</SecondaryButton>
        <PrimaryButton full trailingIcon="arrowRight" onClick={() => {
          const next = (taskIndex + 1) % TASKS.length;
          goto('task', next);
        }}>Next</PrimaryButton>
      </div>
    </div>
  );
}

function DebriefStat({ label, value, valueNode }) {
  return (
    <div style={{ padding: '12px 14px', background: C.cardElev, border: `1px solid ${C.border}`, borderRadius: 16 }}>
      <Caption>{label}</Caption>
      <div style={{ marginTop: 6, font: '600 15px/1.3 Inter, system-ui, sans-serif', color: C.fg1 }}>
        {valueNode || value}
      </div>
    </div>
  );
}

function CheckRow({ ok, pending, children }) {
  const color = ok ? '#86EFAC' : pending ? '#FCD34D' : C.fgMuted;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, font: '500 14px/20px Inter, system-ui, sans-serif', color: C.fg2 }}>
      <span style={{ width: 20, height: 20, borderRadius: 999, background: `${color}1A`, border: `1px solid ${color}40`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
        <Icon name={ok ? 'check' : 'clock'} size={11} color={color} strokeWidth={2.5}/>
      </span>
      <span>{children}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TASK CALENDAR — week strip + day agenda timeline
// ─────────────────────────────────────────────────────────────
function TaskCalendar({ goto, setTaskIndex, setView }) {
  // Demo "today" = Tue May 28, 2026 (matches TASKS dueIso)
  const week = [
    { dow: 'MON', d: 26, count: 1 },
    { dow: 'TUE', d: 27, count: 2 },
    { dow: 'WED', d: 28, count: TASKS.length, today: true },
    { dow: 'THU', d: 29, count: 3 },
    { dow: 'FRI', d: 30, count: 1 },
  ];
  const [sel, setSel] = React.useState(28);

  // Parse tasks into {hour, min, idx}
  const parsed = TASKS.map((t, idx) => {
    const m = (t.dueIso || '').match(/T(\d{2}):(\d{2})/);
    const h = m ? parseInt(m[1], 10) : 9;
    const min = m ? parseInt(m[2], 10) : 0;
    return { ...t, idx, h, min, mins: h * 60 + min };
  }).sort((a, b) => a.mins - b.mins);

  const START = 8, END = 17;            // 8 AM → 5 PM
  const PXH = 64;                       // px per hour
  const hours = [];
  for (let h = START; h <= END; h++) hours.push(h);
  const topFor = mins => ((mins - START * 60) / 60) * PXH;
  const fmtH = h => `${((h + 11) % 12) + 1} ${h < 12 ? 'AM' : 'PM'}`;
  const nowMins = 10 * 60 + 42;         // 10:42 AM marker

  const leadDot = { hot: C.danger, warm: C.warning, nurture: C.blue, dead: C.fgMuted };
  const kindIcon = { Call: 'phone', Email: 'mail', Bid: 'gavel', Vendor: 'inbox', Bid_: 'gavel' };

  const onSel = sel === 28;

  return (
    <div>
      {/* Month + week strip */}
      <div style={{ padding: '6px 20px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ font: '700 20px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '0.01em', whiteSpace: 'nowrap' }}>May 2026</div>
        <div style={{ display: 'flex', gap: 6 }}>
          <IconButton icon="chevronLeft" size={30} color={C.fgMuted}/>
          <IconButton icon="chevron" size={30} color={C.fgMuted}/>
        </div>
      </div>

      <div style={{ padding: '8px 16px 4px', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
        {week.map(d => {
          const on = sel === d.d;
          return (
            <button key={d.d} onClick={() => setSel(d.d)} type="button" style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, padding: '10px 0',
              borderRadius: 14, cursor: 'pointer',
              background: on ? 'linear-gradient(135deg, rgba(0,163,255,0.16), rgba(0,163,255,0.04))' : C.card,
              border: `1px solid ${on ? 'rgba(0,163,255,0.4)' : C.border}`,
              boxShadow: on ? '0 0 16px rgba(0,163,255,0.2)' : 'none',
            }}>
              <span style={{ font: '600 10px/1 Inter, system-ui, sans-serif', letterSpacing: '0.08em', color: on ? C.blueElectric : C.fgMuted }}>{d.dow}</span>
              <span className="tabular" style={{ font: '700 18px/1 Rajdhani, "Inter", system-ui, sans-serif', color: on ? C.fg1 : C.fg2 }}>{d.d}</span>
              <span style={{ display: 'flex', gap: 3, height: 5, alignItems: 'center' }}>
                {d.count > 0 ? Array.from({ length: Math.min(d.count, 3) }).map((_, i) => (
                  <span key={i} style={{ width: 4, height: 4, borderRadius: 999, background: on ? C.blueElectric : C.fgMuted }}/>
                )) : <span style={{ width: 4, height: 4 }}/>}
              </span>
            </button>
          );
        })}
      </div>

      {/* Day header */}
      <div style={{ padding: '14px 20px 6px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Caption>{onSel ? 'Tuesday · May 28' : `May ${sel}`}</Caption>
          <div style={{ font: '700 18px/1.15 Rajdhani, "Inter", system-ui, sans-serif', marginTop: 4, whiteSpace: 'nowrap' }}>
            {onSel ? `${TASKS.length} tasks · 2h 40m` : 'No scheduled tasks'}
          </div>
        </div>
        <div style={{ flex: 'none', display: 'flex', gap: 6 }}>
          <SyncChip state="connected" label="Calendar" size="sm"/>
        </div>
      </div>

      {!onSel ? (
        <div style={{ padding: '8px 20px' }}>
          <EmptyState icon="calendar" title="Nothing booked"
            body={`Tap a task on a busy day, or run today's mission to schedule follow-ups for May ${sel}.`}/>
        </div>
      ) : (
        /* Agenda timeline */
        <div style={{ padding: '4px 20px 0' }}>
          <div style={{ position: 'relative', paddingLeft: 56 }}>
            {/* Hour grid */}
            {hours.map((h, i) => (
              <div key={h} style={{ position: 'relative', height: PXH }}>
                <span style={{ position: 'absolute', left: -56, top: -7, width: 48, textAlign: 'right', font: '500 10px/1 JetBrains Mono, monospace', color: C.fgMuted }}>{fmtH(h)}</span>
                <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, background: C.border }}/>
              </div>
            ))}

            {/* Now line */}
            <div style={{ position: 'absolute', left: 0, right: 0, top: topFor(nowMins), zIndex: 3, display: 'flex', alignItems: 'center', gap: 0 }}>
              <span style={{ position: 'absolute', left: -56, top: -6, width: 48, textAlign: 'right', font: '700 9px/1 JetBrains Mono, monospace', color: C.blueElectric }}>NOW</span>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: C.blueElectric, boxShadow: '0 0 8px rgba(41,199,255,0.8)', marginLeft: -4 }}/>
              <span style={{ flex: 1, height: 1.5, background: 'linear-gradient(90deg, #29C7FF, transparent)' }}/>
            </div>

            {/* Task blocks */}
            {parsed.map(t => {
              const top = topFor(t.mins);
              const dur = 45; // assume 45-min blocks
              const height = (dur / 60) * PXH - 6;
              const dot = leadDot[t.lead] || C.blue;
              return (
                <button key={t.id} onClick={() => { setTaskIndex(t.idx); setView && setView('deck'); localStorage.setItem('stw:taskview', 'deck'); goto('task', t.idx); }} type="button" style={{
                  position: 'absolute', left: 4, right: 0, top, height: Math.max(height, 50),
                  textAlign: 'left', cursor: 'pointer', zIndex: 2,
                  background: C.cardElev, border: `1px solid ${C.border}`, borderLeft: `3px solid ${dot}`,
                  borderRadius: 12, padding: '8px 10px', overflow: 'hidden',
                  boxShadow: '0 6px 18px rgba(0,0,0,0.3)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Icon name={kindIcon[t.taskType] || 'phone'} size={12} color={dot}/>
                    <span style={{ font: '700 12px/1.1 Inter, system-ui, sans-serif', color: C.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{t.company}</span>
                    <span className="tabular" style={{ font: '500 10px/1 JetBrains Mono, monospace', color: C.fgMuted, flex: 'none' }}>{String(t.h % 12 === 0 ? 12 : t.h % 12).padStart(2, '0')}:{String(t.min).padStart(2, '0')}</span>
                  </div>
                  <div style={{ font: '400 11px/1.3 Inter, system-ui, sans-serif', color: C.fg2, marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {t.type} · {t.opportunity}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Agenda footer summary */}
          <div style={{ marginTop: 16, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <StatusPill kind="hot" size="sm">{TASKS.filter(t => t.lead === 'hot').length} Hot</StatusPill>
            <StatusPill kind="warm" size="sm">{TASKS.filter(t => t.lead === 'warm').length} Warm</StatusPill>
            <StatusPill kind="nurture" size="sm">{TASKS.filter(t => t.lead === 'nurture').length} Nurture</StatusPill>
          </div>
          <div style={{ marginTop: 12 }}>
            <PrimaryButton full glow leadingIcon="play" onClick={() => { setView && setView('deck'); localStorage.setItem('stw:taskview', 'deck'); goto('task', 0); }}>
              Start from the top
            </PrimaryButton>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenLogin, ScreenToday, ScreenTask, ScreenOutcome, ScreenDebrief, MiniStat, TaskCalendar });
