/* Vooice — Dashboard home (desktop, primary product surface) */

function Dashboard({ width = 1320, height = 880, onNavigate }) {
  const [tick, setTick] = React.useState(0);
  const go = (k) => onNavigate && onNavigate(k);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="vc-root" style={{
      width, minHeight: height, background: VC_TOKENS.paper, color: VC_TOKENS.ink,
      display: 'grid',
      gridTemplateColumns: 'minmax(220px, 240px) 1fr',
      gridTemplateRows: 'auto 1fr',
      borderTop: `1px solid ${VC_TOKENS.line}`,
    }}>
      {/* Top bar — unified AppHeader */}
      <AppHeader onNavigate={onNavigate} current="home" status="● ALL SYSTEMS NOMINAL" />

      {/* Sidebar */}
      <aside style={{
        borderRight: `1px solid ${VC_TOKENS.line}`,
        padding: '24px 16px', display:'flex', flexDirection:'column', gap: 24,
        background: VC_TOKENS.paper2,
      }}>
        <NavGroup title="ASSISTANT" items={[
          { label: 'Home', active: true, go: () => go('home') },
          { label: 'Calls', count: 14, go: () => go('outbound-call') },
          { label: 'Messages', count: 3 },
          { label: 'Reminders', go: () => go('reminders') },
        ]} />
        <NavGroup title="MEMORY" items={[
          { label: 'Contacts', count: 184, go: () => go('contacts-memory') },
          { label: 'What she remembers', go: () => go('contacts-memory') },
          { label: 'Audit log', go: () => go('audit') },
        ]} />
        <NavGroup title="SETUP" items={[
          { label: 'Pricing', go: () => go('pricing') },
          { label: 'Landing page', go: () => go('marketing-hero') },
        ]} />
        <div style={{ marginTop: 'auto', padding: 12, border:`1px solid ${VC_TOKENS.line}`, background: VC_TOKENS.paper }}>
          <Mono>THIS MONTH</Mono>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginTop: 6 }}>
            <span style={{ fontSize: 22, fontWeight: 700, letterSpacing:'-0.02em' }}>83 / 200</span>
            <Mono color={VC_TOKENS.ink3}>min</Mono>
          </div>
          <div style={{ height: 4, background: VC_TOKENS.paper3, marginTop: 8 }}>
            <div style={{ width: '41%', height: '100%', background: VC_TOKENS.signal }} />
          </div>
        </div>
      </aside>

      {/* Main */}
      <main style={{ padding: 28, display:'flex', flexDirection:'column', gap: 24, minWidth: 0 }}>
        {/* Headline strip */}
        <div style={{
          border: `1px solid ${VC_TOKENS.line}`, background: VC_TOKENS.ink, color: VC_TOKENS.paper,
          padding: '20px 24px',
          display:'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', gap: 20, alignItems:'center',
        }} className="vc-grid-2col">
          <div>
            <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 8 }}>
              <RingingRing size={12} color={VC_TOKENS.signal} />
              <Mono color={VC_TOKENS.signal}>ON THE LINE NOW</Mono>
            </div>
            <div style={{
              fontFamily: "'Inter Tight', sans-serif", fontSize: 30, fontWeight: 600,
              letterSpacing: '-0.02em', lineHeight: 1.15,
            }}>
              Calling <u>Bayview Hair Studio</u> for you — booking <span style={{ color: VC_TOKENS.signal }}>Thu 2pm</span>.
            </div>
            <div style={{ marginTop: 8, display: 'flex', gap: 14 }}>
              <Mono color={VC_TOKENS.paper}>00:{(20 + (tick % 30)).toString().padStart(2,'0')} elapsed</Mono>
              <Mono color={VC_TOKENS.ink3}>·</Mono>
              <Mono color={VC_TOKENS.ink3}>3 actions queued, awaiting confirmation</Mono>
            </div>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap: 8, minWidth: 280 }}>
            <Waveform bars={56} height={48} speaker="vooice" color={VC_TOKENS.paper} accent={VC_TOKENS.signal} />
            <div style={{ display:'flex', gap: 8 }}>
              <button onClick={() => go('outbound-call')} style={btnDark}>OPEN LIVE</button>
              <button onClick={() => go('outbound-call')} style={btnDarkOutline}>BRING ME IN</button>
            </div>
          </div>
        </div>

        {/* Metrics row */}
        <div className="vc-grid-4col" style={{
          display:'grid', gridTemplateColumns: 'repeat(4, 1fr)',
          border: `1px solid ${VC_TOKENS.line}`,
        }}>
          {[
            { v: '14', u: 'this week', l: 'CALLS HANDLED' },
            { v: '6',  u: 'avg/day',  l: 'OUTBOUND' },
            { v: '92', u: '%',         l: 'SLOT READ‑BACK PASS' },
            { v: '3',  u: 'pending',   l: 'NEEDS YOUR EYES' },
          ].map((m, i) => (
            <div key={i} style={{
              padding: 24, borderRight: i < 3 ? `1px solid ${VC_TOKENS.lineSoft}` : 'none',
              background: VC_TOKENS.paper,
            }}>
              <Metric value={m.v} unit={m.u} label={m.l} />
            </div>
          ))}
        </div>

        {/* Two-up: Activity timeline + Inbox */}
        <div className="vc-grid-2col" style={{ display:'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, minHeight: 0 }}>
          <Surface padding={0} bordered style={{ overflow:'hidden', display:'flex', flexDirection:'column' }}>
            <div style={{ padding:'18px 22px', borderBottom: `1px solid ${VC_TOKENS.lineSoft}`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <SectionHead eyebrow="TODAY · APR 8" title="What Vooice did" />
              <Mono>FILTER · ALL</Mono>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: '8px 0' }}>
              <ActivityRow time="09:14" type="inbound"  who="Mom" body="Asked when you're coming for dinner. Vooice replied: Sunday at 6." action="Replied" />
              <ActivityRow time="10:02" type="email"    who="Inbox triage" body="2 important: Lina (lease renewal), David (Tues prep)." action="Summarized" />
              <ActivityRow time="11:30" type="outbound" who="Dr. Han's office" body="Confirmed annual physical for Apr 22, 9am." action="Scheduled" highlight />
              <ActivityRow time="13:48" type="reminder" who="3pm reminder" body="Pinged you on Telegram: 'Call dentist re: cleaning.'" action="Fired" />
              <ActivityRow time="14:22" type="message"  who="Mike" body="WhatsApp: 'Running 10 late.' Sent on your behalf." action="Sent" />
              <ActivityRow time="15:51" type="outbound" who="Bayview Hair Studio" body="Booking Thu 2pm with Marcus. In progress." action="Live" live onClick={() => go('outbound-call')} />
              <ActivityRow time="14:30" type="outbound" who="Earlier · Dr. Han voicemail" body="View the post-mortem of yesterday's call." action="Detail →" onClick={() => go('call-detail')} />
            </div>
          </Surface>

          <Surface padding={0} bordered style={{ overflow:'hidden', display:'flex', flexDirection:'column' }}>
            <div style={{ padding:'18px 22px', borderBottom: `1px solid ${VC_TOKENS.lineSoft}` }}>
              <SectionHead eyebrow="NEEDS YOUR EYES" title="3 things to confirm" />
            </div>
            <div style={{ flex: 1, overflow:'auto' }}>
              <ConfirmRow
                channel="EMAIL DRAFT"
                head="Reply to David Kim — RE: Tuesday prep"
                body={`"Thanks David — I'll have the deck ready by Monday EOD. Want to walk through it Tuesday at 9?"`}
                meta="3 min read · sage tone"
                cta="REVIEW &amp; SEND"
              />
              <ConfirmRow
                channel="OUTBOUND CALL"
                head="Call back +1 (628) 555‑0177"
                body={`Unknown number, left a 14s voicemail saying "this is Mark from the brokerage about the Tuesday closing"`}
                meta="Vooice: medium‑confidence legitimate"
                cta="QUEUE CALL"
              />
              <ConfirmRow
                channel="MEMORY"
                head="Remember this about Lina?"
                body={`"Lina prefers Wednesday afternoons; husband's name is Pete; daughter Eli started kindergarten 2026."`}
                meta="Source · 2 calls + 4 messages"
                cta="ADD TO MEMORY"
                last
              />
            </div>
          </Surface>
        </div>
      </main>
    </div>
  );
}

const btnDark = {
  padding: '8px 14px', background: VC_TOKENS.signal, color: VC_TOKENS.paper,
  border:'none', cursor:'pointer',
  fontFamily:"'JetBrains Mono', monospace", fontSize: 11, fontWeight: 700, letterSpacing:'.12em',
};
const btnDarkOutline = {
  padding: '8px 14px', background: 'transparent', color: VC_TOKENS.paper,
  border:`1px solid ${VC_TOKENS.paper}`, cursor:'pointer',
  fontFamily:"'JetBrains Mono', monospace", fontSize: 11, fontWeight: 700, letterSpacing:'.12em',
};

function NavGroup({ title, items }) {
  return (
    <div>
      <Mono style={{ marginBottom: 10, display:'block', paddingLeft: 10 }}>{title}</Mono>
      <div style={{ display:'flex', flexDirection:'column' }}>
        {items.map(it => (
          <div key={it.label} onClick={it.go} style={{
            padding: '8px 10px', display:'flex', justifyContent:'space-between',
            background: it.active ? VC_TOKENS.ink : 'transparent',
            color: it.active ? VC_TOKENS.paper : VC_TOKENS.ink,
            fontWeight: it.active ? 600 : 500,
            fontSize: 14, cursor: it.go ? 'pointer' : 'default',
            borderLeft: it.active ? `2px solid ${VC_TOKENS.signal}` : '2px solid transparent',
          }}>
            <span>{it.label}</span>
            {it.count != null && (
              <span style={{
                fontFamily:"'JetBrains Mono', monospace", fontSize: 11,
                color: it.active ? VC_TOKENS.paper : VC_TOKENS.ink3,
              }}>{it.count}</span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function ActivityRow({ time, type, who, body, action, highlight, live, onClick }) {
  const typeColor = {
    inbound:  VC_TOKENS.sage,
    outbound: VC_TOKENS.signal,
    email:    VC_TOKENS.ink3,
    message:  VC_TOKENS.ink3,
    reminder: VC_TOKENS.butter,
  }[type] || VC_TOKENS.ink3;
  return (
    <div onClick={onClick} style={{
      display:'grid', gridTemplateColumns: '60px 12px 1fr auto',
      gap: 14, padding: '14px 22px', alignItems: 'baseline',
      borderLeft: highlight ? `3px solid ${VC_TOKENS.signal}` : '3px solid transparent',
      background: live ? VC_TOKENS.signalSoft : 'transparent',
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <Mono color={VC_TOKENS.ink3}>{time}</Mono>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: typeColor, marginTop: 5 }} />
      <div>
        <div style={{ fontWeight: 600, fontSize: 14 }}>
          {who}
          {live && <span style={{ marginLeft: 8 }}><Tag tone="signal">LIVE</Tag></span>}
        </div>
        <div style={{ color: VC_TOKENS.ink3, fontSize: 13, marginTop: 4, lineHeight: 1.4 }}>{body}</div>
      </div>
      <Mono color={VC_TOKENS.ink}>{action}</Mono>
    </div>
  );
}

function ConfirmRow({ channel, head, body, meta, cta, last }) {
  return (
    <div style={{
      padding: '16px 22px',
      borderBottom: last ? 'none' : `1px solid ${VC_TOKENS.lineSoft}`,
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
        <Mono color={VC_TOKENS.signal}>{channel}</Mono>
        <Mono color={VC_TOKENS.ink3}>WAITING</Mono>
      </div>
      <div style={{ fontSize: 14, fontWeight: 600 }}>{head}</div>
      <div style={{ fontSize: 13, color: VC_TOKENS.ink3, marginTop: 6, lineHeight: 1.5,
        borderLeft: `2px solid ${VC_TOKENS.lineSoft}`, paddingLeft: 10,
        fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 15,
      }}>{body}</div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 12 }}>
        <Mono color={VC_TOKENS.ink3}>{meta}</Mono>
        <button style={{
          background: VC_TOKENS.ink, color: VC_TOKENS.paper, border:'none',
          padding: '6px 12px', cursor:'pointer',
          fontFamily:"'JetBrains Mono', monospace", fontSize: 10, fontWeight:700, letterSpacing:'.12em',
        }} dangerouslySetInnerHTML={{ __html: cta }} />
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
