// ============ ANGELO OS ============
const { useState: useStateOS, useEffect: useEffectOS, useRef: useRefOS, useCallback: useCallbackOS } = React;

const FOLDER_ORDER = ["Proyectos","Educación","Experiencia","Café Tecnológico","Investigación","Contacto"];

function Clock() {
  const [now, setNow] = useStateOS(new Date());
  useEffectOS(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const fmt = now.toLocaleString('es-AR', { weekday: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
  return <span>{fmt}</span>;
}

function OSWindow({ kind, name, onClose, onFocus, z, initialPos }) {
  // kind: "folder" | "terminal" | "readme"
  const winRef = useRefOS(null);
  const [pos, setPos] = useStateOS(initialPos || { x: 60, y: 40 });
  const dragRef = useRefOS({ dragging: false });

  const startDrag = (e) => {
    onFocus?.();
    const r = winRef.current.getBoundingClientRect();
    const parent = winRef.current.parentElement.getBoundingClientRect();
    dragRef.current = {
      dragging: true,
      offX: e.clientX - r.left,
      offY: e.clientY - r.top,
      parent
    };
    const move = (ev) => {
      const d = dragRef.current;
      if (!d.dragging) return;
      const newX = Math.max(0, Math.min(d.parent.width - 200, ev.clientX - d.parent.left - d.offX));
      const newY = Math.max(0, Math.min(d.parent.height - 60, ev.clientY - d.parent.top - d.offY));
      setPos({ x: newX, y: newY });
    };
    const up = () => {
      dragRef.current.dragging = false;
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
  };

  return (
    <div
      ref={winRef}
      className={`os-window ${kind === 'terminal' ? 'terminal' : ''}`}
      style={{ left: pos.x, top: pos.y, zIndex: z }}
      onMouseDown={onFocus}
    >
      <div className="os-titlebar" onMouseDown={startDrag}>
        <div className="os-dots">
          <span className="r" onClick={onClose} title="Cerrar"></span>
          <span className="y" title="Minimizar"></span>
          <span className="g" title="Maximizar"></span>
        </div>
        <span className="os-title">{name}</span>
        <span style={{width: 50}}></span>
      </div>
      {kind === 'folder' && <FolderBody folder={name} />}
      {kind === 'readme' && <ReadmeBody />}
      {kind === 'terminal' && <TerminalBody />}
    </div>
  );
}

function FolderBody({ folder }) {
  const files = window.OS_FS[folder] || [];
  const [sel, setSel] = useStateOS(0);
  const cur = files[sel];
  return (
    <>
      <div className="os-toolbar">
        <span className="nav-arrow">‹</span>
        <span className="nav-arrow">›</span>
        <span className="path">~/{folder.toLowerCase().replace(/ /g, '-')}/</span>
        <span style={{flex:1}}/>
        <span>{files.length} items</span>
      </div>
      <div className="os-body">
        <div className="os-sidebar">
          {files.map((f, i) => (
            <div key={i} className={`file-item ${i === sel ? 'active' : ''}`} onClick={() => setSel(i)}>
              <span>📄</span><span>{f.name}</span>
            </div>
          ))}
        </div>
        <div className="os-pane">{cur ? cur.body : <span className="empty">— vacío —</span>}</div>
      </div>
    </>
  );
}

function ReadmeBody() {
  const file = window.OS_DESKTOP_FILES[0];
  return (
    <>
      <div className="os-toolbar">
        <span className="nav-arrow">‹</span>
        <span className="nav-arrow">›</span>
        <span className="path">~/README.txt</span>
      </div>
      <div className="os-pane" style={{gridColumn: '1 / -1'}}>{file.body}</div>
    </>
  );
}

const TERM_HELP = `comandos disponibles:
  help       lista de comandos
  whoami     quién soy
  ls         lista carpetas
  cat <f>    leer archivo (ej: cat about.txt)
  contact    abrir info de contacto
  clear      limpiar terminal
  konami     ✨
  chess      ir a sección AURA`;

function TerminalBody() {
  const [lines, setLines] = useStateOS([
    { t: 'out', v: 'angelo.os terminal · v1.0' },
    { t: 'dim', v: 'tipeá "help" para ver comandos disponibles' }
  ]);
  const [input, setInput] = useStateOS('');
  const inputRef = useRefOS(null);

  useEffectOS(() => { inputRef.current?.focus(); }, []);

  const run = (cmd) => {
    const c = cmd.trim().toLowerCase();
    const echo = { t: 'echo', v: <span><span className="prompt">angelo@uai:~$</span> <span className="out">{cmd}</span></span> };
    let out = [];
    if (!c) out = [];
    else if (c === 'help') out = [{ t: 'out', v: TERM_HELP }];
    else if (c === 'whoami') out = [{ t: 'out', v: 'angelo@uai:~$ ingeniero en formación · constructor de cosas' }];
    else if (c === 'ls') out = [{ t: 'out', v: FOLDER_ORDER.join('   ') + '   README.txt  CV.pdf' }];
    else if (c.startsWith('cat ')) {
      const f = c.slice(4).trim();
      if (f === 'about.txt' || f === 'readme.txt') out = [{ t: 'out', v: window.OS_DESKTOP_FILES[0].body }];
      else out = [{ t: 'err', v: `cat: ${f}: no encontrado. probá: cat about.txt` }];
    }
    else if (c === 'contact') out = [{ t: 'out', v: window.OS_FS['Contacto'][0].body }];
    else if (c === 'clear') { setLines([]); setInput(''); return; }
    else if (c === 'konami') {
      out = [{ t: 'accent', v: '✨ konami activado · 5 segundos en verde matrix' }];
      document.documentElement.style.setProperty('--cyan', '#22c55e');
      document.documentElement.style.setProperty('--violet', '#16a34a');
      setTimeout(() => {
        document.documentElement.style.removeProperty('--cyan');
        document.documentElement.style.removeProperty('--violet');
      }, 5000);
    }
    else if (c === 'chess' || c === 'aura') {
      out = [{ t: 'accent', v: '→ scrolling a AURA...' }];
      setTimeout(() => document.getElementById('aura')?.scrollIntoView({ behavior: 'smooth' }), 300);
    }
    else out = [{ t: 'err', v: `comando no encontrado: ${cmd} — tipeá "help"` }];
    setLines(L => [...L, echo, ...out]);
    setInput('');
  };

  const onKey = (e) => {
    if (e.key === 'Enter') run(input);
  };

  return (
    <>
      <div className="term">
        {lines.map((l, i) => (
          <pre key={i} className={`line ${l.t}`} style={{margin:0, whiteSpace:'pre-wrap'}}>{l.v}</pre>
        ))}
      </div>
      <div className="term-input-row">
        <span className="prompt" style={{color: 'var(--emerald)', fontFamily: 'var(--font-mono)', fontSize: 12}}>angelo@uai:~$</span>
        <input ref={inputRef} value={input} onChange={e => setInput(e.target.value)} onKeyDown={onKey} placeholder="" autoFocus aria-label="Terminal input" />
      </div>
    </>
  );
}

function AngeloOS() {
  const { t } = window.useLang();
  const ref = window.useReveal();
  const [wins, setWins] = useStateOS([]); // { id, kind, name }
  const [topZ, setTopZ] = useStateOS(10);

  const openWin = useCallbackOS((kind, name) => {
    setWins(W => {
      const exists = W.find(w => w.kind === kind && w.name === name);
      if (exists) {
        // bring to front
        setTopZ(z => z + 1);
        return W.map(w => w === exists ? { ...w, z: topZ + 1 } : w);
      }
      setTopZ(z => z + 1);
      const offset = W.length * 28;
      return [...W, { id: Date.now() + Math.random(), kind, name, z: topZ + 1, pos: { x: 80 + offset, y: 60 + offset } }];
    });
  }, [topZ]);

  const closeWin = (id) => setWins(W => W.filter(w => w.id !== id));
  const focusWin = (id) => {
    setTopZ(z => z + 1);
    setWins(W => W.map(w => w.id === id ? { ...w, z: topZ + 1 } : w));
  };

  const icons = [
    ...FOLDER_ORDER.map(f => ({ glyph: '📂', label: f, action: () => openWin('folder', f) })),
    { glyph: '📄', label: 'README.txt', action: () => openWin('readme', 'README.txt') },
    { glyph: '📕', label: 'CV.pdf', action: () => {
      const a = document.createElement('a');
      a.href = 'cv.pdf';
      a.download = 'CV-Angelo-Perrotta.pdf';
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
      document.body.appendChild(a);
      a.click();
      a.remove();
    } },
    { glyph: '⌨️', label: 'Terminal', action: () => openWin('terminal', 'angelo@uai ~ /bin/bash') }
  ];

  return (
    <section id="os" ref={ref}>
      <div className="container">
        <div className="fade-up">
          <span className="kicker">{t.os.kicker}</span>
          <h2 className="section-title">{t.os.h2}</h2>
          <p className="section-sub">{t.os.sub}</p>
        </div>

        <div className="os-frame fade-up d1" style={{marginTop: 40}}>
          <div className="os-menubar">
            <span style={{fontSize: 14}}>🍎</span>
            <span className="os-logo">Angelo OS</span>
            <span>Archivo</span><span>Editar</span><span>Ver</span><span>Ventana</span><span>Ayuda</span>
            <span className="os-spacer" />
            <span className="os-meta">
              <span>📶</span><span>🔋 92%</span><Clock />
            </span>
          </div>

          {/* Desktop view */}
          <div className="os-desktop">
            <div className="os-icons">
              {icons.map((ic, i) => (
                <button key={i} className="os-icon" onClick={ic.action} onDoubleClick={ic.action} tabIndex={0}>
                  <span className="glyph">{ic.glyph}</span>
                  <span className="label">{ic.label}</span>
                </button>
              ))}
            </div>
            {wins.map(w => (
              <OSWindow
                key={w.id}
                kind={w.kind}
                name={w.name}
                z={w.z}
                initialPos={w.pos}
                onClose={() => closeWin(w.id)}
                onFocus={() => focusWin(w.id)}
              />
            ))}
          </div>

          {/* Mobile fallback */}
          <div className="os-mobile">
            {FOLDER_ORDER.map(f => (
              <details key={f}>
                <summary>📂 {f}</summary>
                {(window.OS_FS[f] || []).map((file, i) => (
                  <details key={i} style={{marginTop: 8, marginLeft: 12, background:'transparent', border:0, padding:'6px 0'}}>
                    <summary style={{fontSize: 12}}>📄 {file.name}</summary>
                    <pre>{file.body}</pre>
                  </details>
                ))}
              </details>
            ))}
            <details>
              <summary>📄 README.txt</summary>
              <pre>{window.OS_DESKTOP_FILES[0].body}</pre>
            </details>
            <details>
              <summary>📕 CV.pdf</summary>
              <pre>Descargá el CV completo · <a href="cv.pdf" download="CV-Angelo-Perrotta.pdf" target="_blank" rel="noopener noreferrer" style={{color:'var(--cyan)'}}>descargar PDF</a></pre>
            </details>
          </div>
        </div>
      </div>
    </section>
  );
}

window.AngeloOS = AngeloOS;
