// ============================================================
// ShieldTech Secret Weapon — System screens
// Integrations · End-of-Day Review · Settings · Diagnostics
// ============================================================

// ─────────────────────────────────────────────────────────────
// GOOGLE / INTEGRATIONS STATUS
// ─────────────────────────────────────────────────────────────
function ScreenIntegrations({ goto }) {
  const [taskList, setTaskList] = React.useState('Secret Weapon');
  const [calList, setCalList] = React.useState('ShieldTech (primary)');
  const [testing, setTesting] = React.useState(false);
  const [integrations, setIntegrations] = React.useState([]);

  React.useEffect(() => {
    window.ShieldTechApi?.request?.('/api/integrations')
      .then(data => setIntegrations(data.integrations || []))
      .catch(error => window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'INTEGRATIONS_FAILED' } })));
  }, []);

  const google = integrations.find(item => item.id === 'google-oauth');
  const googleReady = google?.state === 'configured';

  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <BackRow onBack={() => goto('settings')} label="Settings" center="GOOGLE SYNC"/>

      <div style={{ padding: '8px 20px 0' }}>
        <div style={{ font: '700 28px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em' }}>Integrations</div>
        <div style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
          The assistant only writes back to Google when these are connected. No fake sync.
        </div>
      </div>

      {/* Big Google card */}
      <div style={{ padding: '16px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <svg width="22" height="22" 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>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: '700 17px/1.2 Rajdhani, "Inter", system-ui, sans-serif' }}>Google Workspace</div>
            <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 2 }}>{google?.detail || 'Google OAuth configuration required'}</div>
            </div>
            <SyncChip state={googleReady ? 'connected' : 'disconnected'} label={googleReady ? 'Configured' : 'Setup needed'}/>
          </div>
          <div style={{ marginTop: 14, padding: '10px 12px', background: C.cardElev, borderRadius: 12 }}>
            <Caption>Scopes granted</Caption>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
              {['calendar.events', 'tasks', 'profile', 'email'].map(s => (
                <span key={s} style={{
                  font: '600 11px/1 JetBrains Mono, monospace', padding: '4px 8px', borderRadius: 6,
                  background: '#0B1118', color: C.blueElectric, border: `1px solid ${C.border}`,
                }}>{s}</span>
              ))}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <SecondaryButton full leadingIcon="refresh" onClick={() => window.ShieldTechApi?.connectGoogle?.()}>Reconnect</SecondaryButton>
            <PrimaryButton full leadingIcon="signal" onClick={async () => {
              setTesting(true);
              try {
                await window.ShieldTechApi?.testIntegration?.('google-oauth');
              } catch (error) {
                window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'INTEGRATION_TEST_FAILED' } }));
              } finally {
                setTesting(false);
              }
            }}>
              {testing ? 'Testing…' : 'Test sync'}
            </PrimaryButton>
          </div>
        </Card>
      </div>

      {/* Tasks settings */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(34,197,94,0.10)', border: '1px solid rgba(34,197,94,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="check" size={18} color="#86EFAC"/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: '600 15px/1.2 Inter, system-ui, sans-serif' }}>Google Tasks</div>
              <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>{googleReady ? 'Ready after OAuth connection' : 'Google OAuth not configured or not connected'}</div>
            </div>
            <SyncChip state={googleReady ? 'pending' : 'disconnected'} label={googleReady ? 'Ready' : 'Setup needed'} size="sm"/>
          </div>
          <SelectRow label="Task list" value={taskList} options={['Secret Weapon', 'Inbox', 'ShieldTech']} onChange={setTaskList}/>
          <div style={{ marginTop: 10, font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted }}>
            Auto-create a task on every completed mission action. Updates reflect back here.
          </div>
        </Card>
      </div>

      {/* Calendar settings */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(0,163,255,0.10)', border: '1px solid rgba(0,163,255,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="calendar" size={18} color={C.blueElectric}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: '600 15px/1.2 Inter, system-ui, sans-serif' }}>Google Calendar</div>
              <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>{googleReady ? 'Ready after OAuth connection' : 'Google OAuth not configured or not connected'}</div>
            </div>
            <SyncChip state={googleReady ? 'pending' : 'disconnected'} label={googleReady ? 'Ready' : 'Setup needed'} size="sm"/>
          </div>
          <SelectRow label="Calendar" value={calList} options={['ShieldTech (primary)', 'Daniel personal', 'ShieldTech Field']} onChange={setCalList}/>
        </Card>
      </div>

      {/* Supabase error example */}
      <div style={{ padding: '14px 20px 0' }}>
        <ErrorState
          title="Supabase — reconnect required"
          body="Region timeout 4 hours ago. Mission and pipeline data are still cached locally, but new writes are queued."
          onRetry={() => window.ShieldTechApi?.hydrateGlobals?.()}
        />
      </div>

      {/* Sync activity */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <Caption>Recent sync activity</Caption>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
            {(integrations.length ? integrations : [{ state: 'missing', name: 'Integrations', detail: 'Run setup checks to populate status.' }]).map((row, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name={row.state === 'configured' ? 'check' : 'x'} size={12} color={row.state === 'configured' ? '#86EFAC' : '#FCA5A5'} strokeWidth={2.5}/>
                <span style={{ font: '500 12px/18px JetBrains Mono, monospace', color: C.fg2 }}>{row.name}: {row.detail}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function SelectRow({ label, value, options, onChange }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} type="button" style={{
        width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 14px', background: C.cardElev, border: `1px solid ${C.border}`, borderRadius: 12,
        color: C.fg1, font: '500 14px/1 Inter, system-ui, sans-serif', cursor: 'pointer',
      }}>
        <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 2 }}>
          <Caption>{label}</Caption>
          <span style={{ font: '600 14px/1 Inter, system-ui, sans-serif', color: C.fg1 }}>{value}</span>
        </span>
        <Icon name="chevronDown" size={16} color={C.fgMuted}/>
      </button>
      {open && (
        <div style={{ position: 'absolute', left: 0, right: 0, top: '100%', marginTop: 4, background: C.card, border: `1px solid ${C.borderStrong}`, borderRadius: 12, padding: 6, zIndex: 30, boxShadow: '0 12px 32px rgba(0,0,0,0.5)' }}>
          {options.map(o => (
            <button key={o} onClick={() => { onChange?.(o); setOpen(false); }} type="button" style={{
              width: '100%', padding: '10px 12px', borderRadius: 8, background: o === value ? C.cardElev : 'transparent',
              color: C.fg1, font: '500 14px/1 Inter, system-ui, sans-serif', border: 0, cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              {o}
              {o === value && <Icon name="check" size={14} color={C.blueElectric}/>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// END-OF-DAY REVIEW
// ─────────────────────────────────────────────────────────────
function ScreenEod({ goto }) {
  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <MobileHeader subtitle="END OF DAY · MAY 28" title="What moved ShieldTech forward today?"
        leading={
          <div style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(0,163,255,0.12)', border: '1px solid rgba(0,163,255,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="moon" size={18} color={C.blueElectric}/>
          </div>
        }/>

      {/* Hero summary */}
      <div style={{ padding: '8px 20px 0' }}>
        <GlassCard style={{ padding: 20 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <EodStat label="Calls" value="10" sub="of 12 · 83%" color="#86EFAC"/>
            <EodStat label="Emails sent" value="6"/>
            <EodStat label="Bids checked" value="2" sub="1 bid · 1 no-bid"/>
            <EodStat label="Vendor moves" value="3" sub="2 packets, 1 follow"/>
          </div>
          <div style={{ marginTop: 14 }}>
            <LinearProgress value={68} total={100} label="Daily sales score" sublabel="68 / 100"/>
          </div>
        </GlassCard>
      </div>

      {/* Wins */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <Icon name="trending" size={16} color="#86EFAC"/>
            <Caption color="#86EFAC">What worked</Caption>
          </div>
          {[
            'Penn Valley walkthrough confirmed for Thursday',
            'Keystone pricing got a same-day reply',
            'Wachter onboarding cleared the W2 question',
          ].map((w, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '8px 0', borderTop: i === 0 ? 0 : `1px solid ${C.border}` }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: '#86EFAC', marginTop: 8, flex: 'none' }}/>
              <div style={{ font: '500 14px/20px Inter, system-ui, sans-serif', color: C.fg1 }}>{w}</div>
            </div>
          ))}
        </Card>
      </div>

      {/* Wasted motion */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <Icon name="alertTriangle" size={16} color="#FCD34D"/>
            <Caption color="#FCD34D">Wasted motion</Caption>
          </div>
          {[
            { t: 'NorthStar Integrators — 5th no-answer', m: 'Recommend: mark dead and re-engage Q3.' },
            { t: 'Riverline Property Group — vendor packet sat idle', m: 'Move to nurture, set Jun 5 check-in.' },
          ].map((w, i) => (
            <div key={i} style={{ padding: '10px 0', borderTop: i === 0 ? 0 : `1px solid ${C.border}` }}>
              <div style={{ font: '600 14px/20px Inter, system-ui, sans-serif', color: '#FCD34D' }}>{w.t}</div>
              <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 2 }}>{w.m}</div>
            </div>
          ))}
        </Card>
      </div>

      {/* Lessons */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card glow="purple" style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <Icon name="sparkles" size={16} color={C.assistantSoft}/>
            <Caption color={C.assistantSoft}>Lessons</Caption>
          </div>
          <div style={{ font: '500 15px/22px Inter, system-ui, sans-serif', color: C.fg1 }}>
            Leading with the channel partner name shortened decision time on 2 of today’s calls. Keep doing that on camera RFPs.
          </div>
        </Card>
      </div>

      {/* Lead moves */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card style={{ padding: 18 }}>
          <Caption>Lead moves today</Caption>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
            {[
              { name: 'Penn Valley SD', from: 'hot', to: 'warm' },
              { name: 'Keystone Electrical', from: 'warm', to: 'warm', same: true, note: 'Stayed warm — pricing accepted' },
              { name: 'Wachter', from: 'nurture', to: 'warm' },
              { name: 'NorthStar Integrators', from: 'nurture', to: 'dead', pending: true },
            ].map((m, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0', borderTop: i === 0 ? 0 : `1px solid ${C.border}` }}>
                <div style={{ font: '600 13px/1 Inter, system-ui, sans-serif', color: C.fg1, flex: 1 }}>{m.name}</div>
                {m.same ? (
                  <span style={{ font: '500 12px/1 Inter, system-ui, sans-serif', color: C.fgMuted }}>{m.note}</span>
                ) : (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <StatusPill kind={m.from} size="sm">{m.from}</StatusPill>
                    <Icon name="arrowRight" size={12} color={C.fgMuted}/>
                    <StatusPill kind={m.to} size="sm">{m.to}</StatusPill>
                    {m.pending && <span style={{ font: '500 10px/1 Inter, system-ui, sans-serif', color: C.assistantSoft, letterSpacing: '0.04em', textTransform: 'uppercase', marginLeft: 4 }}>needs approval</span>}
                  </span>
                )}
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Tomorrow plan */}
      <div style={{ padding: '14px 20px 0' }}>
        <Card glow="blue" style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <Icon name="sun" size={16} color={C.blueElectric}/>
            <Caption color={C.blueElectric}>Tomorrow’s first 3 actions</Caption>
          </div>
          {[
            { i: 1, t: 'Walkthrough at Penn Valley SD', sub: 'Thu 10 AM · leave 8:45 AM', kind: 'event' },
            { i: 2, t: 'Bayonne Industrial Park walkthrough confirm', sub: 'Thu 8 AM · call to lock 11 AM', kind: 'call' },
            { i: 3, t: 'Anixter integrator registration', sub: 'Thu before lunch · Bensalem branch', kind: 'admin' },
          ].map(p => (
            <div key={p.i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderTop: p.i === 1 ? 0 : `1px solid ${C.border}` }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: C.cardElev, color: C.blueElectric, font: '700 14px/1 Rajdhani, "Inter", system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>{p.i}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{p.t}</div>
                <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>{p.sub}</div>
              </div>
            </div>
          ))}
        </Card>
      </div>

      <div style={{ padding: '20px' }}>
        <PrimaryButton full glow leadingIcon="moon" onClick={() => window.ShieldTechApi?.request?.('/api/eod').catch(error => window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'EOD_FAILED' } })))}>Finish day</PrimaryButton>
      </div>
    </div>
  );
}

function EodStat({ label, value, sub, color = C.fg1 }) {
  return (
    <div style={{ padding: '10px 12px', background: 'rgba(11,17,24,0.6)', border: `1px solid ${C.border}`, borderRadius: 14 }}>
      <Caption>{label}</Caption>
      <div className="tabular" style={{ font: '700 26px/1 Rajdhani, "Inter", system-ui, sans-serif', color, marginTop: 4 }}>{value}</div>
      {sub && <div style={{ font: '400 11px/16px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────────────────────────────
function ScreenSettings({ goto }) {
  const [mode, setMode] = React.useState('Aggressive');
  const [callGoal, setCallGoal] = React.useState(12);
  const [notif, setNotif] = React.useState(true);
  const [pwa, setPwa] = React.useState(true);
  const [trades, toggleTrade] = useSelectedTrades();
  const [tradeSheet, setTradeSheet] = React.useState(false);
  const tradeSummary = trades.length === 0 ? 'None selected'
    : trades.slice(0, 3).map(id => TRADE_BY_ID[id]?.short).filter(Boolean).join(' · ') + (trades.length > 3 ? ` · +${trades.length - 3} more` : '');

  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <MobileHeader subtitle="SETTINGS" title="Daniel Graham"
        leading={<Avatar initials="DG" size={40}/>}
        trailing={null}/>

      <div style={{ padding: '0 20px 4px', font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2 }}>
        ShieldTech Security LLC · PA · NJ · NY
      </div>

      {/* Mode picker */}
      <div style={{ padding: '14px 20px 0' }}>
        <div style={{ padding: '8px 4px' }}><Caption>Coaching mode</Caption></div>
        <Card style={{ padding: 4 }}>
          {[
            { id: 'Aggressive', label: 'Aggressive', sub: 'Push 12+ calls and faster follow-ups.', icon: 'flame', color: '#FCA5A5' },
            { id: 'Normal', label: 'Normal', sub: 'Balanced call and admin rhythm.', icon: 'target', color: C.blueElectric },
            { id: 'Light', label: 'Light', sub: 'Essential follow-ups only.', icon: 'moon', color: C.assistantSoft },
          ].map((m, i, arr) => {
            const on = mode === m.id;
            return (
              <button key={m.id} onClick={() => setMode(m.id)} type="button" style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 12,
                background: on ? 'rgba(0,163,255,0.06)' : 'transparent',
                border: 0, borderBottom: i === arr.length - 1 ? 0 : `1px solid ${C.border}`, borderRadius: 0,
                cursor: 'pointer', textAlign: 'left',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: C.cardElev, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
                  <Icon name={m.icon} size={18} color={m.color}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: '600 15px/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={{
                  width: 20, height: 20, borderRadius: 999,
                  border: `2px solid ${on ? C.blueElectric : C.borderStrong}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
                }}>
                  {on && <span style={{ width: 8, height: 8, borderRadius: 999, background: C.blueElectric, boxShadow: '0 0 8px rgba(41,199,255,0.6)' }}/>}
                </div>
              </button>
            );
          })}
        </Card>
      </div>

      {/* Daily targets */}
      <SettingsGroup label="Daily targets">
        <SettingRow icon="target" tint="rgba(0,163,255,0.10)" tintIcon={C.blueElectric}
          title="Calls per day" detail={`${callGoal} calls`} right={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <button onClick={() => setCallGoal(c => Math.max(1, c - 1))} type="button" style={{ width: 28, height: 28, borderRadius: 8, background: C.cardElev, color: C.fg1, border: `1px solid ${C.border}`, cursor: 'pointer' }}>–</button>
              <span className="tabular" style={{ font: '700 14px/1 Inter, system-ui, sans-serif', color: C.fg1, minWidth: 20, textAlign: 'center' }}>{callGoal}</span>
              <button onClick={() => setCallGoal(c => c + 1)} type="button" style={{ width: 28, height: 28, borderRadius: 8, background: C.cardElev, color: C.fg1, border: `1px solid ${C.border}`, cursor: 'pointer' }}>+</button>
            </div>
          }/>
        <SettingRow icon="clock" title="Work window" detail="7:30 AM – 6:00 PM" right={<Caption>Edit</Caption>}/>
        <SettingRow icon="bell" tint="rgba(245,158,11,0.10)" tintIcon="#FCD34D"
          title="Push notifications" detail="Reminders 15 min before each task" right={<Toggle on={notif} onChange={setNotif}/>} last/>
      </SettingsGroup>

      <SettingsGroup label="Territory & services">
        <SettingRow icon="mapPin" title="Territory" detail="PA · NJ · NY" right={<Caption>Edit</Caption>}/>
        <SettingRow icon="shield" tint="rgba(168,85,247,0.10)" tintIcon={C.assistantSoft}
          title="Trade selections" detail={tradeSummary}
          right={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ padding: '3px 9px', borderRadius: 999, background: 'rgba(168,85,247,0.12)', border: '1px solid rgba(168,85,247,0.32)', color: C.assistantSoft, font: '700 11px/1 Inter, system-ui, sans-serif' }}>{trades.length}</span>
              <Icon name="chevron" size={16} color={C.fgMuted}/>
            </span>
          } onClick={() => setTradeSheet(true)} last/>
      </SettingsGroup>

      <div style={{ padding: '4px 24px 0', font: '400 11px/16px Inter, system-ui, sans-serif', color: C.fgMuted }}>
        Trade selections power the Opportunities command center — they decide which bids match, how they're scored, and how bids are built.
      </div>

      <SettingsGroup label="Integrations">
        <SettingRow icon="google" tint="rgba(0,163,255,0.10)" tintIcon={C.blueElectric}
          title="Google account" detail="Tasks + Calendar require OAuth connection" right={<SyncChip state="pending" label="Check" size="sm"/>} onClick={() => goto('integrations')}/>
        <SettingRow icon="sparkles" tint="rgba(168,85,247,0.10)" tintIcon={C.assistantSoft}
          title="OpenRouter" detail="Debrief + email drafts require OPENROUTER_API_KEY" right={<SyncChip state="pending" label="Check" size="sm"/>} onClick={() => goto('diagnostics')}/>
        <SettingRow icon="database" tint="rgba(245,158,11,0.10)" tintIcon="#FCD34D"
          title="Supabase" detail="Pipeline + history require Supabase env" right={<SyncChip state="pending" label="Check" size="sm"/>} onClick={() => goto('diagnostics')} last/>
      </SettingsGroup>

      <SettingsGroup label="App">
        <SettingRow icon="download" title="Install PWA" detail="Add to home screen" right={<Toggle on={pwa} onChange={setPwa}/>}/>
        <SettingRow icon="activity" title="Diagnostics" detail="Production health check" right={<Icon name="chevron" size={16} color={C.fgMuted}/>} onClick={() => goto('diagnostics')}/>
        <SettingRow icon="refresh" title="Reset demo data" detail="Reseed PA/NJ/NY placeholders" right={<Caption>Run</Caption>} onClick={() => window.ShieldTechApi?.resetData?.().catch(error => window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'RESET_FAILED' } })))}/>
        <SettingRow icon="download" title="Export data" detail="JSON — pipeline + history" right={<Caption>Export</Caption>} onClick={async () => {
          try {
            const data = await window.ShieldTechApi?.exportData?.();
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'shieldtech-command-center-export.json';
            a.click();
            URL.revokeObjectURL(url);
          } catch (error) {
            window.dispatchEvent(new CustomEvent('stw:api-error', { detail: { message: error.message, code: error.code || 'EXPORT_FAILED' } }));
          }
        }} last/>
      </SettingsGroup>

      <div style={{ padding: '24px 24px 16px', textAlign: 'center', font: '400 11px/16px Inter, system-ui, sans-serif', color: C.fgMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
        ShieldTech Secret Weapon · v2.4.1 · production
      </div>

      {tradeSheet && <TradeSelectSheet trades={trades} toggleTrade={toggleTrade} onClose={() => setTradeSheet(false)}/>}
    </div>
  );
}

// Trade multi-select — the single source of truth for opportunity generation.
function TradeSelectSheet({ trades, toggleTrade, onClose }) {
  const byDiv = { '27': [], '28': [], '—': [] };
  TRADE_CATALOG.forEach(t => (byDiv[t.div] || byDiv['—']).push(t));
  const groups = [
    { label: 'Division 28 · Electronic safety & security', items: byDiv['28'] },
    { label: 'Division 27 · Communications', items: byDiv['27'] },
    { label: 'Service', items: byDiv['—'] },
  ];
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 90, background: 'rgba(3,5,8,0.7)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} className="slide-up" style={{
        width: '100%', maxHeight: '88%', overflowY: 'auto', background: C.card,
        borderTop: `1px solid ${C.borderStrong}`, borderRadius: '24px 24px 0 0',
        padding: '8px 18px 24px', boxShadow: '0 -16px 50px rgba(0,0,0,0.5)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: C.borderStrong, margin: '8px auto 16px' }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <div style={{ width: 36, height: 36, borderRadius: 11, background: 'rgba(168,85,247,0.12)', border: '1px solid rgba(168,85,247,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
            <Icon name="shield" size={18} color={C.assistantSoft}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ font: '700 18px/1.15 Rajdhani, "Inter", system-ui, sans-serif' }}>Your trades</div>
            <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fg2 }}>{trades.length} selected · drives all opportunity matching</div>
          </div>
          <IconButton icon="x" size={32} color={C.fgMuted} bg="transparent" border="transparent" onClick={onClose}/>
        </div>

        {groups.map(g => (
          <div key={g.label} style={{ marginTop: 14 }}>
            <Caption>{g.label}</Caption>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
              {g.items.map(t => {
                const on = trades.includes(t.id);
                return (
                  <button key={t.id} onClick={() => toggleTrade(t.id)} type="button" style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px', borderRadius: 12, cursor: 'pointer',
                    background: on ? 'rgba(0,163,255,0.07)' : C.cardElev,
                    border: `1px solid ${on ? 'rgba(0,163,255,0.32)' : C.border}`, textAlign: 'left',
                  }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{t.label}</div>
                      <div style={{ font: '400 11px/14px Inter, system-ui, sans-serif', color: C.fgMuted, marginTop: 2 }}>Signals: {t.kw.slice(0, 3).join(', ')}…</div>
                    </div>
                    <div style={{
                      width: 24, height: 24, borderRadius: 7, flex: 'none',
                      background: on ? 'linear-gradient(135deg,#00A3FF,#29C7FF)' : 'transparent',
                      border: `1.5px solid ${on ? '#0369A1' : C.borderStrong}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {on && <Icon name="check" size={14} color="#03182A" strokeWidth={3}/>}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}

        <div style={{ marginTop: 18 }}>
          <PrimaryButton full glow leadingIcon="check" onClick={onClose}>Done · {trades.length} trades</PrimaryButton>
        </div>
      </div>
    </div>
  );
}

function SettingsGroup({ label, children }) {
  return (
    <div style={{ padding: '14px 20px 0' }}>
      <div style={{ padding: '8px 4px' }}><Caption>{label}</Caption></div>
      <Card style={{ padding: 4 }}>{children}</Card>
    </div>
  );
}

function SettingRow({ icon, tint = C.cardElev, tintIcon = C.fg2, title, detail, right, last, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 12px',
      borderBottom: last ? 'none' : `1px solid ${C.border}`,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{ width: 36, height: 36, borderRadius: 10, background: tint, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
        <Icon name={icon} size={18} color={tintIcon}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 15px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{title}</div>
        {detail && <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 2 }}>{detail}</div>}
      </div>
      <div style={{ flex: 'none' }}>{right}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DIAGNOSTICS / HEALTH
// ─────────────────────────────────────────────────────────────
function ScreenDiagnostics({ goto }) {
  return (
    <div className="slide-up" style={{ padding: '0 0 140px' }}>
      <BackRow onBack={() => goto('settings')} label="Settings" center="DIAGNOSTICS"/>

      <div style={{ padding: '8px 20px 0' }}>
        <div style={{ font: '700 28px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em' }}>System health</div>
        <div style={{ font: '400 15px/22px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
          <span style={{ color: '#86EFAC', fontWeight: 600 }}>9 ok</span> · <span style={{ color: '#FCD34D', fontWeight: 600 }}>2 warn</span> · <span style={{ color: '#FCA5A5', fontWeight: 600 }}>1 error</span>
        </div>
      </div>

      <div style={{ padding: '14px 20px 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {DIAGNOSTICS.map(d => <DiagnosticRow key={d.id} d={d}/>)}
      </div>

      <div style={{ padding: '20px' }}>
        <SecondaryButton full leadingIcon="refresh" onClick={() => window.ShieldTechApi?.hydrateGlobals?.()}>Run all checks</SecondaryButton>
      </div>
    </div>
  );
}

function DiagnosticRow({ d }) {
  const colors = {
    ok: { fg: '#86EFAC', bg: '#052E16', border: '#166534', icon: 'check' },
    warn: { fg: '#FCD34D', bg: '#1A1306', border: '#92400E', icon: 'alertTriangle' },
    error: { fg: '#FCA5A5', bg: '#1B0908', border: '#7F1D1D', icon: 'x' },
  };
  const c = colors[d.status];
  return (
    <Card style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, borderColor: d.status === 'error' ? c.border : C.border, background: d.status === 'error' ? '#1B0908' : C.card }}>
      <div style={{ width: 28, height: 28, borderRadius: 8, background: c.bg, border: `1px solid ${c.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
        <Icon name={c.icon} size={14} color={c.fg} strokeWidth={2.5}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1 }}>{d.label}</div>
        <div style={{ font: '400 12px/16px JetBrains Mono, monospace', color: C.fgMuted, marginTop: 2 }}>{d.detail}</div>
      </div>
      {d.fix && (
        <button type="button" style={{ height: 32, padding: '0 12px', borderRadius: 10, background: c.bg, color: c.fg, border: `1px solid ${c.border}`, font: '600 12px/1 Inter, system-ui, sans-serif', cursor: 'pointer', flex: 'none' }}>
          {d.fix}
        </button>
      )}
    </Card>
  );
}

Object.assign(window, {
  ScreenIntegrations, ScreenEod, ScreenSettings, ScreenDiagnostics,
  SettingsGroup, SettingRow, DiagnosticRow, EodStat, SelectRow,
});
