/* Main Windows 98 desktop shell */

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

/* ============== Draggable Window ============== */
function Win98Window({ win, active, onFocus, onClose, onMin, onMove, onResize, children }) {
  const dragState = useRef(null);
  const resizeState = useRef(null);

  useEffect(() => {
    const onMM = (e) => {
      if (dragState.current) {
        const dx = e.clientX - dragState.current.sx;
        const dy = e.clientY - dragState.current.sy;
        onMove(win.id, dragState.current.x + dx, Math.max(0, dragState.current.y + dy));
      }
      if (resizeState.current) {
        const dw = e.clientX - resizeState.current.sx;
        const dh = e.clientY - resizeState.current.sy;
        onResize(win.id,
          Math.max(220, resizeState.current.w + dw),
          Math.max(120, resizeState.current.h + dh)
        );
      }
    };
    const onMU = () => { dragState.current = null; resizeState.current = null; };
    window.addEventListener("mousemove", onMM);
    window.addEventListener("mouseup", onMU);
    return () => { window.removeEventListener("mousemove", onMM); window.removeEventListener("mouseup", onMU); };
  }, [win.id, onMove, onResize]);

  const startDrag = (e) => {
    if (e.button !== 0) return;
    onFocus(win.id);
    dragState.current = { sx: e.clientX, sy: e.clientY, x: win.x, y: win.y };
  };
  const startResize = (e) => {
    e.stopPropagation();
    onFocus(win.id);
    resizeState.current = { sx: e.clientX, sy: e.clientY, w: win.w, h: win.h };
  };

  return (
    <div
      className={`window ${active ? 'active' : ''} ${win.minimized ? 'minimized' : ''}`}
      style={{ left: win.x, top: win.y, width: win.w, height: win.h, zIndex: win.z }}
      onMouseDown={() => onFocus(win.id)}
    >
      <div className="window-title" onMouseDown={startDrag} onDoubleClick={() => {}}>
        <span className="window-title-icon">{win.icon}</span>
        <span className="window-title-text">{win.title}</span>
        <div className="window-controls">
          <button className="title-btn" onClick={() => onMin(win.id)} title="Réduire">
            <svg width="8" height="8" viewBox="0 0 8 8"><rect x="0" y="6" width="7" height="2" fill="#000"/></svg>
          </button>
          <button className="title-btn" title="Agrandir">
            <svg width="8" height="8" viewBox="0 0 8 8"><rect x="0" y="0" width="8" height="8" fill="none" stroke="#000" strokeWidth="1"/><rect x="0" y="0" width="8" height="2" fill="#000"/></svg>
          </button>
          <button className="title-btn" onClick={() => onClose(win.id)} title="Fermer">
            <svg width="8" height="8" viewBox="0 0 8 8">
              <path d="M0 0 L8 8 M8 0 L0 8" stroke="#000" strokeWidth="1.2" fill="none"/>
            </svg>
          </button>
        </div>
      </div>
      {children}
      {!win.noResize && <div className="resize-handle" onMouseDown={startResize}></div>}
    </div>
  );
}

/* ============== Start Menu ============== */
function StartMenu({ open, onPick, onClose }) {
  if (!open) return null;
  const items = [
    { ico: "📂", label: "Programmes", sub: true },
    { ico: "📑", label: "Documents", sub: true },
    { ico: "⚙️", label: "Paramètres", sub: true },
    { ico: "🔍", label: "Rechercher", sub: true },
    { ico: "❓", label: "Aide" },
    { ico: "▶", label: "Exécuter..." },
    { sep: true },
    { ico: "🚪", label: "Arrêter...", action: "shutdown" },
  ];
  const programs = [
    { ico: "📝", label: "Bloc-notes", action: "notepad" },
    { ico: "📃", label: "WordPad", action: "wordpad" },
    { ico: "🎨", label: "Paint", action: "paint" },
    { ico: "🧮", label: "Calculatrice", action: "calc" },
    { ico: "🌐", label: "Internet Explorer", action: "ie" },
    { ico: "👥", label: "MSN Messenger", action: "msn" },
    { ico: "🎵", label: "Winamp", action: "winamp" },
    { ico: "🎙", label: "Magnétophone", action: "recorder" },
    { ico: "🂡", label: "Solitaire", action: "solitaire" },
    { ico: "💣", label: "Démineur", action: "mines" },
    { ico: "🖥", label: "Poste de travail", action: "mycomputer" },
  ];
  return (
    <>
      <div style={{ position: 'fixed', inset: 0, zIndex: 9997 }} onClick={onClose}></div>
      <div className="start-menu" onClick={(e) => e.stopPropagation()}>
        <div className="start-menu-band">
          <div className="start-menu-band-text">
            Windows<b>98</b>
          </div>
        </div>
        <div className="start-menu-items">
          {/* Programs as a flat list (acts like primary fly-out) */}
          {programs.map((p, i) => (
            <div className="start-menu-item" key={`p${i}`} onClick={() => { onPick(p.action); onClose(); }}>
              <span className="smi-ico">{p.ico}</span>
              <span>{p.label}</span>
            </div>
          ))}
          <div className="start-menu-sep"></div>
          {items.map((it, i) => it.sep
            ? <div className="start-menu-sep" key={i}></div>
            : (
              <div
                className={`start-menu-item ${it.sub ? 'has-submenu' : ''}`}
                key={i}
                onClick={() => { if (it.action) { onPick(it.action); onClose(); } }}
              >
                <span className="smi-ico">{it.ico}</span>
                <span>{it.label}</span>
              </div>
            )
          )}
        </div>
      </div>
    </>
  );
}

/* ============== Taskbar ============== */
function Taskbar({ windows, activeId, startOpen, onStart, onTaskClick }) {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000 * 15);
    return () => clearInterval(id);
  }, []);
  const hh = String(now.getHours()).padStart(2, "0");
  const mm = String(now.getMinutes()).padStart(2, "0");

  return (
    <div className="taskbar">
      <button className={`start-button ${startOpen ? 'active' : ''}`} onClick={onStart}>
        <svg width="18" height="18" viewBox="0 0 18 18" style={{ flexShrink: 0 }}>
          <rect x="1" y="1" width="7" height="7" fill="#ff0000"/>
          <rect x="9" y="1" width="7" height="7" fill="#00aa00"/>
          <rect x="1" y="9" width="7" height="7" fill="#0066ff"/>
          <rect x="9" y="9" width="7" height="7" fill="#ffcc00"/>
        </svg>
        <span>Démarrer</span>
      </button>
      <div className="taskbar-divider"></div>
      <div className="task-items">
        {windows.map(w => (
          <button
            key={w.id}
            className={`task-item ${w.id === activeId && !w.minimized ? 'active' : ''}`}
            onClick={() => onTaskClick(w.id)}
          >
            <span className="task-icon">{w.icon}</span>
            <span className="task-text">{w.title}</span>
          </button>
        ))}
      </div>
      <div className="systray">
        <div className="systray-icons">
          <span title="Volume">🔊</span>
          <span title="Réseau">📡</span>
          <span title="Antivirus">🛡</span>
        </div>
        <div className="systray-clock">{hh}:{mm}</div>
      </div>
    </div>
  );
}

/* ============== Desktop Icons (draggable, persisted) ============== */
const DEFAULT_ICONS = [
  { id: 'mycomputer', label: 'Poste de travail',  ico: '🖥️', action: 'mycomputer' },
  { id: 'docs',       label: 'Mes documents',     ico: '📁', action: 'mycomputer' },
  { id: 'ie',         label: 'Internet Explorer', ico: '🌐', action: 'ie' },
  { id: 'recycle',    label: 'Corbeille',         ico: '🗑️', action: 'recycle' },
  { id: 'notepad',    label: 'Bloc-notes.txt',    ico: '📝', action: 'notepad' },
  { id: 'paint',      label: 'Paint',             ico: '🎨', action: 'paint' },
  { id: 'mines',      label: 'Démineur',          ico: '💣', action: 'mines' },
  { id: 'msn',        label: 'MSN Messenger',     ico: '👥', action: 'msn' },
  { id: 'winamp',     label: 'Winamp',            ico: '🎵', action: 'winamp' },
  { id: 'wordpad',    label: 'WordPad',           ico: '📃', action: 'wordpad' },
  { id: 'calc',       label: 'Calculatrice',      ico: '🧮', action: 'calc' },
  { id: 'solitaire',  label: 'Solitaire',         ico: '🂡', action: 'solitaire' },
  { id: 'recorder',   label: 'Magnéto.',          ico: '🎙', action: 'recorder' },
  { id: 'network',    label: 'Voisinage réseau',  ico: '🖧', action: 'network' },
];

function defaultPositions() {
  const out = {};
  DEFAULT_ICONS.forEach((ic, i) => {
    out[ic.id] = { x: 16, y: 16 + i * 76 };
  });
  return out;
}

function DesktopIcons({ onOpen }) {
  const [selected, setSelected] = useState(null);
  const [positions, setPositions] = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('w98_icons') || 'null');
      return saved && typeof saved === 'object' ? { ...defaultPositions(), ...saved } : defaultPositions();
    } catch { return defaultPositions(); }
  });
  const dragRef = useRef(null);

  useEffect(() => {
    const onMM = (e) => {
      if (!dragRef.current) return;
      const { id, sx, sy, ix, iy } = dragRef.current;
      const x = Math.max(0, Math.min(window.innerWidth - 80, ix + (e.clientX - sx)));
      const y = Math.max(0, Math.min(window.innerHeight - 100, iy + (e.clientY - sy)));
      setPositions(p => ({ ...p, [id]: { x, y } }));
    };
    const onMU = () => {
      if (dragRef.current) {
        try { localStorage.setItem('w98_icons', JSON.stringify(positions)); } catch {}
        dragRef.current = null;
      }
    };
    window.addEventListener('mousemove', onMM);
    window.addEventListener('mouseup', onMU);
    return () => {
      window.removeEventListener('mousemove', onMM);
      window.removeEventListener('mouseup', onMU);
    };
  }, [positions]);

  const startDrag = (e, ic) => {
    if (e.button !== 0) return;
    setSelected(ic.id);
    const pos = positions[ic.id] || { x: 16, y: 16 };
    dragRef.current = { id: ic.id, sx: e.clientX, sy: e.clientY, ix: pos.x, iy: pos.y };
  };

  return (
    <>
      {DEFAULT_ICONS.map(ic => {
        const p = positions[ic.id] || { x: 16, y: 16 };
        return (
          <div
            key={ic.id}
            className={`desktop-icon ${selected === ic.id ? 'selected' : ''}`}
            style={{ position: 'absolute', left: p.x, top: p.y }}
            onMouseDown={(e) => startDrag(e, ic)}
            onClick={(e) => { e.stopPropagation(); setSelected(ic.id); }}
            onDoubleClick={() => onOpen(ic.action)}
          >
            <div className="icon-img">{ic.ico}</div>
            <div className="icon-label">{ic.label}</div>
          </div>
        );
      })}
    </>
  );
}

/* ============== App registry ============== */
const APPS = {
  notepad:    { title: "Sans titre - Bloc-notes",        icon: "📝", w: 480, h: 340, comp: () => <Notepad /> },
  mycomputer: { title: "Poste de travail",               icon: "🖥️", w: 560, h: 380, comp: ({ open }) => <MyComputer onOpen={open} /> },
  ie:         { title: "Bienvenue - Microsoft Internet Explorer", icon: "🌐", w: 640, h: 460, comp: () => <InternetExplorer /> },
  mines:      { title: "Démineur",                       icon: "💣", w: 200, h: 270, comp: () => <Minesweeper />, noResize: true },
  paint:      { title: "Sans titre - Paint",             icon: "🎨", w: 560, h: 420, comp: () => <Paint /> },
  welcome:    { title: "Bienvenue dans Windows 98",      icon: "💡", w: 420, h: 220, comp: ({ close }) => <WelcomeDialog onClose={close} />, noResize: true },
  properties: { title: "Propriétés de Affichage",        icon: "🖼", w: 380, h: 320, comp: () => <Properties />, noResize: true },
  msn:        { title: "Windows Live Messenger",        icon: "\uD83D\uDC65", w: 280, h: 460, comp: ({ open }) => <MsnMessenger open={open} /> },
  'msn-chat': { title: "Conversation",                  icon: "\uD83D\uDCAC", w: 440, h: 420, comp: ({ payload }) => <MsnChat payload={payload} /> },
  winamp:     { title: "Winamp",                         icon: "\uD83C\uDFB5", w: 360, h: 410, comp: () => <Winamp />, noResize: true },
  calc:       { title: "Calculatrice",                   icon: "\uD83E\uDDEE", w: 220, h: 280, comp: () => <Calculator />, noResize: true },
  wordpad:    { title: "Document - WordPad",             icon: "\uD83D\uDCC3", w: 540, h: 420, comp: () => <WordPad /> },
  solitaire:  { title: "Solitaire",                      icon: "\uD83C\uDCA1", w: 600, h: 480, comp: () => <Solitaire /> },
  recorder:   { title: "Son - Magn\u00E9tophone",             icon: "\uD83C\uDF99", w: 320, h: 200, comp: () => <SoundRecorder />, noResize: true },
  bob:        { title: "Microsoft Bob",                  icon: "\uD83C\uDFE0", w: 360, h: 320, comp: () => <MicrosoftBob />, noResize: true },
  recycle:    { title: "Corbeille",                      icon: "🗑️", w: 420, h: 240, comp: () => (
    <div style={{ padding: 0, display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Affichage", "Aide"]} />
      <div className="window-body sunken" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 8, color: '#444' }}>
        <div style={{ fontSize: 48 }}>🗑️</div>
        <div>La Corbeille est vide.</div>
      </div>
    </div>
  )},
  network:    { title: "Voisinage réseau",               icon: "🖧", w: 380, h: 220, comp: () => (
    <div style={{ padding: 0, display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Affichage", "Aide"]} />
      <div className="window-body sunken" style={{ padding: 14, fontSize: 12 }}>
        <p style={{ marginTop: 0 }}>Aucun ordinateur n'a été trouvé sur votre réseau local.</p>
        <p>Vérifiez la connexion du câble RJ-45 ou redémarrez votre ordinateur.</p>
      </div>
    </div>
  )},
};

function WindowMenu({ items }) {
  return (
    <div className="window-menu">
      {items.map((it, i) => (
        <div className="window-menu-item" key={i}>
          <span style={{ textDecoration: 'underline' }}>{it[0]}</span>{it.slice(1)}
        </div>
      ))}
    </div>
  );
}

/* ============== Desktop / App ============== */
function Desktop() {
  const tweakDefaults = /*EDITMODE-BEGIN*/{
    "wallpaper": "teal",
    "titleStyle": "navy",
    "showClippy": false,
    "scanlines": false,
    "showCRT": false,
    "sounds": true
  }/*EDITMODE-END*/;

  const [t, setTweak] = useTweaks(tweakDefaults);
  const [wins, setWins] = useState([]);
  const [activeId, setActiveId] = useState(null);
  const [startOpen, setStartOpen] = useState(false);
  const [zCounter, setZCounter] = useState(100);
  const [bsod, setBsod] = useState(false);
  const [shutdownOpen, setShutdownOpen] = useState(false);
  const [shutdownState, setShutdownState] = useState(null); // 'shutdown' | 'standby' | 'restartdos'
  const [screensaver, setScreensaver] = useState(false);
  const [ctxMenu, setCtxMenu] = useState(null);
  const nextId = useRef(1);
  const welcomedRef = useRef(false);
  const idleRef = useRef(null);

  // Wire mute state on Sounds singleton
  useEffect(() => { if (window.Sounds) window.Sounds.setMuted(!t.sounds); }, [t.sounds]);

  const open = useCallback((key, opts = {}) => {
    if (key === 'shutdown') {
      setShutdownOpen(true);
      return;
    }
    const def = APPS[key];
    if (!def) return;
    const { payload, allowMultiple, titleSuffix } = opts;
    setWins(prev => {
      // dedupe unless multi or different payload-id allowed
      if (!allowMultiple) {
        const existing = prev.find(w => w.app === key);
        if (existing) {
          setActiveId(existing.id);
          setZCounter(z => z + 1);
          return prev.map(w => w.id === existing.id ? { ...w, minimized: false, z: zCounter + 1 } : w);
        }
      } else if (payload && payload.id) {
        // dedupe within multi by payload id
        const existing = prev.find(w => w.app === key && w.payloadKey === payload.id);
        if (existing) {
          setActiveId(existing.id);
          setZCounter(z => z + 1);
          return prev.map(w => w.id === existing.id ? { ...w, minimized: false, z: zCounter + 1 } : w);
        }
      }
      const id = nextId.current++;
      const w = Math.min(def.w, window.innerWidth - 40);
      const h = Math.min(def.h, window.innerHeight - 80);
      const offset = prev.length * 24;
      const x = 60 + offset % 240;
      const y = 40 + offset % 160;
      const title = titleSuffix ? `${titleSuffix} - ${def.title}` : def.title;
      const newWin = {
        id, app: key, title, icon: def.icon, x, y, w, h,
        z: zCounter + 1, minimized: false, noResize: def.noResize,
        payload, payloadKey: payload && payload.id,
      };
      setActiveId(id);
      setZCounter(z => z + 1);
      return [...prev, newWin];
    });
  }, [zCounter]);

  // Welcome dialog on first load
  useEffect(() => {
    if (welcomedRef.current) return;
    welcomedRef.current = true;
    setTimeout(() => open('welcome'), 350);
  }, [open]);

  // Idle screensaver (60s)
  useEffect(() => {
    const reset = () => {
      clearTimeout(idleRef.current);
      idleRef.current = setTimeout(() => setScreensaver(true), 60000);
    };
    const evs = ['mousemove', 'mousedown', 'keydown', 'touchstart'];
    evs.forEach(e => window.addEventListener(e, reset));
    reset();
    return () => { clearTimeout(idleRef.current); evs.forEach(e => window.removeEventListener(e, reset)); };
  }, []);

  // Ctrl+Alt+B easter egg → Microsoft Bob
  useEffect(() => {
    const onKey = (e) => {
      if (e.ctrlKey && e.altKey && (e.key === 'b' || e.key === 'B')) {
        e.preventDefault();
        open('bob');
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const onShutdownChoice = (c) => {
    setShutdownOpen(false);
    if (window.Sounds) window.Sounds.shutdown();
    if (c === 'restart') {
      setTimeout(() => window.location.reload(), 700);
    } else if (c === 'shutdown') {
      setTimeout(() => setShutdownState('shutdown'), 700);
    } else if (c === 'standby') {
      setTimeout(() => setShutdownState('standby'), 700);
    } else if (c === 'restartdos') {
      setTimeout(() => setShutdownState('restartdos'), 700);
    }
  };

  const openContextMenu = (e) => {
    if (e.target !== e.currentTarget) return;
    e.preventDefault();
    setCtxMenu({
      x: Math.min(e.clientX, window.innerWidth - 220),
      y: Math.min(e.clientY, window.innerHeight - 280),
    });
  };

  const close = (id) => {
    setWins(prev => prev.filter(w => w.id !== id));
    setActiveId(curr => curr === id ? null : curr);
  };
  const minimize = (id) => {
    setWins(prev => prev.map(w => w.id === id ? { ...w, minimized: true } : w));
    setActiveId(curr => curr === id ? null : curr);
  };
  const focus = (id) => {
    setActiveId(id);
    setZCounter(z => {
      setWins(prev => prev.map(w => w.id === id ? { ...w, z: z + 1, minimized: false } : w));
      return z + 1;
    });
  };
  const move = (id, x, y) => setWins(prev => prev.map(w => w.id === id ? { ...w, x, y } : w));
  const resize = (id, w, h) => setWins(prev => prev.map(W => W.id === id ? { ...W, w, h } : W));

  const onTaskClick = (id) => {
    const w = wins.find(W => W.id === id);
    if (!w) return;
    if (w.minimized || w.id !== activeId) focus(id);
    else minimize(id);
  };

  return (
    <>
      <div className={`desktop wallpaper-${t.wallpaper}`} onContextMenu={openContextMenu}>
        <DesktopIcons onOpen={open} />
        {wins.map(w => {
          const App = APPS[w.app].comp;
          return (
            <Win98Window
              key={w.id}
              win={w}
              active={w.id === activeId && !w.minimized}
              onFocus={focus}
              onClose={close}
              onMin={minimize}
              onMove={move}
              onResize={resize}
            >
              <App open={open} close={() => close(w.id)} payload={w.payload} />
            </Win98Window>
          );
        })}

        {t.showClippy && (
          <div style={{
            position: 'absolute', right: 24, bottom: 56,
            background: '#ffffd0', border: '1px solid #000',
            padding: 8, fontSize: 11, width: 200, zIndex: 5000,
            boxShadow: '2px 2px 0 #888'
          }}>
            <div style={{ marginBottom: 6 }}>
              <b>Clippy :</b> on dirait que vous écrivez une lettre. Voulez-vous de l'aide ?
            </div>
            <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
              <button className="btn" style={{ minWidth: 0, padding: '2px 6px' }} onClick={() => setTweak('showClippy', false)}>Non</button>
              <button className="btn" style={{ minWidth: 0, padding: '2px 6px' }}>Oui</button>
            </div>
            <div style={{ position: 'absolute', right: 18, bottom: -14, fontSize: 24 }}>📎</div>
          </div>
        )}

        {t.scanlines && (
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            background: 'repeating-linear-gradient(0deg, rgba(0,0,0,0.10) 0 1px, transparent 1px 3px)',
            zIndex: 8000,
          }}></div>
        )}
        {t.showCRT && (
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            boxShadow: 'inset 0 0 120px rgba(0,0,0,0.55), inset 0 0 30px rgba(0,0,0,0.5)',
            background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.25) 100%)',
            zIndex: 8001,
          }}></div>
        )}

        <StartMenu open={startOpen} onPick={open} onClose={() => setStartOpen(false)} />
        <Taskbar
          windows={wins}
          activeId={activeId}
          startOpen={startOpen}
          onStart={() => setStartOpen(v => !v)}
          onTaskClick={onTaskClick}
        />

        {bsod && <BSOD onDismiss={() => { setBsod(false); window.location.reload(); }} />}

        {shutdownOpen && (
          <ShutdownDialog
            onChoose={onShutdownChoice}
            onCancel={() => setShutdownOpen(false)}
          />
        )}

        {shutdownState === 'shutdown' && (
          <div className="shutdown-final" onClick={() => window.location.reload()}>
            <div>Vous pouvez maintenant éteindre votre ordinateur en toute sécurité.</div>
            <div className="shutdown-final-hint">(Cliquez pour rallumer)</div>
          </div>
        )}
        {shutdownState === 'standby' && (
          <div className="shutdown-final standby" onClick={() => setShutdownState(null)}></div>
        )}
        {shutdownState === 'restartdos' && (
          <div className="dos-screen" onClick={() => window.location.reload()}>
            <pre>{`Microsoft(R) Windows 98
   (C)Copyright Microsoft Corp 1981-1999.

C:\\WINDOWS>echo Off
C:\\WINDOWS>type README.TXT
C:\\WINDOWS>cd \\
C:\\>_`}</pre>
          </div>
        )}

        {screensaver && <MystifyScreensaver onDismiss={() => setScreensaver(false)} />}

        {ctxMenu && (
          <ContextMenu
            x={ctxMenu.x}
            y={ctxMenu.y}
            onClose={() => setCtxMenu(null)}
            items={[
              { label: 'Active Desktop', right: '▶', disabled: true },
              { label: 'Réorganiser les icônes', right: '▶', disabled: true },
              { label: "Aligner sur la grille", action: () => { localStorage.removeItem('w98_icons'); window.location.reload(); } },
              { sep: true },
              { label: 'Actualiser', action: () => window.location.reload() },
              { sep: true },
              { label: 'Coller', disabled: true },
              { label: 'Coller le raccourci', disabled: true },
              { sep: true },
              { label: 'Nouveau', right: '▶', disabled: true },
              { sep: true },
              { label: 'Propriétés', action: () => open('properties') },
            ]}
          />
        )}
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Fond d'écran">
          <TweakSelect
            label="Wallpaper"
            value={t.wallpaper}
            onChange={(v) => setTweak('wallpaper', v)}
            options={[
              { value: 'teal',    label: '— Teal classique' },
              { value: 'plus',    label: '— Bleu Plus!' },
              { value: 'clouds',  label: '— Nuages (gradient)' },
              { value: 'setup',   label: '— Setup (quadrillé)' },
              { value: 'img-underwater',  label: 'Plus! · Underwater' },
              { value: 'img-space',       label: 'Plus! · Space' },
              { value: 'img-jungle',      label: 'Plus! · Jungle' },
              { value: 'img-inside',      label: 'Plus! · Inside your Computer' },
              { value: 'img-davinci',     label: 'Plus! · Leonardo da Vinci' },
              { value: 'img-mystery',     label: 'Plus! · Mystery' },
              { value: 'img-nature',      label: 'Plus! · Nature' },
              { value: 'img-travel',      label: 'Plus! · Travel' },
              { value: 'img-sports',      label: 'Plus! · Sports' },
              { value: 'img-science',     label: 'Plus! · Science' },
              { value: 'img-baseball',    label: 'Plus! · Baseball' },
              { value: 'img-dangerous',   label: 'Plus! · Dangerous Creatures' },
              { value: 'img-sixties',     label: "Plus! · The 60's USA" },
              { value: 'img-goldenera',   label: 'Plus! · The Golden Era' },
              { value: 'img-morewindows', label: 'Plus! · More Windows' },
              { value: 'img-cloudslogo',  label: 'Win98 · Clouds + logo' },
              { value: 'img-win98theme',  label: 'Win98 · Thème défaut' },
              { value: 'img-morewinblur', label: 'Win98 · More Windows close-up' },
              { value: 'img-setupblue',   label: 'Win98 · Setup blue' },
            ]}
          />
        </TweakSection>
        <TweakSection label="Effets CRT">
          <TweakToggle value={t.scanlines} onChange={(v) => setTweak('scanlines', v)} label="Lignes de balayage" />
          <TweakToggle value={t.showCRT}   onChange={(v) => setTweak('showCRT', v)}   label="Vignette CRT" />
        </TweakSection>
        <TweakSection label="Son">
          <TweakToggle value={t.sounds} onChange={(v) => setTweak('sounds', v)} label="Sons système" />
        </TweakSection>
        <TweakSection label="Easter eggs">
          <TweakToggle value={t.showClippy} onChange={(v) => setTweak('showClippy', v)} label="Afficher Clippy" />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

function App() {
  const [stage, setStage] = useState('logon'); // logon → boot → hourglass → desktop
  if (stage === 'logon') return <LogonScreen onLogin={() => setStage('boot')} />;
  if (stage === 'boot') return <BootSequence onDone={() => setStage('hourglass')} />;
  if (stage === 'hourglass') return <Hourglass onDone={() => setStage('desktop')} delay={800} />;
  return <Desktop />;
}

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