// app.jsx v2 — 3-tab nav (Home / Play / You), Watt mascot, motion-rich.
// Adds live-preview QR + cleaner tweaks.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "sage",
  "typeface": "dmsans",
  "heroStyle": "bold"
}/*EDITMODE-END*/;

const { useState, useEffect, useRef, useMemo } = React;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const palette = PALETTES[t.palette] || PALETTES.sage;
  const type = TYPE_PAIRS[t.typeface] || TYPE_PAIRS.dmsans;
  const c = palette;

  useEffect(() => {
    Object.values(TYPE_PAIRS).forEach(tp => {
      const id = `gf-${tp.stack}`;
      if (document.getElementById(id)) return;
      const link = document.createElement('link');
      link.id = id;
      link.rel = 'stylesheet';
      link.href = `https://fonts.googleapis.com/css2?family=${tp.stack}&display=swap`;
      document.head.appendChild(link);
    });
  }, []);

  // App state — start on the login screen unless a token is already stored.
  const [phase, setPhase] = useState(() => SaveHorAPI.isLoggedIn() ? 'app' : 'login');
  const [tab, setTab] = useState('home');

  // Onboarding
  const [onbStep, setOnbStep] = useState(0);
  const [block, setBlock] = useState('472');
  const [unit, setUnit] = useState('#03-21');
  const [kwh, setKwh] = useState('348');
  const [useAvg, setUseAvg] = useState(false);
  const [goal, setGoal] = useState('steady');
  const [notif, setNotif] = useState(true);

  // Live home — full device list (multiple aircons across rooms)
  const [devices, setDevices] = useState(DEFAULT_DEVICES);
  const [recDone, setRecDone] = useState(false);

  // Points + missions
  const [points, setPoints] = useState(2640);
  const [missions, setMissions] = useState(DEFAULT_MISSIONS);
  const [streak] = useState(7);
  const [toast, setToast] = useState(null);
  const [redeeming, setRedeeming] = useState(null);

  // Month spend (animated)
  const [monthSpent] = useState(74.10);
  const monthBudget = 90;

  const completeMission = (id) => {
    setMissions(ms => ms.map(m => m.id === id ? { ...m, state: 'done' } : m));
    const m = missions.find(x => x.id === id);
    if (m) {
      setPoints(p => p + m.points);
      setToast({ title: `+${m.points} points`, sub: m.title, mood: 'cheer' });
      setTimeout(() => setToast(null), 2600);
    }
  };

  const doRedeem = () => {
    setPoints(p => p - redeeming.cost);
    setRedeeming({ ...redeeming, confirmed: true });
  };

  const finishOnboarding = () => setPhase('app');

  // Tweaks panel
  const tweaks = (
    <TweaksPanel title="SaveHor Tweaks">
      <TweakSection label="Palette" />
      <TweakColor label="Theme" value={t.palette}
        options={[
          [PALETTES.sage.primary, PALETTES.sage.bg, PALETTES.sage.accent],
          [PALETTES.eucalyptus.primary, PALETTES.eucalyptus.bg, PALETTES.eucalyptus.accent],
          [PALETTES.tea.primary, PALETTES.tea.bg, PALETTES.tea.accent],
        ]}
        onChange={(v) => {
          const idx = [
            [PALETTES.sage.primary, PALETTES.sage.bg, PALETTES.sage.accent].join('|'),
            [PALETTES.eucalyptus.primary, PALETTES.eucalyptus.bg, PALETTES.eucalyptus.accent].join('|'),
            [PALETTES.tea.primary, PALETTES.tea.bg, PALETTES.tea.accent].join('|'),
          ].indexOf(v.join('|'));
          setTweak('palette', ['sage', 'eucalyptus', 'tea'][idx] || 'sage');
        }} />

      <TweakSection label="Typography" />
      <TweakRadio label="Type" value={t.typeface}
        options={['dmsans', 'jakarta', 'manrope']}
        onChange={(v) => setTweak('typeface', v)} />

      <TweakSection label="Home hero" />
      <TweakRadio label="Hero style" value={t.heroStyle}
        options={['light', 'bold']}
        onChange={(v) => setTweak('heroStyle', v)} />

      <TweakSection label="Demo" />
      <TweakButton label="Restart onboarding"
        onClick={() => { setPhase('onboarding'); setOnbStep(0); setTab('home'); }} />
      <TweakButton label="Reset missions"
        onClick={() => setMissions(DEFAULT_MISSIONS)} secondary />
    </TweaksPanel>
  );

  // Onboarding sequence (kept compact — 5 steps default now)
  const onbSeq = ['welcome', 'household', 'usage', 'goal', 'perms'];
  const onbCurrent = onbSeq[onbStep];
  const onbNext = () => {
    if (onbStep < onbSeq.length - 1) setOnbStep(onbStep + 1);
    else finishOnboarding();
  };
  const onbBack = () => setOnbStep(s => Math.max(0, s - 1));

  const onboardingScreen = (() => {
    const common = { c, onNext: onbNext, onBack: onbBack };
    switch (onbCurrent) {
      case 'welcome':   return <OnbWelcome {...common} />;
      case 'household': return <OnbHousehold {...common} block={block} setBlock={setBlock} unit={unit} setUnit={setUnit} />;
      case 'usage':     return <OnbUsage {...common} kwh={kwh} setKwh={setKwh} useAvg={useAvg} setUseAvg={setUseAvg} />;
      case 'goal':      return <OnbGoal {...common} goal={goal} setGoal={setGoal} baseKwh={parseInt(kwh, 10) || 348} />;
      case 'perms':     return <OnbPerms {...common} notif={notif} setNotif={setNotif} />;
      default: return null;
    }
  })();

  const tabContent = (() => {
    switch (tab) {
      case 'home':
        return <HomeScreen
          c={c} points={points} setTab={setTab}
          heroStyle={t.heroStyle}
          devices={devices} setDevices={setDevices}
          recDone={recDone} setRecDone={setRecDone}
          missions={missions} completeMission={completeMission}
          monthSpent={monthSpent} monthBudget={monthBudget} />;
      case 'play':
        return <PlayScreen
          c={c} missions={missions} completeMission={completeMission}
          streak={streak} points={points}
          redeeming={redeeming} setRedeeming={setRedeeming} doRedeem={doRedeem} />;
      case 'analysis':
        return <AnalysisScreen c={c} />;
      case 'you':
        return <YouScreen
          c={c} points={points} streak={streak}
          onLogout={() => { SaveHorAPI.clearSession(); setPhase('login'); }} />;
      default: return null;
    }
  })();

  // Screen body
  const screen = (
    <div style={{ width: '100%', height: '100%', background: c.bg, color: c.text, fontFamily: type.ui, position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', paddingTop: 'env(safe-area-inset-top, 0px)' }}>
      {phase === 'login' ? (
        <LoginScreen c={c} onLoggedIn={() => { setPhase('app'); setTab('home'); }} />
      ) : phase === 'onboarding' ? (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '14px 24px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <button onClick={onbStep === 0 ? null : onbBack} style={{
              width: 36, height: 36, border: 'none', background: 'transparent',
              cursor: onbStep === 0 ? 'default' : 'pointer', opacity: onbStep === 0 ? 0 : 1,
            }}><IcArrowL size={20} color={c.text} /></button>
            <Stepper step={onbStep} total={onbSeq.length} c={c} />
            <button onClick={finishOnboarding} style={{
              border: 'none', background: 'transparent', cursor: 'pointer',
              fontSize: 13.5, color: c.textMuted, fontWeight: 500, fontFamily: 'inherit',
            }}>Skip</button>
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflowY: 'auto' }}>
            {onboardingScreen}
          </div>
        </div>
      ) : (
        <>
          <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', WebkitOverflowScrolling: 'touch' }}>
            {tabContent}
          </div>
          <TabBar active={tab} onChange={setTab} c={c} />
        </>
      )}

      {toast && (
        <div style={{ position: 'absolute', left: 16, right: 16, bottom: 110, zIndex: 60, animation: 'sh-slideup 0.3s ease' }}>
          <div style={{
            background: c.text, color: '#fff', borderRadius: 18,
            padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
            boxShadow: '0 12px 32px rgba(0,0,0,0.22)',
          }}>
            <Watt size={40} color={c.primary} bg="#fff" mood={toast.mood || 'cheer'} anim="bounce" />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 700, letterSpacing: -0.1 }}>{toast.title}</div>
              {toast.sub && <div style={{ fontSize: 12, opacity: 0.7, marginTop: 1 }}>{toast.sub}</div>}
            </div>
          </div>
        </div>
      )}

    </div>
  );

  // Full-viewport web app. On phones/tablets the app fills the screen; on wide
  // desktops it's centered in a comfortable column with the app's own bg around
  // it — no device frame, status bar, or home indicator.
  return (
    <div style={{
      position: 'fixed', inset: 0, background: c.bg,
      display: 'flex', justifyContent: 'center',
      fontFamily: type.ui,
    }}>
      <div style={{
        position: 'relative',
        width: '100%', maxWidth: 480, height: '100%',
        overflow: 'hidden', background: c.bg,
        boxShadow: '0 0 60px rgba(0,0,0,0.08)',
      }}>
        {screen}
      </div>
      {tweaks}
    </div>
  );
}

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