// views-2.jsx — Models, Style, AI, Settings

const { useState: useState2, useEffect: useEffect2 } = React;

// ── 3. MODELS ───────────────────────────────────────────────

const MODELS = [
  {
    id: 'parakeet-v3',
    name: 'Parakeet V3',
    tag: 'Lightning-fast streaming',
    desc: 'Real-time transcription with sub-200ms latency. Best for live dictation, voice commands, and quick memos where speed matters most.',
    perf: 96, qual: 72,
    size: '142 MB',
    badge: 'Default'
  },
  {
    id: 'whisper-pro',
    name: 'Whisper Pro',
    tag: 'Balanced accuracy',
    desc: "The all-rounder. Handles accents, technical jargon, and noisy rooms well. Use this when you don't know what you'll be recording.",
    perf: 72, qual: 86,
    size: '780 MB',
    badge: 'Recommended'
  },
  {
    id: 'qwen',
    name: 'Qwen',
    tag: 'Multilingual specialist',
    desc: 'Trained on 100+ languages with strong code-switching. Pick this if you record in non-English or mixed-language settings.',
    perf: 58, qual: 90,
    size: '1.2 GB'
  },
  {
    id: 'parakeet-v2',
    name: 'Parakeet V2',
    tag: 'Legacy fast',
    desc: 'The previous-gen real-time model. Slightly less accurate than V3 but uses ~40% less CPU — handy on older hardware.',
    perf: 90, qual: 65,
    size: '98 MB'
  },
  {
    id: 'studio',
    name: 'Studio',
    tag: 'Maximum accuracy',
    desc: 'Frontier-grade quality with speaker diarization, punctuation, and disfluency cleanup. Slower (~3× realtime) — use for interviews, podcasts, court transcripts.',
    perf: 32, qual: 98,
    size: '2.8 GB',
    badge: 'Pro'
  },
];

function Models() {
  const [active, setActive] = useState2('whisper-pro');
  const [hovered, setHovered] = useState2(null);

  return (
    <div className="page">
      <PageHead
        eyebrow="Models"
        title={<>Pick your <em>transcription</em> engine.</>}
        sub="Hover any model to see what it's best for. Hot-swap any time — no restart needed."
      >
        <div className="chip"><Icon.Check style={{width:12,height:12}}/> 3 of 5 downloaded</div>
      </PageHead>

      <div className="grid grid-3" style={{gap:16}}>
        {MODELS.map(m => (
          <ModelCard
            key={m.id}
            model={m}
            active={active === m.id}
            hovered={hovered === m.id}
            onSelect={() => setActive(m.id)}
            onHover={() => setHovered(m.id)}
            onLeave={() => setHovered(null)}
          />
        ))}

        {/* explainer slot to fill the 6th cell */}
        <div className="card card-dark" style={{display:'flex', flexDirection:'column', gap:14, justifyContent:'space-between'}}>
          <div>
            <h3 style={{color:'oklch(75% 0.008 85)'}}>How the scale works</h3>
            <div style={{fontSize:14, lineHeight:1.5, color:'oklch(90% 0.005 85)', marginTop:10}}>
              Every model trades speed for accuracy. Left of the bar means it's
              fast and uses less CPU. Right means it catches more nuance — names,
              accents, overlapping speakers — but takes longer.
            </div>
          </div>
          <div style={{display:'flex', gap:10, alignItems:'center'}}>
            <SpeedQualityBar perf={50} qual={50} mini dark/>
            <div style={{fontSize:11.5, color:'oklch(75% 0.008 85)'}}>Speed ⟷ Accuracy</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ModelCard({ model, active, hovered, onSelect, onHover, onLeave }) {
  return (
    <button
      onClick={onSelect}
      onMouseEnter={onHover}
      onMouseLeave={onLeave}
      className="card"
      style={{
        textAlign:'left',
        cursor:'pointer',
        border: active ? `1.5px solid var(--ink-1)` : '0.5px solid var(--line)',
        background: active ? 'var(--bg-card)' : 'var(--bg-card)',
        boxShadow: active
          ? '0 1px 2px rgba(0,0,0,0.05), 0 12px 30px -14px rgba(0,0,0,0.22), inset 0 0 0 2.5px var(--accent)'
          : 'var(--shadow-card)',
        transform: hovered ? 'translateY(-2px)' : 'none',
        transition:'transform .15s, box-shadow .15s, border-color .15s',
        position:'relative',
        minHeight: 220,
        display:'flex', flexDirection:'column', gap:12,
        font:'inherit', color:'inherit',
        padding: 22,
      }}
    >
      {/* Header */}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start'}}>
        <div>
          <div style={{fontSize:17, fontWeight:600, color:'var(--ink-1)', letterSpacing:'-0.01em'}}>{model.name}</div>
          <div style={{fontSize:12.5, color:'var(--ink-3)', marginTop:2}}>{model.tag}</div>
        </div>
        <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6}}>
          {model.badge && <span className={"chip " + (model.badge === 'Pro' ? 'chip-dark' : 'chip-accent')}>{model.badge}</span>}
          {active && <span className="chip chip-accent"><Icon.Check style={{width:10,height:10}}/> Active</span>}
        </div>
      </div>

      {/* Description (always visible at small size; expands on hover) */}
      <div style={{
        fontSize: 12.5, lineHeight: 1.5,
        color: hovered ? 'var(--ink-2)' : 'var(--ink-3)',
        flex:1,
        transition:'color .15s'
      }}>
        {model.desc}
      </div>

      {/* Perf vs Quality bar */}
      <div style={{marginTop:'auto'}}>
        <SpeedQualityBar perf={model.perf} qual={model.qual} />
        <div style={{display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--ink-3)', marginTop:8, fontWeight:500}}>
          <span>SPEED · {model.perf}</span>
          <span className="mono tnum" style={{color:'var(--ink-4)'}}>{model.size}</span>
          <span>QUALITY · {model.qual}</span>
        </div>
      </div>
    </button>
  );
}

function SpeedQualityBar({ perf, qual, mini, dark }) {
  // Two opposing horizontal bars meeting in the middle.
  // The dot moves along the axis based on perf vs qual balance.
  const total = perf + qual;
  const bias = (qual / total); // 0 = full speed, 1 = full quality
  const h = mini ? 6 : 8;
  return (
    <div style={{position:'relative', height:h+12, marginTop: mini ? 0 : 4}}>
      <div style={{
        position:'absolute', left:0, right:0, top:6, height:h, borderRadius:999,
        background: dark ? 'oklch(28% 0.005 60)' : 'var(--bg-sunken)',
        border: dark ? '0' : '0.5px solid var(--line)',
        overflow:'hidden'
      }}>
        {/* Speed side (left, dark) */}
        <div style={{
          position:'absolute', left:0, top:0, bottom:0,
          width:`${(1-bias)*100}%`,
          background: dark ? 'oklch(95% 0.005 85)' : 'var(--ink-1)'
        }}/>
        {/* Quality side (right, accent) */}
        <div style={{
          position:'absolute', right:0, top:0, bottom:0,
          width:`${bias*100}%`,
          background:'var(--accent)'
        }}/>
      </div>
      {/* Indicator dot at the boundary */}
      <div style={{
        position:'absolute', top:0, left:`calc(${(1-bias)*100}% - ${h+1}px)`,
        width:h+10, height:h+10, borderRadius:'50%',
        background:'white',
        border: '1.5px solid var(--ink-1)',
        boxShadow:'0 1px 4px rgba(0,0,0,0.18)'
      }}/>
    </div>
  );
}

// ── 4. STYLE ────────────────────────────────────────────────

const STYLES = [
  { id:'raw',     name:'Raw transcript', desc:'Verbatim. Nothing changed.', icon:'Mic',       hint:'Word-for-word, no clean-up.' },
  { id:'grammar', name:'Fix grammar',    desc:'Punctuation + sentence flow.', icon:'Check', hint:'Removes "uh", "um", fixes runs.' },
  { id:'email',   name:'Email',          desc:'Subject + greeting + sign-off.', icon:'Mail', hint:'Drafts a ready-to-send email.' },
  { id:'prompt',  name:'Prompt engineering', desc:'Reformats into a clean LLM prompt.', icon:'Code', hint:'Adds context, role, constraints.' },
  { id:'pro',     name:'Professional + todo', desc:'Business tone, extracts action items.', icon:'Briefcase', hint:'For meeting recaps and standups.' },
  { id:'bullets', name:'Bullet points',  desc:'Hierarchical bullet list.', icon:'List', hint:'Great for notes and outlines.' },
  { id:'chat',    name:'Slack message',  desc:'Short, casual, with emoji.', icon:'Chat', hint:'Drops the formality.' },
  { id:'summary', name:'TL;DR summary',  desc:'Compresses to 3-5 sentences.', icon:'Sparkle', hint:'Keeps the gist, ditches the rest.' },
];

function Style({ aiEnabled }) {
  const [selected, setSelected] = useState2('grammar');

  const body = (
    <>
      <div className="grid grid-4" style={{gap:14}}>
        {STYLES.map(s => {
          const Ico = Icon[s.icon] || Icon.Sparkle;
          const on = selected === s.id;
          return (
            <button
              key={s.id}
              onClick={() => setSelected(s.id)}
              className="card"
              style={{
                textAlign:'left', cursor:'pointer',
                border: on ? '1.5px solid var(--ink-1)' : '0.5px solid var(--line)',
                background: on ? 'var(--ink-1)' : 'var(--bg-card)',
                color: on ? 'oklch(98% 0.005 85)' : 'var(--ink-1)',
                font:'inherit', display:'flex', flexDirection:'column', gap:12,
                minHeight:160, padding:18,
                transition:'transform .12s, background .15s',
                position:'relative'
              }}
            >
              <div style={{
                width:38, height:38, borderRadius:11,
                background: on ? 'var(--accent)' : 'var(--bg-sunken)',
                color: on ? '#1a1a1a' : 'var(--ink-1)',
                display:'flex', alignItems:'center', justifyContent:'center'
              }}>
                <Ico style={{width:18, height:18}}/>
              </div>
              <div style={{fontSize:15, fontWeight:600, letterSpacing:'-0.01em'}}>{s.name}</div>
              <div style={{fontSize:12, color: on ? 'oklch(75% 0.008 85)' : 'var(--ink-3)', lineHeight:1.45}}>{s.desc}</div>
              {on && (
                <div style={{position:'absolute', top:14, right:14, width:22, height:22, borderRadius:'50%', background:'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center', color:'#1a1a1a'}}>
                  <Icon.Check style={{width:13, height:13}}/>
                </div>
              )}
            </button>
          );
        })}
      </div>

      {/* Preview */}
      <div className="card card-lg" style={{marginTop:18}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
          <div>
            <h3>Live preview</h3>
            <div style={{fontSize:15, fontWeight:600, color:'var(--ink-1)', marginTop:4}}>
              Style: <span style={{color:'var(--ink-2)'}}>{STYLES.find(x=>x.id===selected)?.name}</span>
            </div>
          </div>
          <span className="chip">Sample input: standup recap</span>
        </div>
        <div className="row" style={{gap:14}}>
          <div style={{flex:1}}>
            <div style={{fontSize:11, fontWeight:500, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--ink-3)', marginBottom:8}}>You spoke</div>
            <div style={{fontSize:13.5, lineHeight:1.6, color:'var(--ink-2)', padding:'14px 16px', background:'var(--bg-sunken)', borderRadius:14, border:'0.5px solid var(--line)'}}>
              uh so today i'm gonna work on the transcript editor we talked about
              yesterday um and i also need to follow up with mark about the latency
              thing and oh yeah send the design review notes to the team before
              standup tomorrow
            </div>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:11, fontWeight:500, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--ink-3)', marginBottom:8}}>OpenDicta outputs</div>
            <StylePreview style={selected}/>
          </div>
        </div>
      </div>
    </>
  );

  if (!aiEnabled) {
    return (
      <div className="page">
        <PageHead
          eyebrow="Style"
          title={<>Refine your <em>words</em>.</>}
          sub="AI refinement is currently turned off. Set up a provider on the AI tab to unlock styles."
        />
        <div className="locked">
          <div className="lock-banner">
            <div style={{width:44, height:44, borderRadius:12, background:'var(--accent)', color:'#1a1a1a', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
              <Icon.Lock2 style={{width:22, height:22}}/>
            </div>
            <div>
              <div style={{fontSize:15, fontWeight:600}}>Styles need an AI provider</div>
              <div style={{fontSize:12.5, color:'oklch(75% 0.008 85)', marginTop:4}}>Add a Gemini, OpenAI, or Claude key on the AI tab to enable refinement.</div>
            </div>
          </div>
          <div style={{filter:'saturate(0.4)', opacity:0.7, pointerEvents:'none'}}>{body}</div>
        </div>
      </div>
    );
  }

  return (
    <div className="page">
      <PageHead
        eyebrow="Style"
        title={<>Refine your <em>words</em>.</>}
        sub="Pick how OpenDicta should reshape your raw transcript after you stop speaking."
      >
        <div className="chip chip-accent"><Icon.Sparkle style={{width:12, height:12}}/> AI is on</div>
      </PageHead>
      {body}
    </div>
  );
}

function StylePreview({ style }) {
  const samples = {
    raw: <pre style={{margin:0, fontFamily:'Geist Mono, ui-monospace, monospace', fontSize:12, lineHeight:1.55, whiteSpace:'pre-wrap'}}>uh so today i'm gonna work on the transcript editor we talked about yesterday um and i also need to follow up with mark about the latency thing and oh yeah send the design review notes to the team before standup tomorrow</pre>,
    grammar: <p style={{margin:0, fontSize:13.5, lineHeight:1.6}}>Today I'm going to work on the transcript editor we talked about yesterday. I also need to follow up with Mark about the latency thing, and send the design review notes to the team before standup tomorrow.</p>,
    email: <div style={{fontSize:13, lineHeight:1.55}}>
      <div style={{color:'var(--ink-3)', marginBottom:6}}><b style={{color:'var(--ink-1)'}}>Subject:</b> Today's focus + 2 follow-ups</div>
      <div>Hi team,</div>
      <div style={{marginTop:8}}>Heads-up on today: I'll be focused on the transcript editor we discussed yesterday. Two follow-ups on my plate — checking in with Mark on latency, and getting the design review notes out before standup tomorrow.</div>
      <div style={{marginTop:8}}>Best,<br/>Alex</div>
    </div>,
    prompt: <pre style={{margin:0, fontFamily:'Geist Mono, ui-monospace, monospace', fontSize:11.5, lineHeight:1.55, whiteSpace:'pre-wrap'}}>{`# Role
You are a project planning assistant.

# Context
- Working on the transcript editor (carried over)
- Open thread with Mark re: model latency
- Design review notes pending

# Task
Draft a one-line standup update covering today's focus and the two outstanding items.`}</pre>,
    pro: <div style={{fontSize:13.5, lineHeight:1.55}}>
      <div style={{color:'var(--ink-1)', fontWeight:600}}>Summary</div>
      <div style={{color:'var(--ink-2)', marginTop:4}}>Focus today is the transcript editor. Two outstanding items: a latency check-in with Mark, and design review notes due before tomorrow's standup.</div>
      <div style={{color:'var(--ink-1)', fontWeight:600, marginTop:10}}>Action items</div>
      <div style={{display:'flex', flexDirection:'column', gap:4, marginTop:4}}>
        {['Ship transcript editor work','Follow up with Mark on latency','Send design review notes before standup'].map((t,i)=>(
          <div key={i} style={{display:'flex', gap:8, alignItems:'flex-start'}}>
            <span style={{width:14, height:14, border:'1.2px solid var(--ink-3)', borderRadius:3, flexShrink:0, marginTop:2}}/>
            <span>{t}</span>
          </div>
        ))}
      </div>
    </div>,
    bullets: <ul style={{margin:0, paddingLeft:18, fontSize:13.5, lineHeight:1.65}}>
      <li>Work on the transcript editor</li>
      <li>Follow up with Mark on latency</li>
      <li>Send design review notes before standup</li>
    </ul>,
    chat: <p style={{margin:0, fontSize:13.5, lineHeight:1.55}}>heads up — heads-down on the transcript editor today 🎙️ also: pinging mark re: latency, and design review notes going out before standup tomorrow ✅</p>,
    summary: <p style={{margin:0, fontSize:13.5, lineHeight:1.6}}>Working on the transcript editor today, plus following up with Mark on latency and getting design notes out before tomorrow's standup.</p>,
  };
  return (
    <div style={{padding:'14px 16px', background:'var(--bg-sunken)', borderRadius:14, border:'0.5px solid var(--line)', color:'var(--ink-1)'}}>
      {samples[style] || samples.grammar}
    </div>
  );
}

// ── 5. AI ───────────────────────────────────────────────────

const PROVIDERS = [
  { id:'gemini',  name:'Gemini',   sub:'Google · Fast + cheap',  models:['gemini-2.5-flash', 'gemini-2.5-pro'], color:'oklch(72% 0.13 220)', mark:'G' },
  { id:'openai',  name:'OpenAI',   sub:'Industry standard',       models:['gpt-4o', 'gpt-4o-mini'],              color:'oklch(70% 0.13 150)', mark:'◯' },
  { id:'claude',  name:'Claude',   sub:'Anthropic · Best prose',  models:['claude-sonnet-4', 'claude-haiku-4'],  color:'oklch(70% 0.13 50)',  mark:'※' },
];

function AISetup({ aiEnabled, setAiEnabled }) {
  const [provider, setProvider] = useState2('claude');
  const [apiKey, setApiKey] = useState2('');
  const [reveal, setReveal] = useState2(false);
  const [savedAt, setSavedAt] = useState2(null);

  const onSave = () => {
    setSavedAt(new Date().toLocaleTimeString([], {hour:'numeric', minute:'2-digit'}));
    setTimeout(()=>setSavedAt(null), 3500);
  };

  return (
    <div className="page">
      <PageHead
        eyebrow="AI"
        title={<>Bring your own <em>brain</em>.</>}
        sub="Pick a provider and paste your API key. OpenDicta stores it locally — your keys never touch our servers."
      >
        <div className="chip" style={{background: aiEnabled ? 'var(--accent-soft)' : 'var(--bg-sunken)'}}>
          <span style={{width:6, height:6, borderRadius:'50%', background: aiEnabled ? 'oklch(60% 0.18 145)' : 'var(--ink-4)'}}/>
          {aiEnabled ? 'AI is enabled' : 'AI is disabled'}
        </div>
      </PageHead>

      <div className="row" style={{alignItems:'stretch'}}>
        {/* Left: provider picker */}
        <div className="card card-lg" style={{flex:1.4}}>
          <h3>Choose a provider</h3>
          <div style={{display:'flex', flexDirection:'column', gap:10, marginTop:12}}>
            {PROVIDERS.map(p => {
              const on = provider === p.id;
              return (
                <button key={p.id} onClick={() => setProvider(p.id)} className="card" style={{
                  padding:18, cursor:'pointer', font:'inherit', textAlign:'left',
                  border: on ? '1.5px solid var(--ink-1)' : '0.5px solid var(--line)',
                  background: on ? 'var(--bg-sunken)' : 'var(--bg-card)',
                  boxShadow:'none',
                  display:'flex', alignItems:'center', gap:14,
                  transition:'background .12s, border-color .12s'
                }}>
                  <div style={{
                    width:48, height:48, borderRadius:14,
                    background:`color-mix(in oklch, ${p.color} 28%, white)`,
                    color:`color-mix(in oklch, ${p.color} 70%, black)`,
                    display:'flex', alignItems:'center', justifyContent:'center',
                    fontSize:22, fontWeight:600,
                    flexShrink:0
                  }}>{p.mark}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontSize:15, fontWeight:600, color:'var(--ink-1)'}}>{p.name}</div>
                    <div style={{fontSize:12.5, color:'var(--ink-3)', marginTop:2}}>{p.sub}</div>
                  </div>
                  <div style={{
                    width:20, height:20, borderRadius:'50%',
                    border: on ? '6px solid var(--ink-1)' : '1.5px solid var(--line-2)',
                    transition:'border .12s'
                  }}/>
                </button>
              );
            })}
          </div>
        </div>

        {/* Right: key + config */}
        <div className="col" style={{flex:1.6}}>
          <div className="card card-lg">
            <h3>API key</h3>
            <div style={{fontSize:13, color:'var(--ink-2)', marginTop:6, marginBottom:18}}>
              Paste your {PROVIDERS.find(p=>p.id===provider)?.name} key. Stored encrypted in your OS keychain.
            </div>

            <div className="field">
              <label>Secret key</label>
              <div style={{display:'flex', gap:8}}>
                <div style={{flex:1, position:'relative'}}>
                  <Icon.Key style={{width:15, height:15, position:'absolute', left:14, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)'}}/>
                  <input
                    className="input input-mono"
                    type={reveal ? 'text' : 'password'}
                    placeholder={
                      provider==='openai' ? 'sk-proj-…' :
                      provider==='claude' ? 'sk-ant-api03-…' :
                      'AIza…'
                    }
                    value={apiKey}
                    onChange={(e)=>setApiKey(e.target.value)}
                    style={{width:'100%', paddingLeft:38, paddingRight:90}}
                  />
                  <button className="btn btn-sm btn-ghost"
                          onClick={()=>setReveal(r=>!r)}
                          style={{position:'absolute', right:6, top:'50%', transform:'translateY(-50%)', height:30}}>
                    {reveal ? 'Hide' : 'Reveal'}
                  </button>
                </div>
              </div>
            </div>

            <div className="field" style={{marginTop:14}}>
              <label>Model</label>
              <select className="input">
                {PROVIDERS.find(p=>p.id===provider)?.models.map(m =>
                  <option key={m}>{m}</option>
                )}
              </select>
            </div>

            <div className="field" style={{marginTop:14}}>
              <label>Temperature</label>
              <div style={{display:'flex', alignItems:'center', gap:14}}>
                <input type="range" min="0" max="100" defaultValue="35" style={{flex:1, accentColor:'var(--ink-1)'}}/>
                <div className="mono tnum" style={{fontSize:13, color:'var(--ink-2)', width:36, textAlign:'right'}}>0.35</div>
              </div>
            </div>

            <div className="divider" style={{margin:'18px 0'}}/>

            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
              <div style={{fontSize:12, color:'var(--ink-3)'}}>
                {savedAt
                  ? <span style={{color:'oklch(50% 0.15 150)', fontWeight:500}}>✓ Saved at {savedAt}</span>
                  : <>Last test: <span style={{color:'var(--ink-2)'}}>connection OK · 142ms</span></>}
              </div>
              <div style={{display:'flex', gap:8}}>
                <button className="btn btn-sm">Test connection</button>
                <button className="btn btn-primary btn-sm" onClick={onSave}>
                  <Icon.Check style={{width:13, height:13}}/> Save key
                </button>
              </div>
            </div>
          </div>

          <div className="card" style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div>
              <div style={{fontSize:14, fontWeight:600, color:'var(--ink-1)'}}>Enable AI refinement</div>
              <div style={{fontSize:12.5, color:'var(--ink-3)', marginTop:3}}>Turns on the Style tab and any AI-powered features app-wide.</div>
            </div>
            <div className="toggle" data-on={aiEnabled} onClick={()=>setAiEnabled(!aiEnabled)} role="switch" aria-checked={aiEnabled}/>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── 6. SETTINGS ────────────────────────────────────────────

function Settings({ prefs, setPrefs }) {
  const [s, setS] = useState2({
    launch: true,
    menubar: true,
    sounds: false,
    autoUpdate: true,
    mic: 'AirPods Pro · External',
    pushToTalk: 'Hold Fn',
    record: '⌥ Space',
    stop: 'Esc',
  });
  const set = (k,v) => setS(prev=>({...prev, [k]:v}));

  // safe fallbacks if rendered without props (unlikely now)
  const p = prefs || { accent:'#dbef6a', density:'regular', sidebar:'icons', userName:'Alex' };
  const sp = setPrefs || (() => {});
  const themes = window.THEMES || [];

  return (
    <div className="page">
      <PageHead
        eyebrow="Settings"
        title={<>General <em>preferences</em>.</>}
        sub="The fiddly bits. Hardware, shortcuts, and how OpenDicta behaves on launch."
      >
        <button className="btn btn-sm"><Icon.Diagnostic style={{width:14,height:14}}/> Run diagnostic</button>
      </PageHead>

      {/* ── Appearance / Themes ─────────────────────────────── */}
      <div className="card card-lg" style={{marginBottom:'var(--gap)'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18}}>
          <div>
            <div className="section-title" style={{margin:0}}>Appearance</div>
            <div style={{fontSize:13, color:'var(--ink-3)', marginTop:4}}>Theme applies everywhere instantly and remembers across launches.</div>
          </div>
          <div className="chip"><span style={{width:9, height:9, borderRadius:'50%', background:'var(--accent)'}}/> Current theme</div>
        </div>

        <div className="grid grid-4" style={{gap:14}}>
          {themes.map(theme => {
            const on = p.accent.toLowerCase() === theme.accent.toLowerCase();
            return (
              <button
                key={theme.id}
                onClick={() => sp('accent', theme.accent)}
                className="card"
                style={{
                  textAlign:'left', cursor:'pointer', font:'inherit',
                  border: on ? '1.5px solid var(--ink-1)' : '0.5px solid var(--line)',
                  background:'var(--bg-card)',
                  padding:14, gap:10,
                  display:'flex', flexDirection:'column',
                  transition:'transform .12s, border-color .12s',
                  position:'relative',
                  boxShadow: on
                    ? '0 1px 2px rgba(0,0,0,0.05), 0 10px 24px -14px rgba(0,0,0,0.18)'
                    : 'var(--shadow-card)'
                }}
              >
                <ThemeSwatch accent={theme.accent} on={on}/>
                <div>
                  <div style={{fontSize:14, fontWeight:600, color:'var(--ink-1)'}}>{theme.name}</div>
                  <div style={{fontSize:12, color:'var(--ink-3)', marginTop:2}}>{theme.sub}</div>
                </div>
                {on && (
                  <div style={{position:'absolute', top:10, right:10, width:22, height:22, borderRadius:'50%', background:'var(--ink-1)', color:'oklch(98% 0.005 85)', display:'flex', alignItems:'center', justifyContent:'center'}}>
                    <Icon.Check style={{width:13, height:13}}/>
                  </div>
                )}
              </button>
            );
          })}
        </div>

        <div className="divider" style={{margin:'20px 0 16px'}}/>

        <div className="row" style={{gap:18}}>
          <div style={{flex:1}}>
            <div style={{fontSize:12, fontWeight:500, color:'var(--ink-2)', marginBottom:8}}>Sidebar style</div>
            <div className="seg-row">
              {[
                {v:'icons', label:'Icons only'},
                {v:'wide',  label:'Icons + labels'},
              ].map(opt => (
                <button key={opt.v}
                  onClick={()=>sp('sidebar', opt.v)}
                  className={'seg ' + (p.sidebar===opt.v ? 'seg-on' : '')}>{opt.label}</button>
              ))}
            </div>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:12, fontWeight:500, color:'var(--ink-2)', marginBottom:8}}>Layout density</div>
            <div className="seg-row">
              {[
                {v:'compact', label:'Compact'},
                {v:'regular', label:'Regular'},
                {v:'comfy',   label:'Comfy'},
              ].map(opt => (
                <button key={opt.v}
                  onClick={()=>sp('density', opt.v)}
                  className={'seg ' + (p.density===opt.v ? 'seg-on' : '')}>{opt.label}</button>
              ))}
            </div>
          </div>
          <div style={{flex:1.2}}>
            <div style={{fontSize:12, fontWeight:500, color:'var(--ink-2)', marginBottom:8}}>Display name</div>
            <input
              className="input"
              value={p.userName}
              onChange={(e)=>sp('userName', e.target.value)}
              style={{height:36}}
              placeholder="Your name"
            />
          </div>
        </div>
      </div>

      <div className="row" style={{alignItems:'stretch'}}>
        <div className="col" style={{flex:1.4}}>

          <div className="card card-lg">
            <div className="section-title">Startup</div>
            <Setting label="Open at login"
                     desc="Launch OpenDicta when you sign in."
                     icon={<Icon.Power style={{width:18,height:18}}/>}>
              <div className="toggle" data-on={s.launch} onClick={()=>set('launch', !s.launch)}/>
            </Setting>
            <Divider/>
            <Setting label="Stay in menu bar"
                     desc="Quick access without keeping a window open."
                     icon={<Icon.Dashboard style={{width:18,height:18}}/>}>
              <div className="toggle" data-on={s.menubar} onClick={()=>set('menubar', !s.menubar)}/>
            </Setting>
            <Divider/>
            <Setting label="Auto-update models"
                     desc="Pull new model versions when available."
                     icon={<Icon.Models style={{width:18,height:18}}/>}>
              <div className="toggle" data-on={s.autoUpdate} onClick={()=>set('autoUpdate', !s.autoUpdate)}/>
            </Setting>
            <Divider/>
            <Setting label="Sounds"
                     desc="Subtle start / stop chimes when recording."
                     icon={<Icon.Wave style={{width:18,height:18}}/>}>
              <div className="toggle" data-on={s.sounds} onClick={()=>set('sounds', !s.sounds)}/>
            </Setting>
          </div>

          <div className="card card-lg">
            <div className="section-title">Hardware</div>
            <Setting label="Microphone"
                     desc="Currently routing through your selected input."
                     icon={<Icon.Mic style={{width:18,height:18}}/>}>
              <select className="input" style={{minWidth:220, height:36}} value={s.mic} onChange={(e)=>set('mic', e.target.value)}>
                <option>AirPods Pro · External</option>
                <option>MacBook Pro Microphone</option>
                <option>Shure MV7+ · USB</option>
                <option>Studio Display Microphone</option>
              </select>
            </Setting>
            <Divider/>
            <div style={{padding:'14px 0 4px'}}>
              <div style={{fontSize:11, fontWeight:500, letterSpacing:'.06em', textTransform:'uppercase', color:'var(--ink-3)', marginBottom:8}}>Input level</div>
              <MicLevel/>
              <div style={{fontSize:11.5, color:'var(--ink-3)', marginTop:6}}>Speak normally. Aim for the green zone.</div>
            </div>
          </div>

        </div>

        <div className="col" style={{flex:1}}>
          <div className="card card-lg">
            <div className="section-title">Shortcuts</div>
            <Shortcut label="Record toggle" value={s.record}/>
            <Divider/>
            <Shortcut label="Push-to-talk" value={s.pushToTalk}/>
            <Divider/>
            <Shortcut label="Stop and discard" value={s.stop}/>
            <Divider/>
            <Shortcut label="Refine with AI" value="⌘ ⇧ R"/>
            <Divider/>
            <Shortcut label="Open editor" value="⌘ E"/>
          </div>

          <div className="card" style={{background:'var(--ink-1)', color:'oklch(95% 0.005 85)', borderColor:'transparent'}}>
            <div style={{display:'flex', gap:14, alignItems:'flex-start'}}>
              <div style={{width:36, height:36, borderRadius:11, background:'var(--accent)', color:'#1a1a1a', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                <Icon.Sparkle style={{width:18,height:18}}/>
              </div>
              <div style={{flex:1}}>
                <div style={{fontSize:14, fontWeight:600}}>OpenDicta 2.4.1</div>
                <div style={{fontSize:12, color:'oklch(75% 0.008 85)', marginTop:4, lineHeight:1.5}}>
                  Up to date. Latest models synced 2 hours ago.
                </div>
                <button className="btn btn-sm btn-ghost" style={{marginTop:10, color:'oklch(95% 0.005 85)'}}>Check for updates →</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Setting({ label, desc, icon, children }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:14, padding:'14px 0'}}>
      <div style={{width:36, height:36, borderRadius:10, background:'var(--bg-sunken)', color:'var(--ink-2)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>{icon}</div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontSize:14, fontWeight:500, color:'var(--ink-1)'}}>{label}</div>
        {desc && <div style={{fontSize:12, color:'var(--ink-3)', marginTop:2}}>{desc}</div>}
      </div>
      {children}
    </div>
  );
}

function Divider() { return <div className="divider" style={{margin:'2px 0'}}/>; }

function Shortcut({ label, value }) {
  const keys = value.split(' ');
  return (
    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 0', gap:14}}>
      <div style={{fontSize:13.5, color:'var(--ink-1)', fontWeight:500}}>{label}</div>
      <div style={{display:'flex', gap:4, alignItems:'center'}}>
        {keys.map((k,i)=>(
          <kbd key={i} style={{
            display:'inline-flex', alignItems:'center', justifyContent:'center',
            minWidth:28, height:28, padding:'0 7px',
            background:'var(--bg-card)', border:'0.5px solid var(--line-2)',
            borderRadius:7, fontFamily:'Geist, sans-serif', fontSize:12, fontWeight:500,
            color:'var(--ink-1)',
            boxShadow:'0 1px 0 var(--line)'
          }}>{k}</kbd>
        ))}
        <button className="btn btn-sm btn-ghost" style={{height:28, padding:'0 8px', fontSize:11.5}}>Edit</button>
      </div>
    </div>
  );
}

function MicLevel() {
  const [level, setLevel] = useState2(0.45);
  useEffect2(()=>{
    const id = setInterval(()=>{
      // wandering input level
      setLevel(prev => {
        const target = 0.35 + Math.random() * 0.5;
        return prev + (target - prev) * 0.18;
      });
    }, 180);
    return ()=>clearInterval(id);
  },[]);
  const bars = 28;
  return (
    <div style={{display:'flex', gap:3, alignItems:'center', height:24}}>
      {Array.from({length:bars}).map((_,i)=>{
        const active = (i/bars) < level;
        const color = i < bars*0.55 ? 'oklch(64% 0.16 145)' : i < bars*0.82 ? 'var(--accent)' : 'oklch(70% 0.18 30)';
        return <div key={i} style={{
          flex:1, height: 4 + (i/bars)*18,
          background: active ? color : 'var(--bg-sunken)',
          borderRadius:2,
          transition:'background .12s'
        }}/>;
      })}
    </div>
  );
}

function ThemeSwatch({ accent, on }) {
  // Mini illustration of the app with the accent applied — a tiny cream card
  // with a dark sidebar stripe and an accent chip + bar inside.
  return (
    <div style={{
      height:74, borderRadius:12, overflow:'hidden',
      background:'oklch(95% 0.018 145)',  // sage stage
      border:'0.5px solid var(--line)',
      display:'flex',
      position:'relative'
    }}>
      {/* sidebar mock */}
      <div style={{width:14, background:'oklch(18% 0.005 60)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'flex-start', paddingTop:4, gap:3}}>
        <div style={{width:8, height:8, borderRadius:2, background:accent}}/>
        <div style={{width:6, height:2, borderRadius:1, background:'oklch(60% 0.01 85)', marginTop:2}}/>
        <div style={{width:6, height:2, borderRadius:1, background:'oklch(60% 0.01 85)'}}/>
        <div style={{width:6, height:2, borderRadius:1, background:'oklch(60% 0.01 85)'}}/>
      </div>
      {/* app body mock */}
      <div style={{flex:1, padding:6, display:'flex', flexDirection:'column', gap:4, background:'oklch(97.5% 0.004 85)'}}>
        <div style={{height:4, width:'60%', borderRadius:2, background:'oklch(35% 0.008 75)'}}/>
        <div style={{height:2, width:'40%', borderRadius:2, background:'oklch(72% 0.008 75)'}}/>
        <div style={{display:'flex', gap:4, marginTop:'auto'}}>
          <div style={{flex:1, height:18, borderRadius:4, background:accent, border:'0.5px solid color-mix(in oklch, ' + accent + ' 70%, black)'}}/>
          <div style={{flex:1, height:18, borderRadius:4, background:'#fff', border:'0.5px solid var(--line)'}}/>
          <div style={{flex:0.5, height:18, borderRadius:4, background:'oklch(18% 0.005 60)'}}/>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Models, Style, AISetup, Settings });
