/* App content components for the Win98 prototype */

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

/* ============== Notepad ============== */
function Notepad() {
  const [text, setText] = useState(
    "Bienvenue dans le Bloc-notes\r\n" +
    "----------------------------\r\n\r\n" +
    "Cette interface est une recréation du look-and-feel de Windows 98.\r\n" +
    "Essayez :\r\n" +
    "  • Déplacer les fenêtres en saisissant la barre de titre\r\n" +
    "  • Cliquer sur Démarrer pour ouvrir le menu\r\n" +
    "  • Cliquer sur les boutons _ □ X de la barre de titre\r\n" +
    "  • Lancer Démineur (Programmes › Jeux › Démineur)\r\n" +
    "  • Dessiner dans Paint\r\n\r\n" +
    "Tapez ce que vous voulez ici..."
  );
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Recherche", "Aide"]} />
      <div style={{ flex: 1, padding: 2, background: '#c0c0c0' }}>
        <textarea
          className="notepad-text"
          value={text}
          onChange={(e) => setText(e.target.value)}
          spellCheck={false}
        />
      </div>
    </div>
  );
}

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

/* ============== My Computer ============== */
function MyComputer({ onOpen }) {
  const drives = [
    { icon: "💾", label: "Disquette 3½ (A:)" },
    { icon: "🖴", label: "Disque local (C:)" },
    { icon: "💿", label: "Lecteur CD (D:)" },
    { icon: "🗂️", label: "Panneau de configuration" },
    { icon: "🖨️", label: "Imprimantes" },
    { icon: "📡", label: "Accès réseau à distance" },
  ];
  const [selected, setSelected] = useState(null);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Affichage", "Aller à", "Favoris", "Aide"]} />
      <div className="window-toolbar">
        <ToolbarBtn icon="⬅" label="Précéd." />
        <ToolbarBtn icon="➡" label="Suivant" />
        <ToolbarBtn icon="⬆" label="Dossier parent" />
        <div className="toolbar-sep"></div>
        <ToolbarBtn icon="✂" label="Couper" />
        <ToolbarBtn icon="📋" label="Copier" />
        <ToolbarBtn icon="📥" label="Coller" />
        <div className="toolbar-sep"></div>
        <ToolbarBtn icon="🗑" label="Supprimer" />
        <ToolbarBtn icon="ℹ" label="Propriétés" />
      </div>
      <div className="address-bar">
        <label>Adresse</label>
        <div className="address-input">
          <span>🖥️</span>
          <span>Poste de travail</span>
        </div>
      </div>
      <div className="window-body sunken" onClick={() => setSelected(null)}>
        <div className="file-list">
          {drives.map((d, i) => (
            <div
              key={i}
              className={`file-item ${selected === i ? 'selected' : ''}`}
              onClick={(e) => { e.stopPropagation(); setSelected(i); }}
              onDoubleClick={() => onOpen && onOpen(d.label)}
            >
              <div className="fi-icon">{d.icon}</div>
              <div className="fi-label">{d.label}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="window-statusbar">
        <div className="status-cell">{selected !== null ? `1 objet sélectionné` : `${drives.length} objet(s)`}</div>
        <div className="status-cell" style={{ minWidth: 90 }}>Poste de travail</div>
      </div>
    </div>
  );
}

function ToolbarBtn({ icon, label }) {
  return (
    <button className="toolbar-btn">
      <span className="ico">{icon}</span>
      <span>{label}</span>
    </button>
  );
}

/* ============== Internet Explorer ============== */
function InternetExplorer() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Affichage", "Aller à", "Favoris", "Aide"]} />
      <div className="window-toolbar">
        <ToolbarBtn icon="⬅" label="Précéd." />
        <ToolbarBtn icon="➡" label="Suivant" />
        <ToolbarBtn icon="⛔" label="Arrêter" />
        <ToolbarBtn icon="🔄" label="Actualiser" />
        <ToolbarBtn icon="🏠" label="Démarrage" />
        <div className="toolbar-sep"></div>
        <ToolbarBtn icon="🔍" label="Recherche" />
        <ToolbarBtn icon="⭐" label="Favoris" />
        <ToolbarBtn icon="📰" label="Imprimer" />
      </div>
      <div className="address-bar">
        <label>Adresse</label>
        <div className="address-input">
          <span>🌐</span>
          <span>http://www.geocities.com/~retroweb/index.html</span>
        </div>
        <button className="btn" style={{ minWidth: 0, padding: '2px 8px' }}>Atteindre</button>
      </div>
      <div className="window-body sunken">
        <div className="ie-content">
          <h1>★ Bienvenue sur ma page perso ★</h1>
          <p>
            Vous êtes le <span className="ie-counter">000 0421</span> visiteur depuis le 14 août 1998.
            Cette page est <b>OPTIMISÉE</b> pour Internet Explorer 4.0 en <i>800×600</i>.
          </p>

          <div className="ie-marquee">
            <span className="ie-marquee-inner">
              ✨✨✨ NOUVEAU : ajoutez ma page à vos favoris ! &nbsp; ✨ Sous construction ✨ &nbsp; Signez mon livre d'or ! &nbsp; ✨✨✨
            </span>
          </div>

          <h2>Sommaire</h2>
          <ul>
            <li><a>Page d'accueil</a></li>
            <li><a>À propos de moi</a></li>
            <li><a>Mes liens préférés</a></li>
            <li><a>Galerie de GIFs animés</a></li>
            <li><a>Livre d'or</a></li>
          </ul>

          <h2>À propos</h2>
          <p>
            Salut ! Bienvenue sur <b>mon coin du Web</b>. Vous trouverez ici mes hobbies, mes
            sites préférés et plein d'images cool. N'hésitez pas à m'envoyer un{" "}
            <a>e-mail</a> ✉ !
          </p>

          <div style={{ textAlign: 'center', margin: '14px 0' }}>
            <span className="ie-img-placeholder">[ photo.jpg ]</span>
            <span className="ie-img-placeholder" style={{ animationDelay: '-3s' }}>[ banner.gif ]</span>
          </div>

          <h2>Webrings</h2>
          <p>
            Ce site fait partie du <b>Webring Rétro</b>. <br />
            <a>« Précédent</a> &nbsp;|&nbsp; <a>Aléatoire</a> &nbsp;|&nbsp; <a>Liste</a> &nbsp;|&nbsp; <a>Suivant »</a>
          </p>

          <hr className="ie-hr" />
          <p style={{ fontSize: 11, color: '#555' }}>
            Dernière mise à jour : 12/03/1999 — Best viewed with Internet Explorer 4.0+
          </p>
        </div>
      </div>
      <div className="window-statusbar">
        <div className="status-cell">Terminé</div>
        <div className="status-cell" style={{ minWidth: 90 }}>🌐 Internet</div>
      </div>
    </div>
  );
}

/* ============== Minesweeper ============== */
function Minesweeper() {
  const ROWS = 9, COLS = 9, MINES = 10;

  const make = () => {
    const grid = Array.from({ length: ROWS }, () => Array.from({ length: COLS }, () => ({
      mine: false, revealed: false, flagged: false, n: 0
    })));
    let placed = 0;
    while (placed < MINES) {
      const r = Math.floor(Math.random() * ROWS);
      const c = Math.floor(Math.random() * COLS);
      if (!grid[r][c].mine) { grid[r][c].mine = true; placed++; }
    }
    for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
      if (grid[r][c].mine) continue;
      let n = 0;
      for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
        const nr = r + dr, nc = c + dc;
        if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;
        if (grid[nr][nc].mine) n++;
      }
      grid[r][c].n = n;
    }
    return grid;
  };

  const [grid, setGrid] = useState(make);
  const [status, setStatus] = useState("playing"); // playing | dead | won
  const [time, setTime] = useState(0);
  const [pressed, setPressed] = useState(false);

  useEffect(() => {
    if (status !== "playing") return;
    const id = setInterval(() => setTime(t => Math.min(999, t + 1)), 1000);
    return () => clearInterval(id);
  }, [status]);

  const flags = grid.flat().filter(c => c.flagged).length;

  const reset = () => { setGrid(make()); setStatus("playing"); setTime(0); };

  const reveal = (r, c, g = grid) => {
    const next = g.map(row => row.map(cell => ({...cell})));
    const stack = [[r, c]];
    let dead = false;
    while (stack.length) {
      const [r, c] = stack.pop();
      const cell = next[r][c];
      if (cell.revealed || cell.flagged) continue;
      cell.revealed = true;
      if (cell.mine) { dead = true; continue; }
      if (cell.n === 0) {
        for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
          const nr = r + dr, nc = c + dc;
          if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;
          if (!next[nr][nc].revealed) stack.push([nr, nc]);
        }
      }
    }
    if (dead) {
      for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
        if (next[r][c].mine) next[r][c].revealed = true;
      }
      setStatus("dead");
    } else {
      const remaining = next.flat().filter(c => !c.revealed && !c.mine).length;
      if (remaining === 0) setStatus("won");
    }
    setGrid(next);
  };

  const flag = (r, c) => {
    if (status !== "playing") return;
    const next = grid.map(row => row.map(cell => ({...cell})));
    if (!next[r][c].revealed) next[r][c].flagged = !next[r][c].flagged;
    setGrid(next);
  };

  const pad = (n, w = 3) => String(n).padStart(w, "0");
  const face = status === "dead" ? "😵" : status === "won" ? "😎" : pressed ? "😮" : "🙂";

  return (
    <div className="mine-app">
      <div className="mine-header">
        <div className="lcd">{pad(MINES - flags)}</div>
        <button className="mine-smiley" onClick={reset}>{face}</button>
        <div className="lcd">{pad(time)}</div>
      </div>
      <div className="mine-grid" style={{ gridTemplateColumns: `repeat(${COLS}, 18px)` }}>
        {grid.map((row, r) => row.map((cell, c) => {
          const cls = ["mine-cell"];
          if (cell.revealed) cls.push("revealed");
          if (cell.revealed && cell.mine) cls.push("mine");
          if (cell.flagged && !cell.revealed) cls.push("flagged");
          if (cell.revealed && cell.n > 0 && !cell.mine) cls.push(`mc-${cell.n}`);
          return (
            <div
              key={`${r}-${c}`}
              className={cls.join(" ")}
              onMouseDown={() => status === "playing" && setPressed(true)}
              onMouseUp={() => setPressed(false)}
              onMouseLeave={() => setPressed(false)}
              onClick={() => status === "playing" && reveal(r, c)}
              onContextMenu={(e) => { e.preventDefault(); flag(r, c); }}
            >
              {cell.revealed
                ? (cell.mine ? "💣" : (cell.n > 0 ? cell.n : ""))
                : ""}
            </div>
          );
        }))}
      </div>
    </div>
  );
}

/* ============== Paint ============== */
function Paint() {
  const canvasRef = useRef(null);
  const [tool, setTool] = useState("pen"); // pen | eraser | fill | line
  const [color, setColor] = useState("#000000");
  const drawing = useRef(false);
  const last = useRef(null);

  const palette = [
    "#000000","#808080","#800000","#808000","#008000","#008080","#000080","#800080","#808040","#004040","#0080ff","#004080","#4000ff","#804000",
    "#ffffff","#c0c0c0","#ff0000","#ffff00","#00ff00","#00ffff","#0000ff","#ff00ff","#ffff80","#00ff80","#80ffff","#8080ff","#ff0080","#ff8040",
  ];

  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, c.width, c.height);
  }, []);

  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    return { x: Math.floor(e.clientX - r.left), y: Math.floor(e.clientY - r.top) };
  };

  const onDown = (e) => {
    drawing.current = true;
    last.current = pos(e);
    if (tool === "fill") {
      doFill(last.current.x, last.current.y);
      drawing.current = false;
    }
  };
  const onMove = (e) => {
    if (!drawing.current) return;
    const p = pos(e);
    const ctx = canvasRef.current.getContext("2d");
    ctx.strokeStyle = tool === "eraser" ? "#fff" : color;
    ctx.lineWidth = tool === "eraser" ? 12 : 2;
    ctx.lineCap = "round";
    ctx.beginPath();
    ctx.moveTo(last.current.x, last.current.y);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
    last.current = p;
  };
  const onUp = () => { drawing.current = false; };

  const doFill = (x, y) => {
    const ctx = canvasRef.current.getContext("2d");
    const W = canvasRef.current.width, H = canvasRef.current.height;
    const img = ctx.getImageData(0, 0, W, H);
    const data = img.data;
    const idx = (x, y) => (y * W + x) * 4;
    const start = idx(x, y);
    const sr = data[start], sg = data[start+1], sb = data[start+2];
    const hex = color.slice(1);
    const tr = parseInt(hex.slice(0,2),16), tg = parseInt(hex.slice(2,4),16), tb = parseInt(hex.slice(4,6),16);
    if (sr === tr && sg === tg && sb === tb) return;
    const stack = [[x, y]];
    while (stack.length) {
      const [cx, cy] = stack.pop();
      if (cx < 0 || cx >= W || cy < 0 || cy >= H) continue;
      const i = idx(cx, cy);
      if (data[i] !== sr || data[i+1] !== sg || data[i+2] !== sb) continue;
      data[i] = tr; data[i+1] = tg; data[i+2] = tb; data[i+3] = 255;
      stack.push([cx+1, cy], [cx-1, cy], [cx, cy+1], [cx, cy-1]);
    }
    ctx.putImageData(img, 0, 0);
  };

  const clear = () => {
    const c = canvasRef.current;
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, c.width, c.height);
  };

  const tools = [
    { id: "pen",    ico: "✏" },
    { id: "eraser", ico: "🩹" },
    { id: "fill",   ico: "🪣" },
    { id: "line",   ico: "╱" },
    { id: "rect",   ico: "▢" },
    { id: "circle", ico: "◯" },
    { id: "spray",  ico: "✷" },
    { id: "pick",   ico: "💧" },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <WindowMenu items={["Fichier", "Edition", "Affichage", "Image", "Couleurs", "Aide"]} />
      <div className="paint-shell">
        <div className="paint-tools">
          {tools.map(t => (
            <button
              key={t.id}
              className={`paint-tool ${tool === t.id ? 'active' : ''}`}
              onClick={() => setTool(t.id)}
            >{t.ico}</button>
          ))}
          <button className="paint-tool" onClick={clear} title="Effacer" style={{ gridColumn: '1 / span 2' }}>🗑</button>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div className="paint-canvas-wrap">
            <canvas
              ref={canvasRef}
              width={420}
              height={260}
              className="paint-canvas"
              onMouseDown={onDown}
              onMouseMove={onMove}
              onMouseUp={onUp}
              onMouseLeave={onUp}
            />
          </div>
          <div className="paint-palette">
            <div style={{
              gridRow: '1 / span 2', gridColumn: '1', display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}>
              <div style={{
                width: 24, height: 24, background: color,
                border: '1px solid #000', boxShadow: '2px 2px 0 #fff, 2px 2px 0 1px #888'
              }}></div>
            </div>
            {palette.map((c, i) => (
              <div
                key={i}
                className={`paint-swatch ${c === color ? 'active' : ''}`}
                style={{ background: c, gridColumn: (i % 14) + 2, gridRow: Math.floor(i / 14) + 1 }}
                onClick={() => setColor(c)}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============== Welcome dialog ============== */
function WelcomeDialog({ onClose }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="dialog-row">
        <div className="dialog-icon">💡</div>
        <div className="dialog-text">
          <div style={{ fontWeight: 'bold', fontSize: 14, marginBottom: 6 }}>Bienvenue dans Windows 98</div>
          <div>
            Cliquez sur <b>Démarrer</b> en bas à gauche pour ouvrir des programmes, double-cliquez
            sur une icône du bureau, ou déplacez les fenêtres en saisissant leur barre de titre.
          </div>
          <div style={{ marginTop: 10 }}>
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <input type="checkbox" defaultChecked /> Afficher cette boîte au démarrage
            </label>
          </div>
        </div>
      </div>
      <div style={{ flex: 1 }}></div>
      <div className="dialog-buttons">
        <button className="btn" onClick={onClose}>OK</button>
        <button className="btn" onClick={onClose}>Annuler</button>
      </div>
    </div>
  );
}

/* ============== Properties dialog (right-click → properties) ============== */
function Properties() {
  return (
    <div style={{ padding: 12, fontSize: 12 }}>
      <div style={{ marginBottom: 6, fontWeight: 'bold' }}>Propriétés de Affichage</div>
      <div style={{
        background: '#fff', height: 90, marginBottom: 10,
        border: '1px solid #000', display: 'flex', alignItems: 'center', justifyContent: 'center',
        backgroundImage: 'linear-gradient(135deg, #008080 0 50%, #c0c0c0 50%)'
      }}>
        <div style={{
          width: 110, height: 14,
          background: 'linear-gradient(90deg, #000080, #1084d0)',
          color: '#fff', fontSize: 9, padding: '2px 4px', boxSizing: 'border-box',
          boxShadow: '0 60px 0 #c0c0c0, 0 60px 0 1px #000, 0 -2px 0 -1px #fff'
        }}>Fenêtre active</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <div>
          <div style={{ marginBottom: 4 }}>Schéma :</div>
          <select style={{ width: '100%', fontFamily: 'inherit', fontSize: 11 }}>
            <option>Windows standard</option>
            <option>Briques</option>
            <option>Désert</option>
            <option>Forêt</option>
            <option>Rose</option>
          </select>
        </div>
        <div>
          <div style={{ marginBottom: 4 }}>Élément :</div>
          <select style={{ width: '100%', fontFamily: 'inherit', fontSize: 11 }}>
            <option>Bureau</option>
            <option>Barre de titre active</option>
            <option>Menu</option>
          </select>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 6, marginTop: 14 }}>
        <button className="btn">OK</button>
        <button className="btn">Annuler</button>
        <button className="btn">Appliquer</button>
      </div>
    </div>
  );
}

/* ============== Winamp ============== */
function Winamp() {
  const [playing, setPlaying] = useState(false);
  const [trackIdx, setTrackIdx] = useState(0);
  const [time, setTime] = useState(0);
  const tracks = [
    { artist: 'DJ Mike Llama', title: 'Llama Whippin\' Intro', dur: 5 },
    { artist: 'Eiffel 65',     title: 'Blue (Da Ba Dee)',     dur: 217 },
    { artist: 'Aqua',          title: 'Barbie Girl',          dur: 196 },
    { artist: 'Vengaboys',     title: 'We Like to Party!',    dur: 217 },
    { artist: 'Smash Mouth',   title: 'All Star',             dur: 200 },
    { artist: 'Britney Spears',title: 'Baby One More Time',   dur: 211 },
  ];
  const track = tracks[trackIdx];

  useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setTime(t => {
        if (t + 1 >= track.dur) {
          setTrackIdx(i => (i + 1) % tracks.length);
          return 0;
        }
        return t + 1;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [playing, track.dur]);

  // Visualizer bars (animated even when paused, but more lively when playing)
  const [bars, setBars] = useState(() => Array(20).fill(0).map(() => Math.random()));
  useEffect(() => {
    const id = setInterval(() => {
      setBars(prev => prev.map(v => {
        const target = playing ? Math.random() : v * 0.85;
        return v * 0.6 + target * 0.4;
      }));
    }, playing ? 80 : 220);
    return () => clearInterval(id);
  }, [playing]);

  const fmt = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
  const pick = (i) => { setTrackIdx(i); setTime(0); setPlaying(true); };

  return (
    <div className="winamp">
      <div className="winamp-title">
        <span>W I N A M P</span>
        <span className="winamp-llama">It really whips the llama's ass</span>
      </div>
      <div className="winamp-main">
        <div className="winamp-display">
          <div className="winamp-time">{fmt(time)}</div>
          <div className="winamp-vis">
            {bars.map((v, i) => (
              <div key={i} className="winamp-bar" style={{ height: `${4 + v * 28}px` }}></div>
            ))}
          </div>
          <div className="winamp-track">
            <div className="winamp-track-scroll">
              {trackIdx + 1}. {track.artist} — {track.title} ({fmt(track.dur)}) ★
            </div>
          </div>
          <div className="winamp-bitrate">
            <span>192</span><span>kbps</span><span>44</span><span>kHz</span><span>stereo</span>
          </div>
        </div>
        <div className="winamp-controls">
          <button className="winamp-btn" onClick={() => pick((trackIdx - 1 + tracks.length) % tracks.length)}>⏮</button>
          <button className="winamp-btn" onClick={() => setPlaying(true)}>▶</button>
          <button className="winamp-btn" onClick={() => setPlaying(false)}>⏸</button>
          <button className="winamp-btn" onClick={() => { setPlaying(false); setTime(0); }}>⏹</button>
          <button className="winamp-btn" onClick={() => pick((trackIdx + 1) % tracks.length)}>⏭</button>
          <button className="winamp-btn winamp-btn-eject" title="Éjecter">⏏</button>
        </div>
      </div>
      <div className="winamp-playlist">
        <div className="winamp-playlist-title">Playlist Editor</div>
        <div className="winamp-playlist-body">
          {tracks.map((t, i) => (
            <div
              key={i}
              className={`winamp-row ${i === trackIdx ? 'active' : ''}`}
              onDoubleClick={() => pick(i)}
            >
              <span className="winamp-row-num">{i + 1}.</span>
              <span className="winamp-row-title">{t.artist} — {t.title}</span>
              <span className="winamp-row-dur">{fmt(t.dur)}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.Notepad = Notepad;
window.MyComputer = MyComputer;
window.InternetExplorer = InternetExplorer;
window.Minesweeper = Minesweeper;
window.Paint = Paint;
window.WelcomeDialog = WelcomeDialog;
window.Properties = Properties;
window.Winamp = Winamp;
