/* global React, ReactDOM,
   useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakColor,
   useAudio, MacShell, PhoneShell */

const { useState, useEffect } = React;

/* Decode the desktop wallpaper during the boot animation so the first paint
   of the desktop is the fully-decoded image, not a progressive JPEG reveal. */
if (typeof Image !== 'undefined') {
  const _wp = new Image();
  _wp.src = 'img/mac-wallpaper-dark.jpg';
  _wp.decode?.().catch(() => {});
}

/* ============== Tweakable defaults =================================== */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "darkMode": false,
  "skipIntro": false,
  "accent": "#0a84ff"
}/*EDITMODE-END*/;

/* The viewport breakpoint at which we switch to the iPhone shell. */
const PHONE_BREAKPOINT = 760;

/* ============== App router ==========================================
   Owns the cross-platform state: tweaks + audio. Picks the shell.
   `restartKey` lets a Restart action remount the active shell so its
   internal phase machine resets, even though tweaks/audio survive. */
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const audioApi = useAudio();

  const [autoIsPhone, setAutoIsPhone] = useState(
    typeof window !== 'undefined' && window.innerWidth < PHONE_BREAKPOINT
  );
  // null = auto-detect; 'mac' / 'phone' = manual override (dev only, not persisted)
  const [override, setOverride] = useState(null);
  const [restartKey, setRestartKey] = useState(0);

  useEffect(() => {
    const onResize = () => setAutoIsPhone(window.innerWidth < PHONE_BREAKPOINT);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const platform = override || (autoIsPhone ? 'phone' : 'mac');

  // Apply platform attribute (drives CSS scoping).
  useEffect(() => {
    document.documentElement.setAttribute('data-platform', platform === 'phone' ? 'ios' : 'mac');
  }, [platform]);

  // Apply theme + accent (shared across both shells).
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-theme', tweaks.darkMode ? 'dark' : 'light');
    r.style.setProperty('--mac-accent', tweaks.accent || '#0a84ff');
    r.style.setProperty('--mac-accent-hover', tweaks.accent || '#0a84ff');
    const tint = tweaks.accent || '#0a84ff';
    r.style.setProperty('--mac-accent-tint', tint + '28');
  }, [tweaks.darkMode, tweaks.accent]);

  const Shell = platform === 'phone' ? PhoneShell : MacShell;

  return (
    <>
      <Shell key={`${platform}-${restartKey}`}
             tweaks={tweaks} setTweak={setTweak} audioApi={audioApi}/>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Appearance">
          <TweakRadio
            label="Theme"
            value={tweaks.darkMode ? 'dark' : 'light'}
            options={[{value:'light',label:'Light'},{value:'dark',label:'Dark'}]}
            onChange={(v) => setTweak('darkMode', v === 'dark')}
          />
          <TweakColor label="Accent" value={tweaks.accent}
                      onChange={(v) => setTweak('accent', v)}/>
        </TweakSection>
        <TweakSection title="Device">
          <TweakRadio
            label="Override"
            value={override || 'auto'}
            options={[
              {value:'auto',  label:'Auto'},
              {value:'mac',   label:'Mac'},
              {value:'phone', label:'iPhone'},
            ]}
            onChange={(v) => setOverride(v === 'auto' ? null : v)}
          />
        </TweakSection>
        <TweakSection title="Intro">
          <TweakToggle
            label="Skip the intro"
            value={tweaks.skipIntro}
            onChange={(v) => {
              setTweak('skipIntro', v);
              setRestartKey(k => k + 1);
            }}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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