// App shell: sidebar nav, top bar, view switching, tweaks panel.

const NAV = [
  { k:'overview', label:'Overview',     icon:'home',     kbd:'G O' },
  { k:'scan',     label:'New Scan',     icon:'cam',      kbd:'G N', badge:'Ready' },
  { k:'history',  label:'Scan History', icon:'history',  kbd:'G H' },
  { k:'reports',  label:'Reports',      icon:'report',   kbd:'G R' },
  { k:'audio',    label:'Voice Lab',    icon:'audio' },
  { k:'breath',   label:'Breath Lab',   icon:'breath' },
  { k:'form',     label:'Questionnaire',icon:'form' },
  { k:'tips',     label:'Health Tips',  icon:'tips' },
];
const NAV_BOTTOM = [
  { k:'settings', label:'Settings',  icon:'settings' },
  { k:'logout',   label:'Sign out',  icon:'logout' },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#1F5A4F",
  "density": "regular",
  "sidebar": "expanded",
  "background": "warm"
}/*EDITMODE-END*/;

function applyTokens(t) {
  const root = document.documentElement;
  // accent + soft
  root.style.setProperty('--accent', t.accent);
  // derive soft using color-mix; fall back keeps things sane
  root.style.setProperty('--accent-soft', `color-mix(in oklab, ${t.accent} 20%, var(--paper))`);
  // background
  const bgs = {
    warm:    { bg:'#F4F1EA', bg2:'#EBE7DD', paper:'#FBFAF6', line:'#E0DBCF', line2:'#CFC8B8' },
    cool:    { bg:'#F2F4F7', bg2:'#E6EAF0', paper:'#FFFFFF', line:'#DEE3EB', line2:'#CCD2DC' },
    ink:     { bg:'#13120F', bg2:'#1B1A16', paper:'#1F1D18', line:'#2A2722', line2:'#3A3630' }
  };
  const b = bgs[t.background] || bgs.warm;
  Object.entries({'--bg':b.bg, '--bg-2':b.bg2, '--paper-2':b.paper, '--paper':b.paper, '--line':b.line, '--line-2':b.line2}).forEach(([k,v])=>root.style.setProperty(k,v));
  if (t.background === 'ink') {
    root.style.setProperty('--ink', '#F2EFE7');
    root.style.setProperty('--ink-2', '#CFC9BC');
    root.style.setProperty('--ink-3', '#8B8578');
    root.style.setProperty('--muted', '#6E685D');
  } else {
    root.style.setProperty('--ink', '#15140F');
    root.style.setProperty('--ink-2', '#3E3A33');
    root.style.setProperty('--ink-3', '#6E685D');
    root.style.setProperty('--muted', '#9A9388');
  }
  // density
  const d = t.density === 'compact' ? { pad: '16px', radius: '14px' }
           : t.density === 'comfy'  ? { pad: '28px', radius: '22px' }
                                    : { pad: '22px', radius: '20px' };
  root.style.setProperty('--pad', d.pad);
  root.style.setProperty('--r-lg', d.radius);
}

function Sidebar({ active, onNav, collapsed, onToggle }) {
  const ref = React.useRef(null);
  const [indStyle, setIndStyle] = React.useState({ opacity: 0 });
  React.useEffect(() => {
    if (!ref.current) return;
    const activeEl = ref.current.querySelector(`a[data-k="${active}"]`);
    if (!activeEl) { setIndStyle({ opacity: 0 }); return; }
    const r = activeEl.getBoundingClientRect();
    const pr = ref.current.getBoundingClientRect();
    setIndStyle({
      transform: `translateY(${r.top - pr.top}px)`,
      opacity: 1,
      height: r.height,
    });
  }, [active, collapsed]);

  return (
    <aside className="side">
      <div className="logo" onClick={() => onNav('overview')} style={{cursor:'pointer'}}>
        <div className="logo-mark">
          {/* O-mark for OraScan */}
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2"/>
            <path d="M7 12c1.5-3 8-3 9.5 0" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
            <path d="M9 8.5h6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
          </svg>
        </div>
        <div className="logo-text">
          <b>OraScan</b><span>Clinician</span>
        </div>
      </div>

      <div className="group-label">Workspace</div>
      <ul className="nav" ref={ref}>
        <li className="indicator" style={indStyle}/>
        {NAV.map(n => {
          const Ic = I[n.icon];
          return (
            <li key={n.k}>
              <a data-k={n.k} className={active===n.k?'active':''} onClick={()=>onNav(n.k)}>
                <Ic className="icn"/>
                <span>{n.label}</span>
                {n.badge && <span className="badge">{n.badge}</span>}
                {!n.badge && n.kbd && <span className="kbd">{n.kbd}</span>}
              </a>
            </li>
          );
        })}
      </ul>

      <div className="group-label">Account</div>
      <ul className="nav">
        {NAV_BOTTOM.map(n => {
          const Ic = I[n.icon];
          return (
            <li key={n.k}>
              <a data-k={n.k} className={active===n.k?'active':''} onClick={()=>onNav(n.k)}>
                <Ic className="icn"/><span>{n.label}</span>
              </a>
            </li>
          );
        })}
      </ul>

      <div className="side-foot">
        <div className="device-card">
          <div className="row">
            <span className="dot"/>
            <span style={{fontWeight:500}}>Capture rig · online</span>
          </div>
          <div className="meta">
            <b>OS-Arm v3.1</b> · cam0 + cam1<br/>
            Motor θ ±0.4° · breath port OK<br/>
            Secure sync · 2m ago
          </div>
        </div>
      </div>
    </aside>
  );
}

function TopBar({ active, onNav }) {
  const labelOf = (k) => NAV.find(n=>n.k===k)?.label ?? NAV_BOTTOM.find(n=>n.k===k)?.label ?? 'Overview';
  return (
    <div className="topbar">
      <div className="crumbs">
        <span>OraScan</span>
        <span className="sep">/</span>
        <b>{labelOf(active)}</b>
      </div>
      <div className="search" onClick={(e)=>e.currentTarget.querySelector('input').focus()}>
        <I.search size={15}/>
        <input placeholder="Search patients, sessions, scan IDs…"/>
        <span className="kbd">⌘ K</span>
      </div>
      <div className="top-actions">
        <button className="iconbtn" title="Activity"><I.wave size={16}/></button>
        <button className="iconbtn" title="Notifications"><I.bell size={16}/><span className="pip"/></button>
        <div className="avatar" title="Dr. Anika Mehta">AM</div>
      </div>
    </div>
  );
}

// Stub view for non-overview pages
function StubView({ title, blurb, icon }) {
  const Ic = I[icon] || I.spark;
  return (
    <div className="page ph">
      <div style={{
        width:80, height:80, borderRadius:20,
        background:'var(--paper-2)', border:'1px solid var(--line)',
        display:'grid', placeItems:'center',
        boxShadow:'var(--shadow-md)',
      }}>
        <Ic size={36} stroke="var(--accent)"/>
      </div>
      <h2>{title}</h2>
      <p>{blurb}</p>
      <div style={{display:'flex', gap:8, marginTop:6}}>
        <button className="lk" style={{border:'1px solid var(--line)', padding:'7px 12px', borderRadius:10}}>
          <I.plus size={14}/> Start
        </button>
        <button className="lk" style={{border:'1px solid var(--line)', padding:'7px 12px', borderRadius:10}}>
          <I.calendar size={14}/> Schedule
        </button>
      </div>
    </div>
  );
}

const STUBS = {
  scan:    { title:'Begin Capture Sequence',  blurb:'Aligns the motorized arm and runs the 13-angle guided protocol.', icon:'cam' },
  history: { title:'Scan History',            blurb:'Browse every session — filter by date, finding, tooth, or review confidence.', icon:'history' },
  reports: { title:'Reports',                 blurb:'Render PDF reports from any session for the patient or referring clinician.', icon:'report' },
  audio:   { title:'Voice Lab',               blurb:'Articulation, sibilance, and resonance checks for speech-impacting conditions.', icon:'audio' },
  breath:  { title:'Breath Lab',              blurb:'H₂S, methyl mercaptan, and VSC trends from the breath port.', icon:'breath' },
  form:    { title:'Daily Questionnaire',     blurb:'12-item triage for diet, hygiene, and symptom escalation.', icon:'form' },
  tips:    { title:'Health Tips',             blurb:'Personalized guidance based on findings and questionnaire signals.', icon:'tips' },
  settings:{ title:'Settings',                blurb:'Hardware, sync, encryption, and clinician profile preferences.', icon:'settings' },
  logout:  { title:'Sign out',                blurb:'End your session.', icon:'logout' },
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [active, setActive] = React.useState('overview');
  const [collapsed, setCollapsed] = React.useState(false);

  React.useEffect(() => { applyTokens(t); }, [t]);

  // ⌘K / G-O / G-N / G-H simple keymap
  React.useEffect(() => {
    let prefix = false, timer;
    function onKey(e) {
      const tag = (e.target?.tagName || '').toLowerCase();
      if (tag === 'input' || tag === 'textarea') return;
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); return; }
      if (!prefix && e.key.toLowerCase() === 'g') {
        prefix = true;
        clearTimeout(timer);
        timer = setTimeout(() => { prefix = false; }, 700);
        return;
      }
      if (prefix) {
        prefix = false;
        const map = { o:'overview', n:'scan', h:'history', r:'reports' };
        const k = map[e.key.toLowerCase()];
        if (k) setActive(k);
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const view = active === 'overview'
    ? <Overview onGo={setActive}/>
    : <StubView {...STUBS[active]}/>;

  return (
    <div className={`app ${collapsed ? 'collapsed' : ''}`}>
      <Sidebar active={active} onNav={setActive} collapsed={collapsed} onToggle={()=>setCollapsed(c=>!c)}/>
      <main className="main">
        <TopBar active={active} onNav={setActive}/>
        <div className="content" key={active}>
          {view}
        </div>
      </main>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette"/>
        <TweakColor label="Accent" value={t.accent}
          options={['#1F5A4F','#0E5E7A','#5C3FB3','#B5453A','#1A1A1A']}
          onChange={v => setTweak('accent', v)}/>
        <TweakRadio label="Background" value={t.background}
          options={['warm','cool','ink']}
          onChange={v => setTweak('background', v)}/>

        <TweakSection label="Layout"/>
        <TweakRadio label="Density" value={t.density}
          options={['compact','regular','comfy']}
          onChange={v => setTweak('density', v)}/>
        <TweakRadio label="Sidebar" value={t.sidebar}
          options={['expanded','collapsed']}
          onChange={v => { setTweak('sidebar', v); setCollapsed(v === 'collapsed'); }}/>
      </TweaksPanel>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
