/* win95-extras.jsx — Minesweeper, Assistant, Welcome tips, Boot & Shutdown */

const { useState: useStateX, useEffect: useEffectX, useRef: useRefX } = React;

/* ---------------- Minesweeper ---------------- */
const MS_W = 9, MS_H = 9, MS_MINES = 10;
const NUM_COLORS = ['', '#0000ff', '#007b00', '#ff0000', '#00007b', '#7b0000', '#007b7b', '#000000', '#7b7b7b'];

function makeBoard() {
  return Array.from({ length: MS_H }, () => Array.from({ length: MS_W }, () => ({
    mine: false, open: false, flag: false, n: 0,
  })));
}
function plantMines(board, safeR, safeC) {
  let planted = 0;
  while (planted < MS_MINES) {
    const r = Math.floor(Math.random() * MS_H), c = Math.floor(Math.random() * MS_W);
    if (board[r][c].mine || (Math.abs(r - safeR) <= 1 && Math.abs(c - safeC) <= 1)) continue;
    board[r][c].mine = true; planted++;
  }
  for (let r = 0; r < MS_H; r++) for (let c = 0; c < MS_W; c++) {
    let n = 0;
    for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
      const rr = r + dr, cc = c + dc;
      if (rr >= 0 && rr < MS_H && cc >= 0 && cc < MS_W && board[rr][cc].mine) n++;
    }
    board[r][c].n = n;
  }
}
function flood(board, r, c) {
  const stack = [[r, c]];
  while (stack.length) {
    const [cr, cc] = stack.pop();
    const cell = board[cr][cc];
    if (cell.open || cell.flag) continue;
    cell.open = true;
    if (cell.n === 0 && !cell.mine) {
      for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
        const rr = cr + dr, ccx = cc + dc;
        if (rr >= 0 && rr < MS_H && ccx >= 0 && ccx < MS_W && !board[rr][ccx].open) stack.push([rr, ccx]);
      }
    }
  }
}

function Smiley({ state, onClick }) {
  // state: 'ok' | 'win' | 'dead'
  const eye = { position: 'absolute', width: 2, height: 2, background: '#000', borderRadius: '50%', top: 7 };
  return (
    <button className="w95-btn" style={{ padding: 3, width: 26, height: 26, display: 'grid', placeItems: 'center' }} onClick={onClick} aria-label="New game">
      <span style={{ position: 'relative', width: 17, height: 17, borderRadius: '50%', background: '#ffd700', boxShadow: 'inset -1px -1px 0 0 #b8860b, 0 0 0 1px #000', display: 'block' }}>
        {state === 'dead' ? (
          <span>
            <span style={{ ...eye, left: 4, top: 5, background: 'transparent', width: 4, height: 4, lineHeight: '4px', fontSize: 6 }}>✕</span>
            <span style={{ ...eye, left: 10, top: 5, background: 'transparent', width: 4, height: 4, lineHeight: '4px', fontSize: 6 }}>✕</span>
          </span>
        ) : (
          <span>
            <span style={{ ...eye, left: 5 }}></span>
            <span style={{ ...eye, left: 10 }}></span>
          </span>
        )}
        {state === 'win'
          ? <span style={{ position: 'absolute', left: 4, top: 3, fontSize: 7 }}>▄▄</span>
          : <span style={{ position: 'absolute', left: 5, [state === 'dead' ? 'bottom' : 'top']: state === 'dead' ? 2 : 11, width: 7, height: 3, borderBottom: state === 'dead' ? 'none' : '1.5px solid #000', borderTop: state === 'dead' ? '1.5px solid #000' : 'none', borderRadius: state === 'dead' ? '50% 50% 0 0' : '0 0 50% 50%' }}></span>}
      </span>
    </button>
  );
}

function MinesweeperWindow({ win, common, onAssist }) {
  const [board, setBoard] = useStateX(makeBoard);
  const [started, setStarted] = useStateX(false);
  const [state, setState] = useStateX('ok'); // ok | dead | win
  const [time, setTime] = useStateX(0);
  const timer = useRefX(null);

  useEffectX(() => {
    if (started && state === 'ok') {
      timer.current = setInterval(() => setTime((t) => Math.min(t + 1, 999)), 1000);
      return () => clearInterval(timer.current);
    }
  }, [started, state]);

  const reset = () => { setBoard(makeBoard()); setStarted(false); setState('ok'); setTime(0); };

  const checkWin = (b) => {
    const won = b.flat().every((c) => c.open || c.mine);
    if (won) { setState('win'); onAssist && onAssist('win'); }
    return won;
  };

  const openCell = (r, c) => {
    if (state !== 'ok') return;
    setBoard((prev) => {
      const b = prev.map((row) => row.map((cell) => ({ ...cell })));
      if (!started) { plantMines(b, r, c); setStarted(true); }
      const cell = b[r][c];
      if (cell.flag || cell.open) return prev;
      if (cell.mine) {
        b.forEach((row) => row.forEach((cl) => { if (cl.mine) cl.open = true; }));
        cell.boom = true;
        setState('dead');
        onAssist && onAssist('dead');
        return b;
      }
      flood(b, r, c);
      checkWin(b);
      return b;
    });
  };
  const flagCell = (e, r, c) => {
    e.preventDefault();
    if (state !== 'ok') return;
    setBoard((prev) => {
      const b = prev.map((row) => row.map((cell) => ({ ...cell })));
      const cell = b[r][c];
      if (!cell.open) cell.flag = !cell.flag;
      return b;
    });
  };

  const flags = board.flat().filter((c) => c.flag).length;
  const pad = (n) => String(Math.max(Math.min(n, 999), -99)).padStart(3, '0');

  return (
    <Window {...common} win={win} icon="minesweeper-32" width={236} resizable={false}
      menus={[
        { label: 'Game', items: [
          { label: 'New', onClick: reset },
          { sep: true },
          { label: 'Beginner', onClick: reset },
          { label: 'Expert', disabled: true },
          { sep: true },
          { label: 'Exit', onClick: () => common.onClose(win.id) },
        ]},
        { label: 'Help', items: [
          { label: 'How to play', onClick: () => onAssist && onAssist('mshelp') },
        ]},
      ]}
    >
      <div style={{ padding: 6 }}>
        <div className="w95-well" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 4, marginBottom: 6 }}>
          <div className="w95-led">{pad(MS_MINES - flags)}</div>
          <Smiley state={state} onClick={reset} />
          <div className="w95-led">{pad(time)}</div>
        </div>
        <div className="w95-well" style={{ padding: 3, width: 'fit-content', margin: '0 auto' }}>
          {board.map((row, r) => (
            <div key={r} style={{ display: 'flex' }}>
              {row.map((cell, c) => (
                <div key={c}
                  onClick={() => openCell(r, c)}
                  onContextMenu={(e) => flagCell(e, r, c)}
                  style={{
                    width: 20, height: 20, fontSize: 12, fontWeight: 'bold',
                    display: 'grid', placeItems: 'center', userSelect: 'none', cursor: 'default',
                    background: cell.boom ? '#ff0000' : 'var(--w95-material)',
                    boxShadow: cell.open
                      ? 'inset 1px 1px 0 0 var(--w95-border-dark)'
                      : 'inset 1px 1px 0 0 var(--w95-border-lightest), inset -1px -1px 0 0 var(--w95-border-dark), inset 2px 2px 0 0 var(--w95-border-lighter)',
                    color: NUM_COLORS[cell.n] || '#000',
                  }}>
                  {cell.open
                    ? (cell.mine ? <span style={{ fontSize: 11, color: '#000' }}>✹</span> : (cell.n || ''))
                    : (cell.flag ? <span style={{ fontSize: 10, color: '#c00' }}>⚑</span> : '')}
                </div>
              ))}
            </div>
          ))}
        </div>
        <div style={{ fontSize: 10, textAlign: 'center', marginTop: 5, color: '#444' }}>Right-click to flag · first click is safe</div>
      </div>
    </Window>
  );
}

/* ---------------- Welcome / tips dialog ---------------- */
const TIPS = [
  'Cip manages payment authentication processing hundreds of billions of $ a year at Stripe.',
  'Double-click any desktop icon — everything opens in a real, draggable window.',
  'Cip\'s products protect billions of dollars of e-commerce from fraud on a weekly basis.',
  'Try Start ▸ Run… and type "minesweeper".',
  'The Recycle Bin protected us from Cip\'s other ideas.',
  'Network Neighborhood connects to GitHub, LinkedIn, X, his blog and his Stripe Sessions talk.',
  'Open My Computer ▸ Credits to see the open-source project this site is built on.',
  'Cip speaks English, Italian, Romanian and Spanish. The desktop only speaks Win95.',
];

function WelcomeWindow({ win, common, openWindow }) {
  const [tip, setTip] = useStateX(0);
  return (
    <Window {...common} win={win} icon="chip-flag" width={480}>
      <div style={{ display: 'flex', gap: 0 }}>
        <div style={{ background: 'var(--w95-header-bg)', width: 90, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <img src={ICON('chip-flag-64')} style={{ width: 48, height: 48, imageRendering: 'pixelated' }} alt="" />
        </div>
        <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10, flexGrow: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 'bold' }}>Welcome to Windows Chip 95</div>
          <div style={{ fontSize: 12, lineHeight: 1.5 }}>
            The personal site of <b>Cip Blujdea — Product Builder</b>. CV, projects and links, served the way the internet intended: at 800×600.
          </div>
          <fieldset className="w95-fieldset" style={{ marginTop: 4 }}>
            <span className="w95-fieldset-legend">Did you know…</span>
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', minHeight: 52 }}>
              <img src={ICON('bulb-32')} style={{ width: 32, height: 32, imageRendering: 'pixelated', flexShrink: 0 }} alt="" />
              <div style={{ lineHeight: 1.5 }}>{TIPS[tip]}</div>
            </div>
          </fieldset>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <W95Button onClick={() => setTip((tip + 1) % TIPS.length)}>Next Tip</W95Button>
            <W95Button onClick={() => { openWindow('cv'); common.onClose(win.id); }}>Read the CV</W95Button>
            <W95Button def onClick={() => common.onClose(win.id)}>Close</W95Button>
          </div>
        </div>
      </div>
    </Window>
  );
}

/* ---------------- Assistant (bulb buddy) ---------------- */
const ASSIST_LINES = {
  cv: 'It looks like you\'re reading a CV. Would you like me to point out the payment uplift, or will you find it yourself?',
  projects: 'Four side-projects, zero venture funding. Double-click one to take a look.',
  network: 'Connecting to the information superhighway… done. Say hi on LinkedIn.',
  mail: 'It looks like you\'re writing a letter. Cip replies faster than a 28.8k modem.',
  mine: 'Careful. Cip has never lost a game of Minesweeper. (This cannot be independently verified.)',
  dead: 'BOOM. Even great product managers ship the occasional incident.',
  win: 'You won! That\'s the kind of metric Cip would put on a dashboard.',
  recycle: 'Every builder has a folder like this. At least Cip labels his.',
  mshelp: 'Left-click to reveal, right-click to flag. The numbers count neighbouring mines. Good luck!',
  idle: 'Psst — try Start ▸ Run… and type "minesweeper".',
};

function Assistant({ msg, onClose }) {
  if (!msg) return null;
  return (
    <div style={{ position: 'absolute', right: 14, bottom: 48, zIndex: 4000, width: 230 }} data-screen-label="Assistant">
      <div className="w95-window" style={{ padding: 2 }}>
        <div style={{ background: '#ffffcc', boxShadow: 'var(--w95-shadow-input)', padding: '10px 10px', fontSize: 12, lineHeight: 1.5, position: 'relative' }}>
          {msg}
          <button className="w95-btn w95-titlebar-btn" style={{ position: 'absolute', top: 4, right: 4 }} onClick={onClose} aria-label="Dismiss assistant">✕</button>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 4, marginRight: 12 }}>
        <div className="w95-raised" style={{ padding: 6 }}>
          <img src={ICON('bulb-32')} style={{ width: 32, height: 32, imageRendering: 'pixelated', display: 'block' }} alt="Assistant" />
        </div>
      </div>
    </div>
  );
}

/* ---------------- Boot screen ---------------- */
function BootScreen({ onDone }) {
  useEffectX(() => {
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [onDone]);
  return (
    <div onClick={onDone} style={{ position: 'absolute', inset: 0, background: '#000', zIndex: 9000, cursor: 'pointer', display: 'grid', placeItems: 'center' }} data-screen-label="Boot screen">
      <div style={{ textAlign: 'center' }}>
        <img src={ICON('chip-flag-64')} style={{ width: 96, height: 96, imageRendering: 'pixelated' }} alt="" />
        <div style={{ color: '#fff', fontFamily: 'var(--w95-font)', fontSize: 26, marginTop: 18, fontWeight: 'bold' }}>Windows<span style={{ fontWeight: 'normal', color: '#c3c7cb' }}> Chip </span>95</div>
        <div style={{ color: '#aaa', fontFamily: 'var(--w95-font)', fontSize: 12, marginTop: 8 }}>Starting Windows Chip 95…</div>
        <div style={{ width: 220, height: 12, margin: '18px auto 0', background: '#222', overflow: 'hidden', position: 'relative' }}>
          <div className="boot-bar"></div>
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 10, right: 14, color: '#555', fontFamily: "'Courier New', monospace", fontSize: 11 }}>click to skip</div>
    </div>
  );
}

/* ---------------- Shutdown screen ---------------- */
function ShutdownScreen({ onRestart }) {
  return (
    <div onClick={onRestart} style={{ position: 'fixed', inset: 0, background: '#000', zIndex: 9500, display: 'grid', placeItems: 'center', cursor: 'pointer' }} data-screen-label="Shutdown screen">
      <div style={{ textAlign: 'center', fontFamily: 'var(--w95-font)' }}>
        <div style={{ color: '#ffa500', fontSize: 26, fontWeight: 'bold', lineHeight: 1.5, textShadow: '2px 2px 0 #5a3a00' }}>
          It's now safe to close this tab.
        </div>
        <div style={{ color: '#888', fontSize: 13, marginTop: 16 }}>
          (or click anywhere to hire— er, restart)
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  MinesweeperWindow, WelcomeWindow, Assistant, BootScreen, ShutdownScreen, ASSIST_LINES, TIPS,
});
