// views.jsx — OpenDicta page bodies

const { useState, useEffect, useMemo } = React;

// ── Shared atoms ────────────────────────────────────────────

function PageHead({ eyebrow, title, sub, children }) {
  return (
    <div className="page-head">
      <div>
        <div className="page-eyebrow">{eyebrow}</div>
        <h1 className="page-title">{title}</h1>
        {sub && <div className="page-sub">{sub}</div>}
      </div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexShrink: 0 }}>
        {children}
      </div>
    </div>
  );
}

// ── 1. DASHBOARD ────────────────────────────────────────────

function Dashboard({ userName, accent }) {
  const hour = new Date().getHours();
  const greet = hour < 5 ? 'Up late' : hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';

  return (
    <div className="page">
      <PageHead
        eyebrow="Dashboard"
        title={<>{greet}, <em>{userName}</em> <span style={{display:'inline-block',transform:'rotate(8deg)'}}>👋</span></>}
        sub="Here's your speech-to-text snapshot for today."
      >
        <button className="btn btn-sm">
          <Icon.Search style={{width:14,height:14}} /> Browse history
        </button>
        <button className="btn btn-accent btn-sm">
          <Icon.Mic style={{width:14,height:14}} /> New recording
        </button>
      </PageHead>

      {/* Stat row */}
      <div className="grid grid-3" style={{ marginBottom: 18 }}>
        <StatCard
          label="Today's words"
          value="2,847"
          unit="words"
          trend="+18% vs yesterday"
          accent
          inset={<MiniBars data={[0.3,0.5,0.4,0.7,0.6,0.85,0.95]} />}
        />
        <StatCard
          label="Average WPM"
          value="148"
          unit="wpm"
          trend="Up from 132 last week"
          inset={<MiniLine />}
        />
        <StatCard
          label="Hours saved"
          value="42.6"
          unit="this month"
          trend="vs typing at 38 wpm"
          dark
          inset={<HoursPie pct={0.71} />}
        />
      </div>

      {/* Latest transcript + side */}
      <div className="row" style={{alignItems:'stretch'}}>
        <div className="card card-lg" style={{ flex: 2, display:'flex', flexDirection:'column' }}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14}}>
            <div>
              <div style={{fontSize:11, fontWeight:500, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--ink-3)'}}>Latest transcript</div>
              <div style={{fontSize:20, fontWeight:600, marginTop:6, color:'var(--ink-1)'}}>Q3 planning kickoff notes</div>
              <div style={{fontSize:12.5, color:'var(--ink-3)', marginTop:4}}>14 minutes ago · 04:32 duration · 612 words · Whisper Pro</div>
            </div>
            <div style={{display:'flex',gap:8}}>
              <button className="btn btn-sm btn-ghost"><Icon.Copy style={{width:14,height:14}}/> Copy</button>
              <button className="btn btn-sm"><Icon.Play style={{width:12,height:12}}/> Play</button>
            </div>
          </div>

          {/* Waveform */}
          <Waveform />

          {/* Transcript text */}
          <div style={{
            fontSize:14.5, lineHeight:1.6, color:'var(--ink-2)',
            marginTop:18, padding:'18px 20px',
            background:'var(--bg-sunken)', borderRadius:16,
            border:'0.5px solid var(--line)'
          }}>
            <span style={{background:'color-mix(in oklch, var(--accent) 50%, transparent)', padding:'0 2px', borderRadius:3}}>Okay so for Q3</span>, the three big bets we landed on are
            shipping the new transcript editor, cutting model latency below 300ms,
            and finally tackling the team-sharing flow that's been on the backlog
            since spring. I think if we sequence those right — editor first because
            it unblocks design, then latency since infra is already half-done…
            <span style={{color:'var(--ink-3)'}}> and the rest is a separate conversation about resourcing.</span>
          </div>

          <div style={{marginTop:'auto', paddingTop:18, display:'flex', gap:10}}>
            <button className="btn btn-primary"><Icon.Edit style={{width:14,height:14}}/> Open in editor</button>
            <button className="btn"><Icon.Mail style={{width:14,height:14}}/> Send as email</button>
            <button className="btn btn-ghost mt-auto">
              <Icon.Sparkle style={{width:14,height:14}}/> Refine with AI
            </button>
          </div>
        </div>

        <div className="col" style={{flex:1, minWidth:0}}>
          <div className="card">
            <h3>Recording streak</h3>
            <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:2}}>
              <div className="stat-num" style={{fontSize:36}}>23</div>
              <span className="stat-unit">days</span>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(14, 1fr)', gap:4, marginTop:14}}>
              {Array.from({length:28}).map((_,i)=>{
                const active = i < 23 || (i>=24 && i<27);
                return <div key={i} style={{
                  aspectRatio:'1', borderRadius:4,
                  background: active ? 'var(--accent)' : 'var(--bg-sunken)',
                  border:'0.5px solid var(--line)'
                }}/>;
              })}
            </div>
          </div>

          <div className="card" style={{flex:1, display:'flex', flexDirection:'column'}}>
            <h3>Recent sessions</h3>
            <div style={{display:'flex', flexDirection:'column', gap:2, marginTop:8, flex:1}}>
              {[
                {t:'Q3 planning kickoff notes', d:'14m ago', w:612},
                {t:'Customer call — Acme Co.', d:'2h ago', w:1840},
                {t:'Morning journal', d:'8h ago', w:294},
                {t:'Voice memo to self', d:'Yesterday', w:127},
                {t:'Standup recap', d:'Yesterday', w:438},
              ].map((s,i)=>(
                <div key={i} style={{
                  display:'flex', justifyContent:'space-between', alignItems:'center',
                  padding:'10px 4px', borderBottom: i<4 ? '0.5px solid var(--line)' : 'none'
                }}>
                  <div style={{minWidth:0, flex:1}}>
                    <div style={{fontSize:13, fontWeight:500, color:'var(--ink-1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{s.t}</div>
                    <div style={{fontSize:11.5, color:'var(--ink-3)', marginTop:2}}>{s.d}</div>
                  </div>
                  <div className="mono tnum" style={{fontSize:12, color:'var(--ink-3)'}}>{s.w}w</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, unit, trend, accent, dark, inset }) {
  const cls = 'card' + (accent ? ' card-accent' : '') + (dark ? ' card-dark' : '');
  return (
    <div className={cls} style={{display:'flex', flexDirection:'column', gap:12, position:'relative', overflow:'hidden'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start'}}>
        <h3>{label}</h3>
        {!accent && !dark && <div style={{width:8, height:8, borderRadius:'50%', background:'var(--accent)'}}/>}
      </div>
      <div style={{display:'flex', alignItems:'baseline', gap:6}}>
        <div className="stat-num">{value}</div>
        <span className="stat-unit">{unit}</span>
      </div>
      <div style={{
        fontSize: 12.5,
        color: accent ? 'rgba(0,0,0,0.55)' : dark ? 'oklch(70% 0.008 85)' : 'var(--ink-3)'
      }}>{trend}</div>
      <div style={{marginTop:8}}>{inset}</div>
    </div>
  );
}

function MiniBars({ data }) {
  return (
    <div style={{display:'flex', alignItems:'flex-end', gap:5, height:42}}>
      {data.map((v,i)=>(
        <div key={i} style={{
          flex:1, height:`${v*100}%`,
          background:'rgba(0,0,0,0.78)', borderRadius:'4px 4px 4px 4px',
          minHeight:6
        }}/>
      ))}
    </div>
  );
}

function MiniLine() {
  // Simple SVG sparkline
  const pts = [12, 18, 14, 24, 22, 30, 28, 36, 34, 42];
  const w = 100, h = 42;
  const max = Math.max(...pts), min = Math.min(...pts);
  const path = pts.map((v,i)=>{
    const x = (i/(pts.length-1))*w;
    const y = h - ((v-min)/(max-min))*h;
    return `${i===0?'M':'L'}${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{width:'100%', height:42}}>
      <path d={`${path} L${w} ${h} L0 ${h} Z`} fill="var(--accent)" opacity="0.35"/>
      <path d={path} fill="none" stroke="var(--ink-1)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={w} cy={h - ((pts[pts.length-1]-min)/(max-min))*h} r="3" fill="var(--ink-1)"/>
    </svg>
  );
}

function HoursPie({ pct }) {
  const r = 18, c = 2*Math.PI*r;
  return (
    <div style={{display:'flex', alignItems:'center', gap:12}}>
      <svg viewBox="0 0 50 50" style={{width:44, height:44}}>
        <circle cx="25" cy="25" r={r} fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="6"/>
        <circle cx="25" cy="25" r={r} fill="none" stroke="var(--accent)" strokeWidth="6"
                strokeDasharray={`${c*pct} ${c}`} strokeLinecap="round"
                transform="rotate(-90 25 25)"/>
      </svg>
      <div style={{fontSize:11.5, color:'oklch(70% 0.008 85)'}}>71% to monthly goal</div>
    </div>
  );
}

function Waveform() {
  const bars = useMemo(()=>Array.from({length:60}).map((_,i)=>{
    // pseudo-random but stable
    const v = Math.abs(Math.sin(i * 0.7) * 0.5 + Math.cos(i*0.3)*0.3 + 0.2);
    return Math.min(1, v);
  }),[]);
  const played = 0.42;
  return (
    <div style={{display:'flex', alignItems:'center', gap:3, height:54, padding:'0 4px'}}>
      {bars.map((v,i)=>{
        const isPlayed = (i/bars.length) < played;
        return <div key={i} style={{
          flex:1, height:`${v*100}%`, minHeight:4,
          background: isPlayed ? 'var(--ink-1)' : 'oklch(85% 0.005 85)',
          borderRadius: 999
        }}/>;
      })}
    </div>
  );
}

// ── 2. INSIGHTS ─────────────────────────────────────────────

function Insights() {
  return (
    <div className="page">
      <PageHead
        eyebrow="Insights"
        title={<>This week's <em>activity</em>.</>}
        sub="Three rings to close. You're crushing two of them."
      >
        <div className="chip">Week of Nov 11</div>
        <button className="btn btn-sm">Export</button>
      </PageHead>

      <div className="row" style={{alignItems:'stretch', marginBottom:18}}>
        <div className="card card-lg" style={{flex:'0 0 380px', display:'flex', alignItems:'center', justifyContent:'center', padding:20}}>
          <ActivityRings />
        </div>
        <div className="col" style={{flex:1}}>
          <RingStat color="oklch(74% 0.16 145)" name="Words" value="38,420" goal="50,000 word goal" pct={77} icon={<Icon.Wave style={{width:18,height:18}}/>} />
          <RingStat color="oklch(72% 0.18 50)"  name="Speaking hours" value="6h 12m" goal="8h weekly goal" pct={78} icon={<Icon.Clock style={{width:18,height:18}}/>} />
          <RingStat color="oklch(70% 0.20 320)" name="Milestones"  value="11 of 14" goal="Daily streaks + sessions" pct={79} icon={<Icon.Trophy style={{width:18,height:18}}/>} />
        </div>
      </div>

      <div className="row" style={{marginBottom:18}}>
        <div className="card card-lg" style={{flex:2}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18}}>
            <div>
              <h3>Words per day</h3>
              <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:2}}>
                <div className="stat-num" style={{fontSize:30}}>5,489</div>
                <span className="stat-unit">avg / day</span>
              </div>
            </div>
            <div style={{display:'flex', gap:14, fontSize:11.5, color:'var(--ink-3)'}}>
              <Legend color="var(--ink-1)" label="Words"/>
              <Legend color="var(--accent)" label="Goal"/>
            </div>
          </div>
          <DayChart />
        </div>
        <div className="card card-lg" style={{flex:1}}>
          <h3>Personal bests</h3>
          <div style={{display:'flex', flexDirection:'column', gap:14, marginTop:14}}>
            <PB label="Longest session" value="58 min" sub="Tuesday · journaling"/>
            <PB label="Fastest WPM" value="187 wpm" sub="Yesterday · quick memo"/>
            <PB label="Best streak" value="23 days" sub="Active streak"/>
            <PB label="Most words / day" value="9,142" sub="Nov 13 · interview prep"/>
          </div>
        </div>
      </div>

      <div className="grid grid-3">
        <Tip
          icon={<Icon.Bolt style={{width:18,height:18}}/>}
          title="Skip the punctuation pause"
          body="OpenDicta auto-inserts periods when you pause 1.2s. Speak through them and let the model handle it — users gain ~14% WPM."
        />
        <Tip
          icon={<Icon.Sparkle style={{width:18,height:18}}/>}
          title="Try the Studio model for interviews"
          body="Slower but catches names, brands, and overlapping speakers far better than Parakeet V3."
        />
        <Tip
          icon={<Icon.Mic style={{width:18,height:18}}/>}
          title="Mic 6cm, not 30cm"
          body="Your input level averaged 38%. Move your mic closer or run diagnostics — quality jumps noticeably."
        />
      </div>
    </div>
  );
}

function ActivityRings() {
  const rings = [
    { r: 88, w: 18, pct: 0.77, color: 'oklch(74% 0.16 145)' },
    { r: 64, w: 18, pct: 0.78, color: 'oklch(72% 0.18 50)' },
    { r: 40, w: 18, pct: 0.79, color: 'oklch(70% 0.20 320)' },
  ];
  return (
    <svg viewBox="0 0 240 240" style={{width:300, height:300}}>
      <defs>
        <filter id="ringShadow"><feDropShadow dx="0" dy="2" stdDeviation="2" floodOpacity="0.18"/></filter>
      </defs>
      {rings.map((r,i)=>{
        const c = 2*Math.PI*r.r;
        return (
          <g key={i} transform="translate(120 120)">
            <circle r={r.r} fill="none" stroke={r.color} strokeOpacity="0.18" strokeWidth={r.w}/>
            <circle r={r.r} fill="none" stroke={r.color} strokeWidth={r.w}
                    strokeDasharray={`${c*r.pct} ${c}`}
                    strokeLinecap="round"
                    transform="rotate(-90)"
                    style={{filter:'url(#ringShadow)'}}/>
          </g>
        );
      })}
      <text x="120" y="118" textAnchor="middle" fontSize="11" fontWeight="600" fill="var(--ink-3)" letterSpacing="1" style={{textTransform:'uppercase'}}>This week</text>
      <text x="120" y="138" textAnchor="middle" fontSize="22" fontWeight="600" fill="var(--ink-1)" fontFamily="Instrument Serif">78% complete</text>
    </svg>
  );
}

function RingStat({ color, name, value, goal, pct, icon }) {
  return (
    <div className="card" style={{flex:1, display:'flex', alignItems:'center', gap:18}}>
      <div style={{width:44, height:44, borderRadius:14, background:`color-mix(in oklch, ${color} 28%, white)`, color:`color-mix(in oklch, ${color} 70%, black)`, display:'flex', alignItems:'center', justifyContent:'center'}}>
        {icon}
      </div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontSize:12, color:'var(--ink-3)', fontWeight:500}}>{name}</div>
        <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:2}}>
          <div style={{fontSize:24, fontWeight:600, color:'var(--ink-1)', letterSpacing:'-0.01em'}}>{value}</div>
        </div>
        <div style={{fontSize:11.5, color:'var(--ink-3)', marginTop:2}}>{goal}</div>
      </div>
      <div style={{width:64, height:64, position:'relative', flexShrink:0}}>
        <svg viewBox="0 0 64 64" style={{width:'100%', height:'100%'}}>
          <circle cx="32" cy="32" r="26" fill="none" stroke={color} strokeOpacity="0.18" strokeWidth="6"/>
          <circle cx="32" cy="32" r="26" fill="none" stroke={color} strokeWidth="6"
                  strokeDasharray={`${2*Math.PI*26*pct/100} ${2*Math.PI*26}`}
                  strokeLinecap="round" transform="rotate(-90 32 32)"/>
        </svg>
        <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', fontSize:12, fontWeight:600, color:'var(--ink-1)'}}>{pct}%</div>
      </div>
    </div>
  );
}

function Legend({ color, label }) {
  return <div style={{display:'flex', alignItems:'center', gap:6}}>
    <span style={{width:9, height:9, borderRadius:'50%', background:color}}/>{label}
  </div>;
}

function DayChart() {
  const data = [
    {d:'Mon', v:4200, g:5000},
    {d:'Tue', v:5800, g:5000},
    {d:'Wed', v:3100, g:5000},
    {d:'Thu', v:7200, g:5000},
    {d:'Fri', v:6900, g:5000},
    {d:'Sat', v:2400, g:5000},
    {d:'Sun', v:8800, g:5000},
  ];
  const max = 10000;
  return (
    <div>
      <div style={{display:'flex', alignItems:'flex-end', gap:14, height:180, padding:'0 4px'}}>
        {data.map((day,i)=>(
          <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:6, height:'100%'}}>
            <div style={{flex:1, width:'100%', display:'flex', alignItems:'flex-end', position:'relative'}}>
              {/* goal line */}
              <div style={{position:'absolute', left:0, right:0, bottom:`${(day.g/max)*100}%`, height:1.5, background:'var(--accent)', opacity:.85, borderRadius:1}}/>
              <div style={{width:'100%', height:`${(day.v/max)*100}%`, background:'var(--ink-1)', borderRadius:'10px 10px 4px 4px', position:'relative'}}>
                {i===6 && (
                  <div style={{position:'absolute', top:-26, left:'50%', transform:'translateX(-50%)', background:'var(--ink-1)', color:'oklch(98% 0.005 85)', fontSize:11, fontWeight:600, padding:'3px 8px', borderRadius:6}}>
                    {day.v.toLocaleString()}
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
      <div style={{display:'flex', gap:14, padding:'0 4px', marginTop:8}}>
        {data.map((day,i)=>(
          <div key={i} style={{flex:1, textAlign:'center', fontSize:11.5, color:'var(--ink-3)', fontWeight:500}}>{day.d}</div>
        ))}
      </div>
    </div>
  );
}

function PB({ label, value, sub }) {
  return (
    <div>
      <div style={{fontSize:11.5, color:'var(--ink-3)', fontWeight:500, letterSpacing:'.02em'}}>{label}</div>
      <div style={{fontSize:20, fontWeight:600, color:'var(--ink-1)', letterSpacing:'-0.01em', marginTop:2}}>{value}</div>
      <div style={{fontSize:11.5, color:'var(--ink-4)', marginTop:1}}>{sub}</div>
    </div>
  );
}

function Tip({ icon, title, body }) {
  return (
    <div className="card" style={{display:'flex', flexDirection:'column', gap:10}}>
      <div style={{width:36, height:36, borderRadius:10, background:'var(--accent-soft)', color:'var(--ink-1)', display:'flex', alignItems:'center', justifyContent:'center'}}>{icon}</div>
      <div style={{fontSize:14.5, fontWeight:600, color:'var(--ink-1)', lineHeight:1.3}}>{title}</div>
      <div style={{fontSize:13, lineHeight:1.5, color:'var(--ink-2)'}}>{body}</div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.Insights = Insights;
