// ============================================================
// ShieldTech Secret Weapon — Desktop layout
// Left sidebar + main pane. Reuses the mobile screen components
// inside a wider canvas, with a desktop dashboard on Today.
// ============================================================

function DesktopShell({ route, setRoute, taskIndex, setTaskIndex }) {
  const goto = (r, idx) => { if (typeof idx === 'number') setTaskIndex(idx); setRoute(r); };

  return (
    <div style={{
      display: 'flex', minHeight: 760, height: '100%',
      background: `radial-gradient(circle at top right, rgba(0,163,255,0.10), transparent 35%), radial-gradient(circle at bottom left, rgba(168,85,247,0.06), transparent 28%), ${C.bg1}`,
    }}>
      <DesktopSidebar active={route} onChange={r => goto(r)}/>
      <main style={{ flex: 1, minWidth: 0, color: C.fg1, overflow: 'auto' }}>
        <DesktopTopbar route={route}/>
        <DesktopBody route={route} goto={goto} taskIndex={taskIndex} setTaskIndex={setTaskIndex}/>
      </main>
    </div>
  );
}

function DesktopSidebar({ active, onChange }) {
  const groups = [
    { items: [
      { id: 'today', label: 'Today', icon: 'target' },
      { id: 'task', label: 'Task deck', icon: 'layers' },
      { id: 'assistant', label: 'Assistant', icon: 'sparkles' },
      { id: 'pipeline', label: 'Pipeline', icon: 'branch' },
    ]},
    { label: 'Sales ops', items: [
      { id: 'followups', label: 'Follow-ups', icon: 'clock', badge: 5 },
      { id: 'bids', label: 'Bids', icon: 'gavel', badge: 4 },
      { id: 'contractors', label: 'Lists', icon: 'users' },
      { id: 'vendors', label: 'Vendors', icon: 'inbox' },
      { id: 'approvals', label: 'Approvals', icon: 'eye', badge: 3 },
    ]},
    { label: 'System', items: [
      { id: 'integrations', label: 'Google sync', icon: 'calendar' },
      { id: 'eod', label: 'End-of-day', icon: 'moon' },
      { id: 'settings', label: 'Settings', icon: 'settings' },
      { id: 'diagnostics', label: 'Diagnostics', icon: 'activity' },
    ]},
  ];
  return (
    <aside style={{
      width: 248, flex: 'none', borderRight: `1px solid ${C.border}`,
      padding: '20px 14px', display: 'flex', flexDirection: 'column', gap: 18,
      background: 'rgba(11,17,24,0.55)', backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
      minHeight: '100%',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 8px 4px' }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'linear-gradient(135deg, rgba(0,163,255,0.18), rgba(168,85,247,0.12))',
          border: '1px solid rgba(0,163,255,0.32)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <img src="assets/logo-shield.png" style={{ width: 26, height: 26, objectFit: 'contain' }} alt=""/>
        </div>
        <div>
          <div style={{ font: '700 14px/1.1 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '0.02em', color: C.fg1, textTransform: 'uppercase' }}>Secret Weapon</div>
          <div style={{ font: '500 10px/1 Inter, system-ui, sans-serif', color: C.blueElectric, letterSpacing: '0.2em', textTransform: 'uppercase', marginTop: 3 }}>ShieldTech</div>
        </div>
      </div>

      {groups.map((g, gi) => (
        <div key={gi} style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          {g.label && (
            <div style={{ padding: '8px 12px 6px', borderTop: `1px solid ${C.border}` }}>
              <Caption>{g.label}</Caption>
            </div>
          )}
          {g.items.map(item => {
            const on = active === item.id;
            return (
              <button key={item.id} onClick={() => onChange(item.id)} type="button" style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 12px', borderRadius: 10,
                background: on ? 'rgba(0,163,255,0.10)' : 'transparent',
                border: 0, color: on ? C.fg1 : C.fg2, cursor: 'pointer',
                font: '600 14px/1 Inter, system-ui, sans-serif', textAlign: 'left',
                position: 'relative',
              }}>
                {on && <span style={{
                  position: 'absolute', left: -14, top: 8, bottom: 8, width: 3, borderRadius: 2,
                  background: C.blueElectric, boxShadow: '0 0 8px rgba(41,199,255,0.6)',
                }}/>}
                <Icon name={item.icon} size={18} color={on ? C.blueElectric : C.fgMuted}/>
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.badge && (
                  <span style={{
                    padding: '2px 8px', borderRadius: 999,
                    background: '#2E1065', color: '#D8B4FE', border: '1px solid #6B21A8',
                    font: '700 11px/1 Inter, system-ui, sans-serif',
                  }}>{item.badge}</span>
                )}
              </button>
            );
          })}
        </div>
      ))}

      {/* User */}
      <div style={{ marginTop: 'auto', padding: 12, borderRadius: 14, background: C.card, border: `1px solid ${C.border}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Avatar initials="DG" size={36}/>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ font: '600 13px/1.2 Inter, system-ui, sans-serif', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Daniel Graham</div>
            <div style={{ font: '400 11px/1.2 Inter, system-ui, sans-serif', color: C.fgMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>ShieldTech Security LLC</div>
          </div>
        </div>
      </div>
    </aside>
  );
}

function DesktopTopbar({ route }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 32px', borderBottom: `1px solid ${C.border}`,
      background: 'rgba(11,17,24,0.5)', backdropFilter: 'blur(18px)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', borderRadius: 10, background: C.card, border: `1px solid ${C.border}`, flex: 1, maxWidth: 480 }}>
        <Icon name="search" size={14} color={C.fgMuted}/>
        <span style={{ font: '400 13px/1 Inter, system-ui, sans-serif', color: C.fgMuted }}>Search leads, bids, or ask the assistant…</span>
        <span style={{ marginLeft: 'auto', font: '600 10px/1 JetBrains Mono, monospace', color: C.fgMuted, padding: '3px 6px', borderRadius: 4, background: '#0B1118', border: `1px solid ${C.border}` }}>⌘K</span>
      </div>
      <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
        <SyncChip state="pending" label="Google status" size="sm"/>
        <SyncChip state="pending" label="Supabase status" size="sm"/>
      </div>
    </div>
  );
}

function DesktopBody({ route, goto, taskIndex, setTaskIndex }) {
  if (route === 'today') return <DesktopToday goto={goto}/>;
  if (route === 'pipeline') return <DesktopPipeline goto={goto}/>;
  if (route === 'followups') return <DesktopWrap title="Follow-ups"><ScreenFollowups goto={goto}/></DesktopWrap>;
  if (route === 'bids') return <DesktopWrap title="Public bids"><ScreenBids goto={goto}/></DesktopWrap>;
  if (route === 'contractors') return <DesktopWrap title="Lists"><ScreenContractors goto={goto}/></DesktopWrap>;
  if (route === 'vendors') return <DesktopWrap title="Vendor applications"><ScreenVendors goto={goto}/></DesktopWrap>;
  if (route === 'approvals') return <DesktopWrap title="Approvals"><ScreenApprovals goto={goto}/></DesktopWrap>;
  if (route === 'assistant') return <DesktopWrap title="Assistant" wide><ScreenAssistant goto={goto}/></DesktopWrap>;
  if (route === 'integrations') return <DesktopWrap title="Integrations"><ScreenIntegrations goto={goto}/></DesktopWrap>;
  if (route === 'eod') return <DesktopWrap title="End-of-day"><ScreenEod goto={goto}/></DesktopWrap>;
  if (route === 'settings') return <DesktopWrap title="Settings"><ScreenSettings goto={goto}/></DesktopWrap>;
  if (route === 'diagnostics') return <DesktopWrap title="Diagnostics"><ScreenDiagnostics goto={goto}/></DesktopWrap>;
  if (route === 'task') return <DesktopWrap title="Task deck"><ScreenTask goto={goto} taskIndex={taskIndex} setTaskIndex={setTaskIndex}/></DesktopWrap>;
  return null;
}

function DesktopWrap({ title, children, wide }) {
  return (
    <div style={{ padding: '24px 32px', maxWidth: wide ? 1200 : 720, margin: '0 auto' }}>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Desktop: Today — proper command-center dashboard
// ─────────────────────────────────────────────────────────────
function DesktopToday({ goto }) {
  return (
    <div className="slide-up" style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 1200, margin: '0 auto' }}>
      {/* Hero */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
        <div>
          <Caption>Tuesday · May 28 · 10:42 AM</Caption>
          <div style={{ font: '700 36px/1.05 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em', marginTop: 8 }}>Your mission is ready.</div>
          <div style={{ font: '400 17px/26px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
            Start with Hot follow-ups. <span style={{ color: '#FCD34D', fontWeight: 600 }}>4 haven’t been touched in 8+ days.</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <SecondaryButton leadingIcon="refresh" onClick={() => window.ShieldTechApi?.hydrateGlobals?.()}>Refresh mission</SecondaryButton>
          <PrimaryButton glow leadingIcon="play" onClick={() => goto('task')}>Start mission</PrimaryButton>
        </div>
      </div>

      {/* Stat row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
        <DeskStat label="Calls today" value="0 / 12" sub="Behind pace" warn/>
        <DeskStat label="Hot follow-ups" value="4" sub="2 untouched 8+ days"/>
        <DeskStat label="Bids due" value="2" sub="Tri-County · Jun 4"/>
        <DeskStat label="Approvals" value="3" sub="1 email · 1 bid · 1 dead"/>
        <DeskStat label="Vendors stuck" value="3" sub="Wachter · SC · Riverline"/>
      </div>

      {/* Body grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
        {/* Left column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Mission deck list */}
          <Card style={{ padding: 20, overflow: 'hidden' }}>
            <span className="scan-line"/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <div>
                <Caption color={C.blue}>Mission deck · next 5</Caption>
                <div style={{ font: '700 18px/1.2 Rajdhani, "Inter", system-ui, sans-serif', marginTop: 4 }}>The order that wins the day</div>
              </div>
              <button onClick={() => goto('task')} type="button" style={{ background: 'transparent', color: C.blueElectric, border: 0, font: '600 13px/1 Inter, system-ui, sans-serif', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                Open deck <Icon name="arrowRight" size={14}/>
              </button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {TASKS.map((t, i) => (
                <div key={i} onClick={() => goto('task', i)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
                  borderRadius: 14, background: C.cardElev, border: `1px solid ${C.border}`,
                  cursor: 'pointer',
                }}>
                  <div style={{ width: 28, height: 28, flex: 'none', borderRadius: 8, background: 'linear-gradient(135deg, rgba(0,163,255,0.18), rgba(0,163,255,0.04))', color: C.blueElectric, font: '700 12px/1 Rajdhani, "Inter", system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</div>
                  <Avatar initials={t.company.split(' ').map(w => w[0]).slice(0, 2).join('')} size={36}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.company}</div>
                    <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fg2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.type} · {t.opportunity}</div>
                  </div>
                  <Caption style={{ flex: 'none' }}>{t.dueLabel.replace('Due ', '')}</Caption>
                  <PriorityPill level={t.priority} size="sm"/>
                  <StatusPill kind={t.lead} size="sm">{cap(t.lead)}</StatusPill>
                </div>
              ))}
            </div>
          </Card>

          {/* Top 3 money actions */}
          <Card style={{ padding: 20 }}>
            <Caption>Top 3 money actions</Caption>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginTop: 10 }}>
              {[
                { rank: 1, label: 'Hot follow-ups', sub: '4 leads cooling', value: '$340K open' },
                { rank: 2, label: 'Bid + vendor', sub: 'Tri-County · Wachter', value: '8 hrs at stake' },
                { rank: 3, label: 'Warm conversions', sub: 'Keystone · Bayonne', value: '2 deals warm' },
              ].map(m => (
                <div key={m.rank} style={{ padding: 14, borderRadius: 14, background: C.cardElev, border: `1px solid ${C.border}` }}>
                  <div style={{ font: '700 22px/1 Rajdhani, "Inter", system-ui, sans-serif', color: C.blueElectric }}>0{m.rank}</div>
                  <div style={{ font: '600 14px/1.2 Inter, system-ui, sans-serif', color: C.fg1, marginTop: 8 }}>{m.label}</div>
                  <div style={{ font: '400 12px/16px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 4 }}>{m.sub}</div>
                  <div style={{ font: '700 11px/1 Inter, system-ui, sans-serif', color: C.blueElectric, marginTop: 10, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{m.value}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* Right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Mission ring */}
          <GlassCard style={{ padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <ProgressRing value={0} total={12} size={110}/>
              <div style={{ flex: 1 }}>
                <Caption>Daily sales score</Caption>
                <div className="tabular" style={{ font: '700 28px/1 Rajdhani, "Inter", system-ui, sans-serif', marginTop: 6, color: '#FCD34D' }}>0 / 100</div>
                <div style={{ font: '400 13px/18px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>12 tasks · est. 2h 40m focused</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
              <StatusPill kind="hot" size="sm">4 Hot</StatusPill>
              <StatusPill kind="warm" size="sm">5 Warm</StatusPill>
              <StatusPill kind="nurture" size="sm">3 Nurture</StatusPill>
              <StatusPill kind="approval" size="sm">3 Approvals</StatusPill>
            </div>
          </GlassCard>

          {/* Assistant nudge */}
          <Card glow="purple" style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <div className="glow-purple" style={{ width: 28, height: 28, borderRadius: 8, 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={14} color={C.assistantSoft}/>
              </div>
              <Caption color={C.assistantSoft}>Assistant nudge · 2m ago</Caption>
            </div>
            <div style={{ font: '700 17px/1.2 Rajdhani, "Inter", system-ui, sans-serif' }}>You’re behind on calls.</div>
            <div style={{ font: '400 14px/20px Inter, system-ui, sans-serif', color: C.fg2, marginTop: 6 }}>
              Do the next 3 before admin work. Penn Valley’s walkthrough goes cold by tomorrow.
            </div>
            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              <SecondaryButton onClick={() => goto('assistant')} style={{ height: 36, padding: '0 12px', font: '600 13px/1 Inter, system-ui, sans-serif' }}>Ask why</SecondaryButton>
              <PrimaryButton onClick={() => goto('task')} style={{ height: 36, padding: '0 12px', font: '600 13px/1 Inter, system-ui, sans-serif' }}>Start next 3</PrimaryButton>
            </div>
          </Card>

          {/* System */}
          <Card style={{ padding: 18 }}>
            <Caption>System</Caption>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 10 }}>
              <SyncRow icon="calendar" label="Google Calendar" state="pending"/>
              <SyncRow icon="check" label="Google Tasks" state="pending"/>
              <SyncRow icon="sparkles" label="OpenRouter" state="pending"/>
              <SyncRow icon="database" label="Supabase" state="pending"/>
            </div>
            <div style={{ marginTop: 14 }}>
              <SecondaryButton full leadingIcon="activity" onClick={() => goto('diagnostics')}>Open diagnostics</SecondaryButton>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

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

function SyncRow({ icon, label, state }) {
  const labels = { connected: 'Connected', error: 'Reconnect', disconnected: 'Not connected', syncing: 'Syncing', pending: 'Check' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <Icon name={icon} size={16} color={C.fgMuted}/>
      <span style={{ flex: 1, font: '500 13px/1 Inter, system-ui, sans-serif', color: C.fg2 }}>{label}</span>
      <SyncChip state={state} label={labels[state]} size="sm"/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Desktop: Pipeline — Kanban
// ─────────────────────────────────────────────────────────────
function DesktopPipeline({ goto }) {
  const cols = [
    { id: 'hot', label: 'Hot', items: PIPELINE.filter(l => l.lead === 'hot') },
    { id: 'warm', label: 'Warm', items: PIPELINE.filter(l => l.lead === 'warm') },
    { id: 'nurture', label: 'Nurture', items: PIPELINE.filter(l => l.lead === 'nurture') },
    { id: 'dead', label: 'Dead', items: PIPELINE.filter(l => l.lead === 'dead') },
  ];
  return (
    <div className="slide-up" style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 1400, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <Caption>Pipeline</Caption>
          <div style={{ font: '700 32px/1.05 Rajdhani, "Inter", system-ui, sans-serif', letterSpacing: '-0.02em', marginTop: 8 }}>
            {PIPELINE.length} leads · {cols[0].items.length} hot
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <SecondaryButton leadingIcon="filter" onClick={() => window.ShieldTechApi?.hydrateGlobals?.()}>Refresh</SecondaryButton>
          <PrimaryButton leadingIcon="plus" onClick={() => goto('bids')}>Add from source</PrimaryButton>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {cols.map(col => (
          <div key={col.id} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 4px 12px' }}>
              <StatusPill kind={col.id} size="sm" dot={false}>{col.label}</StatusPill>
              <Caption>· {col.items.length}</Caption>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minHeight: 200 }}>
              {col.items.length === 0 && (
                <div style={{ padding: 14, borderRadius: 14, background: C.card, border: `1px dashed ${C.border}`, textAlign: 'center', font: '500 12px/16px Inter, system-ui, sans-serif', color: C.fgMuted }}>
                  No leads
                </div>
              )}
              {col.items.map(l => <PipelineLeadCard key={l.id} lead={l}/>)}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DesktopShell, DesktopSidebar, DesktopToday, DesktopPipeline });
