const PERSONAS = {
  lawyer: {
    label: 'Lawyer',
    day: 'Friday · Sep 19',
    right: { task: 'Deposition prep', sub: 'Tata Dispute · Exhibit tagging', elapsed: '6m' },
    items: [
      { client: 'Patel Acquisition', name: 'Contract review', color: window.TRACE ? window.TRACE.sky : '#00A6FB', hours: 2.6, frac: 0.36 },
      { client: 'Tata Dispute',      name: 'Deposition prep',  color: window.TRACE ? window.TRACE.amber : '#E3B23C', hours: 2.1, frac: 0.29 },
      { client: 'Mehta LLP',         name: 'Brief drafting',   color: window.TRACE ? window.TRACE.mauve : '#775B59', hours: 1.5, frac: 0.21 },
      { client: 'Internal',          name: 'Billing · email',  color: window.TRACE ? window.TRACE.grey : '#9CA3AF', hours: 1.0, frac: 0.14 },
    ],
    timeline: [
      { t: '09:05 – 10:41', task: 'Contract review — clause redlines', client: 'Patel Acquisition', method: 'rule' },
      { t: '10:41 – 10:55', task: 'Email · internal', client: 'Internal', method: 'manual' },
      { t: '10:55 – 12:22', task: 'Brief drafting — Section 4', client: 'Mehta LLP', method: 'ai' },
      { t: '13:40 – 15:52', task: 'Deposition prep — exhibit tagging', client: 'Tata Dispute', method: 'rule' },
      { t: '15:52 – 16:22', task: 'Billing review', client: 'Internal', method: 'manual' },
    ],
  },
  consultant: {
    label: 'Consultant',
    day: 'Friday · Sep 19',
    right: { task: 'Logo lockup', sub: 'Acme Corp · Brand refresh', elapsed: '4m' },
    items: [
      { client: 'Acme Corp.',  name: 'Brand refresh',    color: window.TRACE ? window.TRACE.sky : '#00A6FB', hours: 2.4, frac: 0.40 },
      { client: 'Hayes & Co.', name: 'Discovery review', color: window.TRACE ? window.TRACE.amber : '#E3B23C', hours: 1.2, frac: 0.20 },
      { client: 'Northwind',   name: 'Q3 retainer',      color: window.TRACE ? window.TRACE.mauve : '#775B59', hours: 1.5, frac: 0.25 },
      { client: 'Internal',    name: 'Admin · email',    color: window.TRACE ? window.TRACE.grey : '#9CA3AF', hours: 0.9, frac: 0.15 },
    ],
    timeline: [
      { t: '08:58 – 10:20', task: 'Brand refresh — logo lockup', client: 'Acme Corp.', method: 'rule' },
      { t: '10:20 – 11:35', task: 'Q3 retainer — stakeholder call', client: 'Northwind', method: 'ai' },
      { t: '11:35 – 11:50', task: 'Admin · email', client: 'Internal', method: 'manual' },
      { t: '13:15 – 14:27', task: 'Discovery review — asset audit', client: 'Hayes & Co.', method: 'ai' },
      { t: '14:27 – 15:51', task: 'Brand refresh — style guide', client: 'Acme Corp.', method: 'rule' },
    ],
  },
  freelancer: {
    label: 'Freelancer',
    day: 'Friday · Sep 19',
    right: { task: 'Homepage layout', sub: 'Nova Studio · Website redesign', elapsed: '2m' },
    items: [
      { client: 'Nova Studio',  name: 'Website redesign', color: window.TRACE ? window.TRACE.sky : '#00A6FB', hours: 3.1, frac: 0.44 },
      { client: 'Bloom Cafe',   name: 'Branding retainer', color: window.TRACE ? window.TRACE.mauve : '#775B59', hours: 1.8, frac: 0.26 },
      { client: 'Civic Aid Co.',name: 'Poster series',    color: window.TRACE ? window.TRACE.amber : '#E3B23C', hours: 1.0, frac: 0.14 },
      { client: 'Internal',     name: 'Invoicing',        color: window.TRACE ? window.TRACE.grey : '#9CA3AF', hours: 1.1, frac: 0.16 },
    ],
    timeline: [
      { t: '09:30 – 12:05', task: 'Website redesign — homepage layout', client: 'Nova Studio', method: 'rule' },
      { t: '12:05 – 12:20', task: 'Invoicing', client: 'Internal', method: 'manual' },
      { t: '13:30 – 15:00', task: 'Poster series — concepts', client: 'Civic Aid Co.', method: 'ai' },
      { t: '15:00 – 16:48', task: 'Branding retainer — moodboard', client: 'Bloom Cafe', method: 'rule' },
    ],
  },
};

const METHOD_COLORS = { rule: '#00A6FB', ai: '#A855F7', manual: '#16a34a' };
const METHOD_LABEL = { rule: 'rule', ai: 'ai', manual: 'you' };

const MethodBadge = ({ method }) => {
  const color = METHOD_COLORS[method];
  return (
    <span style={{
      fontSize: 10.5, fontWeight: 600, letterSpacing: '0.02em',
      color, background: `${color}22`, borderRadius: 999,
      padding: '2px 8px', whiteSpace: 'nowrap', textTransform: 'uppercase',
    }}>{METHOD_LABEL[method]}</span>
  );
};

const TraceLiveDemo = () => {
  const t = window.TRACE;
  const [persona, setPersona] = React.useState('consultant');
  const [view, setView] = React.useState('dashboard');
  const [fill, setFill] = React.useState(0);
  const data = PERSONAS[persona];

  React.useEffect(() => {
    setFill(0);
    let raf;
    const start = performance.now();
    const DURATION = 1100;
    const tick = (now) => {
      const p = clamp((now - start) / DURATION, 0, 1);
      setFill(1 - Math.pow(1 - p, 3));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [persona]);

  const totalHours = data.items.reduce((s, x) => s + x.hours, 0);

  return (
    <section id="inside-trace" className="trace-demo" style={{
      padding: '40px 48px 110px', fontFamily: t.sans,
      borderTop: `1px solid ${t.hair}`,
    }}>
      <div style={{ textAlign: 'center', marginBottom: 36 }}>
        <Eyebrow style={{ justifyContent: 'center', display: 'flex', marginBottom: 14 }}>Inside Trace</Eyebrow>
        <h2 style={{
          fontFamily: t.sans, fontSize: 'clamp(30px, 3.6vw, 44px)',
          letterSpacing: '-0.02em', fontWeight: 700, color: t.ink, margin: '0 0 12px',
        }}>
          See it as you.
        </h2>
        <p style={{ fontSize: 15.5, color: t.dim, maxWidth: 480, margin: '0 auto' }}>
          Click around — this is real Trace UI, running on sample data.
          Pick the persona closest to how you work.
        </p>
      </div>

      {/* Persona toggle */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 28 }}>
        {Object.keys(PERSONAS).map(key => {
          const active = key === persona;
          return (
            <button key={key} onClick={() => { setPersona(key); }} style={{
              padding: '9px 18px', borderRadius: 999, fontSize: 13.5,
              border: `1px solid ${active ? t.ink : t.hair}`,
              background: active ? t.ink : 'transparent',
              color: active ? t.bg : t.dim,
              cursor: 'pointer', fontFamily: t.sans, fontWeight: 500,
              transition: 'all 160ms',
            }}>{PERSONAS[key].label}</button>
          );
        })}
      </div>

      <div style={{ maxWidth: 920, margin: '0 auto' }}>
        <MockWindow width="100%" height={560} title={`Trace · ${view[0].toUpperCase()}${view.slice(1)}`} style={{ position: 'relative' }}>
          <div className="trace-demo-body" style={{ display: 'flex', height: '100%' }}>
            <div className="trace-sidebar-wrap">
              <TraceSidebar activeView={view} onSelect={setView} height="100%" />
            </div>
            <div style={{ flex: 1, minWidth: 0, overflow: 'auto', padding: '26px 30px' }}>

              {view === 'dashboard' && (
                <div>
                  <Eyebrow>{data.day}</Eyebrow>
                  <div style={{ fontFamily: t.serif, fontSize: 26, color: t.ink, margin: '4px 0 20px' }}>
                    Today, <em>in motion</em>.
                  </div>
                  <div style={{ display: 'flex', gap: 32, alignItems: 'center', flexWrap: 'wrap' }}>
                    <DayArc size={190} segments={data.items.map(i => ({ frac: i.frac, color: i.color }))}
                      fill={fill} label="TRACKED" sublabel={`${(fill * totalHours).toFixed(1)}h`} />
                    <Card padding={16} style={{ flex: 1, minWidth: 220 }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                        <Eyebrow style={{ marginBottom: 0 }}>Right now</Eyebrow>
                        <span style={{
                          fontSize: 10, fontWeight: 600, letterSpacing: '0.04em',
                          color: t.sky, background: `${t.sky}1a`, borderRadius: 999,
                          padding: '2px 8px',
                        }}>AUTO</span>
                      </div>
                      <div style={{ fontFamily: t.serif, fontSize: 19, color: t.ink }}>{data.right.task}</div>
                      <div style={{ fontSize: 13, color: t.dim, marginTop: 4 }}>{data.right.sub}</div>
                      <div style={{ fontSize: 11.5, color: t.faint, marginTop: 10 }}>elapsed {data.right.elapsed} · auto-classified</div>
                    </Card>
                  </div>

                  <div style={{ marginTop: 26 }}>
                    <Eyebrow style={{ marginBottom: 12 }}>By project · today</Eyebrow>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                      {data.items.map(row => (
                        <div key={row.client} style={{ display: 'grid', gridTemplateColumns: '150px minmax(0,1fr) 44px', gap: 12, alignItems: 'center' }}>
                          <div style={{ fontSize: 12.5, color: t.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: 999, background: row.color, marginRight: 7 }} />
                            {row.client}
                          </div>
                          <div style={{ height: 6, borderRadius: 999, background: t.hair2, overflow: 'hidden' }}>
                            <div style={{ width: `${row.frac * 100}%`, height: '100%', background: row.color, borderRadius: 999 }} />
                          </div>
                          <div style={{ fontSize: 12.5, color: t.ink, textAlign: 'right' }}>{row.hours.toFixed(1)}h</div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {view === 'timeline' && (
                <div>
                  <Eyebrow>{data.day}</Eyebrow>
                  <div style={{ fontFamily: t.serif, fontSize: 26, color: t.ink, margin: '4px 0 8px' }}>The day, in order.</div>
                  <div style={{ fontSize: 12.5, color: t.faint, marginBottom: 16 }}>
                    Auto-categorized by rule, by AI, or by you.
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column' }}>
                    {data.timeline.map((row, i) => {
                      const proj = data.items.find(p => p.client === row.client);
                      return (
                        <div key={i} className="trace-timeline-row" style={{
                          display: 'grid', gridTemplateColumns: '110px minmax(0,1fr) auto auto', gap: 10,
                          padding: '13px 0', alignItems: 'center',
                          borderTop: i === 0 ? 'none' : `1px solid ${t.hair2}`,
                        }}>
                          <span style={{ fontSize: 11.5, color: t.faint, whiteSpace: 'nowrap' }}>{row.t}</span>
                          <span style={{ fontSize: 13.5, color: t.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.task}</span>
                          <MethodBadge method={row.method} />
                          <span style={{
                            fontSize: 11, color: t.dim, whiteSpace: 'nowrap',
                            display: 'flex', alignItems: 'center', gap: 6,
                          }}>
                            <span style={{ width: 6, height: 6, borderRadius: 999, background: proj ? proj.color : t.grey }} />
                            {row.client}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {view === 'projects' && (
                <div>
                  <Eyebrow>Your projects</Eyebrow>
                  <div style={{ fontFamily: t.serif, fontSize: 26, color: t.ink, margin: '4px 0 20px' }}>Every signal, sorted.</div>
                  <div className="trace-projects-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 14 }}>
                    {data.items.map(row => (
                      <Card key={row.client} padding={18}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11, color: t.faint, marginBottom: 6 }}>
                          <span style={{ width: 7, height: 7, borderRadius: 999, background: row.color }} />
                          {row.name.toUpperCase()}
                        </div>
                        <div style={{ fontFamily: t.serif, fontSize: 20, color: t.ink, marginBottom: 10 }}>{row.client}</div>
                        <div style={{ height: 5, borderRadius: 999, background: t.hair2, overflow: 'hidden', marginBottom: 8 }}>
                          <div style={{ width: `${clamp(row.frac * 2.4, 0, 1) * 100}%`, height: '100%', background: row.color, borderRadius: 999 }} />
                        </div>
                        <div style={{ fontSize: 11.5, color: t.faint }}>{row.hours.toFixed(1)}h logged today</div>
                      </Card>
                    ))}
                  </div>
                </div>
              )}

              {view === 'rules' && (
                <div>
                  <Eyebrow>How it knows</Eyebrow>
                  <div style={{ fontFamily: t.serif, fontSize: 26, color: t.ink, margin: '4px 0 8px' }}>Rules you write.</div>
                  <div style={{ fontSize: 12.5, color: t.faint, marginBottom: 16, maxWidth: 420 }}>
                    Patterns it learns. Never your data leaving. Every rule below runs entirely on-device.
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {[
                      { match: 'Figma', goesTo: 'Acme · Brand refresh' },
                      { match: 'calendar.google.com', goesTo: 'Meetings' },
                      { match: 'northwind.com/*', goesTo: 'Northwind · Q3 retainer' },
                    ].map((r, i) => (
                      <Card key={i} padding={14} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <MethodBadge method="rule" />
                        <span style={{ fontSize: 13, color: t.ink, fontFamily: t.mono, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.match}</span>
                        <span style={{ fontSize: 12, color: t.faint }}>→</span>
                        <span style={{ fontSize: 13, color: t.dim, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.goesTo}</span>
                      </Card>
                    ))}
                  </div>
                </div>
              )}

              {view === 'settings' && (
                <div style={{
                  height: '100%', display: 'flex', flexDirection: 'column',
                  alignItems: 'center', justifyContent: 'center', textAlign: 'center',
                  color: t.faint, gap: 8,
                }}>
                  <div style={{ fontFamily: t.serif, fontSize: 20, color: t.dim, fontStyle: 'italic' }}>
                    Coming soon
                  </div>
                  <div style={{ fontSize: 12.5, maxWidth: 260 }}>
                    Account &amp; sync settings ship with the full app.
                  </div>
                </div>
              )}
            </div>
          </div>
        </MockWindow>
      </div>
    </section>
  );
};

window.TraceLiveDemo = TraceLiveDemo;
