/* global React */
const { useState, useEffect } = React;

/* =========================================================================
   PREFERENCES
   ========================================================================= */
function PreferencesScreen() {
  const {
    theme, setTheme, accent, setAccent, density, setDensity, font, setFont, user,
    preferences, savePreferences,
  } = useApp();
  const [section, setSection] = useState('appearance');

  const [notify, setNotify] = useState(preferences?.notifications ?? { runDone: true, runFailed: true, quotaWarn: true, weekly: false, product: false });
  const [defaults, setDefaults] = useState(preferences?.defaults ?? { region: 'eu-west-1', currency: 'EUR', inputMode: 'text', autoRun: false });
  const [analysis, setAnalysis] = useState(preferences?.analysis ?? { includeHidden: true, pillars: { ops:true, sec:true, rel:true, perf:true, cost:true, sus:true }, severity: 'med' });
  const [saveState, setSaveState] = useState('idle'); // idle | saving | saved | error

  // Hydrate from backend the first time preferences arrive (or whenever they
  // change externally — e.g. logging in on another device).
  useEffect(() => {
    if (!preferences) return;
    setNotify(preferences.notifications);
    setDefaults(preferences.defaults);
    setAnalysis(preferences.analysis);
  }, [preferences]);

  const onSave = async () => {
    setSaveState('saving');
    try {
      await savePreferences({
        appearance: { theme, accent, density, font },
        defaults,
        analysis,
        notifications: notify,
      });
      setSaveState('saved');
      setTimeout(() => setSaveState('idle'), 2000);
    } catch {
      setSaveState('error');
    }
  };

  const sections = [
    { id: 'appearance',  icon: 'sparkle', label: 'Appearance' },
    { id: 'defaults',    icon: 'gear',    label: 'Conversation defaults' },
    { id: 'review',      icon: 'shield',  label: 'Review rules' },
    { id: 'notifications', icon: 'mail',  label: 'Notifications' },
    { id: 'keys',        icon: 'lock',    label: 'API keys' },
    { id: 'data',        icon: 'file',    label: 'Data & exports' },
    { id: 'danger',      icon: 'warn',    label: 'Danger zone' },
  ];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow">preferences</div>
          <h1 className="display">Preferences</h1>
          <div className="meta">Tune how Copilot parses, reviews, and shows results.</div>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'220px 1fr', gap:24, alignItems:'flex-start'}}>
        <nav className="card" style={{position:'sticky', top:68, padding:6}}>
          {sections.map(s => (
            <button key={s.id} onClick={() => setSection(s.id)} style={{
              width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:10,
              padding:'8px 10px', borderRadius:4, fontSize:12.5,
              color: section === s.id ? 'var(--ink-0)' : 'var(--ink-2)',
              background: section === s.id ? 'var(--bg-sunken)' : 'transparent',
              fontWeight: section === s.id ? 500 : 400,
            }}>
              <Icon name={s.icon} size={13}/>{s.label}
            </button>
          ))}
        </nav>

        <div style={{display:'flex', flexDirection:'column', gap:16, minWidth:0}}>
          {section === 'appearance' && (
            <>
              <PrefCard title="Theme" subtitle="Light or dark. Your OS setting isn't followed by default.">
                <PrefRow label="Mode">
                  <SegRadio value={theme} onChange={setTheme} options={[
                    { value:'light', label:'Light', hint:'◻' },
                    { value:'dark',  label:'Dark',  hint:'■' },
                  ]}/>
                </PrefRow>
                <PrefRow label="Accent color" hint="Applied across pills, graphs, and buttons.">
                  <div style={{display:'flex', gap:8}}>
                    {[
                      ['cyan',   215],
                      ['green',  150],
                      ['violet', 280],
                      ['amber',   60],
                      ['rose',    15],
                    ].map(([k, h]) => (
                      <button key={k} onClick={() => setAccent(k)} style={{
                        width:28, height:28, borderRadius:4,
                        border: `2px solid ${accent === k ? 'var(--ink-0)' : 'var(--line-strong)'}`,
                        background: `oklch(0.62 0.18 ${h})`, cursor:'pointer',
                      }} title={k}/>
                    ))}
                  </div>
                </PrefRow>
              </PrefCard>

              <PrefCard title="Typography" subtitle="Pick a pairing. Editor and diagram areas always use the mono face.">
                <PrefRow label="Font pairing">
                  <select className="field" value={font} onChange={e => setFont(e.target.value)} style={{maxWidth:320}}>
                    <option value="inter-mono">Inter + JetBrains Mono</option>
                    <option value="ibm">IBM Plex Sans + Plex Mono</option>
                    <option value="geist">Geist + Geist Mono</option>
                    <option value="serif-mono">Instrument Serif display + Mono</option>
                  </select>
                </PrefRow>
                <PrefRow label="Density">
                  <SegRadio value={density} onChange={setDensity} options={[
                    { value:'comfortable', label:'Comfortable' },
                    { value:'compact',     label:'Compact' },
                  ]}/>
                </PrefRow>
              </PrefCard>

              <PrefCard title="Preview" subtitle="Live preview of your current selections.">
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
                  <div className="stat">
                    <div className="label">Sample metric</div>
                    <div className="val">€1,284<span className="unit">/mo</span></div>
                    <div className="bar"><span style={{width:'62%'}}/></div>
                    <div className="sub"><span className="dot" style={{background:'var(--accent)'}}/>accent preview</div>
                  </div>
                  <div className="stat">
                    <div className="label">Pills</div>
                    <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:8}}>
                      <span className="pill accent">accent</span>
                      <span className="pill ok">ok</span>
                      <span className="pill warn">warn</span>
                      <span className="pill err">err</span>
                      <span className="pill">default</span>
                    </div>
                  </div>
                </div>
              </PrefCard>
            </>
          )}

          {section === 'defaults' && (
            <>
              <PrefCard title="Conversation defaults" subtitle="Pre-fill new conversations with your preferred starting point.">
                <PrefRow label="Default region" hint="Used for cost pricing quotes.">
                  <select className="field mono" value={defaults.region} onChange={e => setDefaults(d => ({...d, region: e.target.value}))} style={{maxWidth:260}}>
                    {['eu-west-1','eu-central-1','us-east-1','us-west-2','ap-southeast-1','ap-northeast-1'].map(r => <option key={r}>{r}</option>)}
                  </select>
                </PrefRow>
                <PrefRow label="Currency">
                  <SegRadio value={defaults.currency} onChange={v => setDefaults(d => ({...d, currency: v}))} options={[
                    { value:'EUR', label:'€ EUR' },{ value:'USD', label:'$ USD' },{ value:'GBP', label:'£ GBP' },
                  ]}/>
                </PrefRow>
                <PrefRow label="Preferred input mode">
                  <SegRadio value={defaults.inputMode} onChange={v => setDefaults(d => ({...d, inputMode: v}))} options={[
                    { value:'text', label:'Free text' },{ value:'iac', label:'Paste IaC' },
                  ]}/>
                </PrefRow>
                <PrefRow label="Auto-run on paste" hint="Immediately run the pipeline when IaC is pasted into the editor.">
                  <Toggle value={defaults.autoRun} onChange={v => setDefaults(d => ({...d, autoRun: v}))}/>
                </PrefRow>
              </PrefCard>
            </>
          )}

          {section === 'review' && (
            <>
              <PrefCard title="Well-Architected pillars" subtitle="Toggle off pillars you don't want included in reviews or the PDF.">
                {[
                  ['ops','Operational Excellence'],['sec','Security'],['rel','Reliability'],
                  ['perf','Performance Efficiency'],['cost','Cost Optimization'],['sus','Sustainability'],
                ].map(([k, name]) => (
                  <PrefRow key={k} label={name}>
                    <Toggle value={analysis.pillars[k]} onChange={v => setAnalysis(a => ({...a, pillars:{...a.pillars, [k]: v}}))}/>
                  </PrefRow>
                ))}
              </PrefCard>
              <PrefCard title="Rule engine" subtitle="How strict should Copilot be about findings?">
                <PrefRow label="Minimum severity to surface">
                  <SegRadio value={analysis.severity} onChange={v => setAnalysis(a => ({...a, severity: v}))} options={[
                    { value:'low',  label:'All · LOW+' },
                    { value:'med',  label:'MED+' },
                    { value:'high', label:'HIGH only' },
                  ]}/>
                </PrefRow>
                <PrefRow label="Flag hidden costs" hint="NAT, inter-AZ egress, CloudWatch — items commonly left out of spec.">
                  <Toggle value={analysis.includeHidden} onChange={v => setAnalysis(a => ({...a, includeHidden: v}))}/>
                </PrefRow>
              </PrefCard>
            </>
          )}

          {section === 'notifications' && (
            <PrefCard title="Email notifications" subtitle={user?.email ? `Sent to ${user.email}.` : 'Sent to your account email.'}>
              <PrefRow label="Conversation completed"><Toggle value={notify.runDone} onChange={v => setNotify(n => ({...n, runDone: v}))}/></PrefRow>
              <PrefRow label="Conversation failed"><Toggle value={notify.runFailed} onChange={v => setNotify(n => ({...n, runFailed: v}))}/></PrefRow>
              <PrefRow label="Quota at 80%"><Toggle value={notify.quotaWarn} onChange={v => setNotify(n => ({...n, quotaWarn: v}))}/></PrefRow>
              <PrefRow label="Weekly summary" hint="A rollup of your conversations every Monday."><Toggle value={notify.weekly} onChange={v => setNotify(n => ({...n, weekly: v}))}/></PrefRow>
              <PrefRow label="Product updates"><Toggle value={notify.product} onChange={v => setNotify(n => ({...n, product: v}))}/></PrefRow>
            </PrefCard>
          )}

          {section === 'keys' && (
            <PrefCard title="API keys" subtitle="Use keys to submit conversations from your CI or CLI." action={<button className="btn primary sm"><Icon name="plus" size={11}/>New key</button>}>
              {[
                { name:'cac_sk_live_7hR2_fa21', created:'2026-02-14', used:'2 hours ago', status:'active' },
                { name:'cac_sk_live_kD8Q_9x0e', created:'2026-01-02', used:'3 weeks ago', status:'active' },
                { name:'cac_sk_live_pLM4_33bc', created:'2025-10-17', used:'never', status:'revoked' },
              ].map((k, i) => (
                <div key={i} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 12px', border:'1px solid var(--line)', borderRadius:4, background:'var(--bg-1)', marginBottom:8}}>
                  <span className={`pill ${k.status==='active'?'ok':'ghost'}`} style={{color: k.status==='revoked'?'var(--ink-3)':undefined}}>{k.status}</span>
                  <span className="mono" style={{fontSize:12, flex:1}}>{k.name}</span>
                  <span style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--font-mono)'}}>created {k.created}</span>
                  <span style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--font-mono)'}}>last used {k.used}</span>
                  {k.status === 'active' && <button className="btn sm">Revoke</button>}
                </div>
              ))}
            </PrefCard>
          )}

          {section === 'data' && (
            <>
              <PrefCard title="Export" subtitle="Download all your conversations as JSON or CSV.">
                <div style={{display:'flex', gap:8}}>
                  <button className="btn"><Icon name="download" size={12}/>Export as JSON</button>
                  <button className="btn"><Icon name="download" size={12}/>Export as CSV</button>
                </div>
              </PrefCard>
              <PrefCard title="Retention" subtitle="Copilot keeps conversations indefinitely on Pro and above.">
                <PrefRow label="Auto-delete conversations older than">
                  <SegRadio value="never" onChange={() => {}} options={[
                    { value:'30',    label:'30 days' },
                    { value:'90',    label:'90 days' },
                    { value:'365',   label:'1 year' },
                    { value:'never', label:'Never' },
                  ]}/>
                </PrefRow>
              </PrefCard>
            </>
          )}

          {section === 'danger' && (
            <PrefCard title="Delete account" subtitle="This will permanently remove your account, all conversations, and API keys." tone="danger">
              <PrefRow label="Type DELETE to confirm">
                <input className="field" placeholder="DELETE" style={{maxWidth:260}}/>
              </PrefRow>
              <div>
                <button className="btn" style={{borderColor:'var(--err)', color:'var(--err)'}}>
                  <Icon name="warn" size={12}/>Delete my account
                </button>
              </div>
            </PrefCard>
          )}

          <div style={{display:'flex', justifyContent:'flex-end', alignItems:'center', gap:8, padding:'8px 0 40px'}}>
            {saveState === 'saved' && <span style={{fontSize:12, color:'var(--ok, #2a8a3e)'}}>Saved</span>}
            {saveState === 'error' && <span style={{fontSize:12, color:'var(--err)'}}>Save failed — try again</span>}
            <button className="btn" onClick={() => {
              if (preferences) {
                setNotify(preferences.notifications);
                setDefaults(preferences.defaults);
                setAnalysis(preferences.analysis);
              }
            }}>Cancel</button>
            <button className="btn accent" onClick={onSave} disabled={saveState === 'saving'}>
              {saveState === 'saving' ? 'Saving…' : 'Save changes'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function PrefCard({ title, subtitle, children, action, tone }) {
  return (
    <div className="card" style={{borderColor: tone === 'danger' ? 'color-mix(in srgb, var(--err) 40%, var(--line))' : undefined}}>
      <div className="card-header">
        <div>
          <div style={{fontSize:13.5, fontWeight:600, color: tone === 'danger' ? 'var(--err)' : 'var(--ink-0)'}}>{title}</div>
          {subtitle && <div style={{fontSize:12, color:'var(--ink-2)', marginTop:2}}>{subtitle}</div>}
        </div>
        {action}
      </div>
      <div className="card-body" style={{padding:0}}>
        {React.Children.map(children, (child, i) => (
          <div style={{borderBottom: i === React.Children.count(children) - 1 ? 0 : '1px solid var(--line)'}}>
            {child}
          </div>
        ))}
      </div>
    </div>
  );
}

function PrefRow({ label, hint, children }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:24, padding:'14px 18px', alignItems:'center'}}>
      <div style={{minWidth:0}}>
        <div style={{fontSize:13, fontWeight:500, color:'var(--ink-0)'}}>{label}</div>
        {hint && <div style={{fontSize:11.5, color:'var(--ink-2)', marginTop:2}}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function SegRadio({ value, onChange, options }) {
  return (
    <div style={{display:'inline-flex', border:'1px solid var(--line-strong)', borderRadius:4, background:'var(--bg-2)', padding:2}}>
      {options.map(o => (
        <button key={o.value} onClick={() => onChange(o.value)} style={{
          padding:'4px 10px', fontSize:12, borderRadius:3,
          background: value === o.value ? 'var(--ink-0)' : 'transparent',
          color: value === o.value ? 'var(--bg-2)' : 'var(--ink-1)',
          fontWeight: value === o.value ? 500 : 400,
        }}>{o.hint && <span style={{marginRight:4, opacity:0.6, fontFamily:'var(--font-mono)'}}>{o.hint}</span>}{o.label}</button>
      ))}
    </div>
  );
}

function Toggle({ value, onChange }) {
  return (
    <button onClick={() => onChange(!value)} style={{
      width:36, height:20, borderRadius:999, position:'relative',
      background: value ? 'var(--accent)' : 'var(--line-strong)',
      border:'1px solid ' + (value ? 'var(--accent)' : 'var(--line-strong)'),
      transition:'background .15s',
    }}>
      <span style={{
        position:'absolute', top:1, left: value ? 17 : 1, width:16, height:16, borderRadius:999,
        background:'var(--bg-2)', transition:'left .15s', boxShadow:'0 1px 2px rgba(0,0,0,0.15)',
      }}/>
    </button>
  );
}

window.PreferencesScreen = PreferencesScreen;
