/* global React, ReactDOM, IOSDevice, AuroraMark, SheetHost,
   UWakeHome, UAlarmEdit, UBedtimeEdit, UFires, UPlan, UMemory, UMe, UTabBar, U_TOK, sleepGoal */
// UNIFIED — shell: one phone, footer-tab routing, shared state. Renders the canonical
// screens from aurora-unified-screens.jsx. Bottom-sheet pickers via shared SheetHost.

const { useState: sState } = React;
const SK = U_TOK;

function UnifiedApp() {
  const [tab, setTab] = sState('wake');      // wake | memory | me
  const [stack, setStack] = sState(null);     // null | alarm | fires | plan

  // ── alarms (each fully self-contained) ──
  const [alarms, setAlarms] = sState([
    { id: 1, h: 6, m: 0, enabled: true, days: [true, true, true, true, true, false, false], label: 'Weekdays', method: 'Conversation', wakeSound: 'Birds at dawn', vibration: true, smartWake: '30 min window' },
    { id: 2, h: 7, m: 30, enabled: true, days: [false, false, false, false, false, true, true], label: 'Weekend', method: 'Conversation', wakeSound: 'Gentle chimes', vibration: true, smartWake: 'Off' },
    { id: 3, h: 6, m: 30, enabled: false, days: [false, false, false, false, false, false, false], label: 'Gym', method: 'Agent only', wakeSound: 'Rising tide', vibration: false, smartWake: '15 min window' },
  ]);
  const [sel, setSel] = sState(0);
  const alarm = alarms[sel] || alarms[0] || { h: 6, m: 0, method: 'Conversation' };   // drives preview / fires
  const newAlarm = () => ({ id: Date.now(), h: 7, m: 0, enabled: true, days: [true, true, true, true, true, false, false], label: 'Alarm', method: defaultMethod, wakeSound: 'Birds at dawn', vibration: true, smartWake: '30 min window' });
  const updateAlarm = (i, patch) => setAlarms(as => as.map((a, j) => j === i ? { ...a, ...patch } : a));
  const addAlarm = () => { setSel(alarms.length); setAlarms(as => [...as, newAlarm()]); };
  const deleteAlarm = (i) => { setSel(s => (s >= i && s > 0) ? s - 1 : s); setAlarms(as => as.filter((_, j) => j !== i)); };
  const [defaultMethod, setDefaultMethod] = sState('Conversation');
  const [voice, setVoice] = sState('Aurora — warm');
  const [sleepReport, setSleepReport] = sState(true);

  const goTab = (id) => { setTab(id); setStack(null); };
  // preview uses a fresh mount each time so the morning replays from the top
  const [fireKey, setFireKey] = sState(0);
  const preview = () => { setTab('wake'); setStack('fires'); setFireKey(k => k + 1); };

  let screenEl, footer = true;
  if (tab === 'wake') {
    if (stack === 'alarm') {
      footer = false;
      screenEl = <UAlarmEdit alarm={alarm} update={(patch) => updateAlarm(sel, patch)} onBack={() => setStack(null)}/>;
    } else if (stack === 'fires') {
      footer = false;
      screenEl = <UFires key={fireKey} method={alarm.method} alarm={alarm}
        onPlan={() => setStack('plan')} onDismiss={() => setStack(null)} onStop={() => setStack(null)}/>;
    } else if (stack === 'plan') {
      footer = false;
      screenEl = <UPlan onDone={() => setStack(null)}/>;
    } else {
      screenEl = <UWakeHome alarms={alarms} selectedIndex={sel} onSelect={setSel}
        onToggle={(i) => updateAlarm(i, { enabled: !alarms[i].enabled })} onAdd={addAlarm} onDelete={deleteAlarm}
        onDialChange={(i, t) => updateAlarm(i, t)} onEdit={(i) => { setSel(i); setStack('alarm'); }}/>;
    }
  } else if (tab === 'memory') {
    screenEl = <UMemory/>;
  } else {
    screenEl = <UMe defaultMethod={defaultMethod} setDefaultMethod={setDefaultMethod} voice={voice} setVoice={setVoice}
      sleepReport={sleepReport} setSleepReport={setSleepReport} tagline={`${alarms.filter(a => a.enabled).length} alarms active`}/>;
  }

  return (
    <div style={{ minHeight: '100vh', background: 'transparent', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '16px 0 18px' }}>
      <button onClick={preview} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 18px', borderRadius: 999, background: '#14110f', color: '#fff', border: 'none', fontFamily: 'Inter Tight, system-ui, sans-serif', fontSize: 13, fontWeight: 600, cursor: 'pointer', marginBottom: 16 }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="#ff7a59"><path d="M8 5v14l11-7z"/></svg>
        Preview wake-up
      </button>

      <IOSDevice width={390} height={812} dark={true}>
        <SheetHost>
          {screenEl}
          {footer && <UTabBar active={tab} onChange={goTab} tone={tab === 'memory' ? 'warm' : 'dark'}/>}
        </SheetHost>
      </IOSDevice>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<UnifiedApp/>);
