// Terminal — accepts commands

function Terminal({ collapsed, onToggle, onOpenFile }) {
  const [lines, setLines] = useState(() => initialBanner());
  const [input, setInput] = useState('');
  const [history, setHistory] = useState([]);
  const [histIdx, setHistIdx] = useState(-1);
  const bodyRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [lines]);

  useEffect(() => {
    if (!collapsed && inputRef.current) inputRef.current.focus();
  }, [collapsed]);

  function initialBanner() {
    const D = window.PORTFOLIO_DATA;
    return [
      { t: 'out', text: `leyder@portfolio:~$ neofetch --short` },
      { t: 'raw', text: neofetch() },
      { t: 'muted', text: `Type "help" to see available commands.` },
      { t: 'muted', text: `` },
    ];
  }

  function neofetch() {
    const D = window.PORTFOLIO_DATA;
    const ascii = [
      '  ╔══════════╗  ',
      '  ║  ◢█◣     ║  ',
      '  ║  █ █  ◤◥ ║  ',
      '  ║   ◥ ◣◢█  ║  ',
      '  ║      ◥◤  ║  ',
      '  ╚══════════╝  ',
    ];
    const info = [
      `${D.profile.name}`,
      `${'─'.repeat(22)}`,
      `OS: Portfolio v3.0`,
      `Role: ${D.profile.role}`,
      `Uptime: ${D.profile.experienceYears} years`,
      `Location: ${D.profile.location}`,
      `Shell: zsh 5.9`,
      `Stack: java, ts, python, postgres`,
      `Open to work: true`,
    ];
    let out = '';
    const rows = Math.max(ascii.length, info.length);
    for (let i = 0; i < rows; i++) {
      const a = ascii[i] || ' '.repeat(16);
      const b = info[i] || '';
      out += `<span class="term-arrow">${a}</span>  <span class="term-out">${b}</span>\n`;
    }
    return out;
  }

  function print(t, text) {
    setLines(prev => [...prev, { t, text }]);
  }

  function runCommand(raw) {
    const D = window.PORTFOLIO_DATA;
    const cmd = raw.trim();
    setLines(prev => [...prev, { t: 'prompt', cmd }]);
    if (!cmd) return;
    setHistory(h => [...h, cmd]);
    setHistIdx(-1);

    const [name, ...args] = cmd.split(/\s+/);

    switch (name) {
      case 'help':
        print('out',
`Available commands:
  help            Show this help
  whoami          Who is Leyder?
  ls [path]       List files
  cat <file>      Display file (try: cat about.md, cat skills.json)
  open <file>     Open a file in the editor (e.g., open experience.md)
  projects        List all projects
  experience      Show work history
  skills          Show technical skills
  contact         Contact info
  social          Social links
  neofetch        System-style portfolio card
  echo <text>     Echo input
  date            Current date
  clear           Clear terminal
  sudo hire-me    ;)
  cv              Download my resume (PDF)`);
        break;
      case 'whoami':
        print('out', `${D.profile.name} — ${D.profile.role}`);
        break;
      case 'ls': {
        const p = args[0] || '/';
        const node = p === '/' || p === '.' ? window.FS.profile : window.resolveFS(p);
        if (!node || !node.children) { print('err', `ls: ${p}: No such directory`); break; }
        const entries = Object.entries(node.children).map(([k, v]) =>
          v.type === 'folder' ? `<span class="tok-fn">${k}/</span>` : k
        );
        print('raw', entries.join('   '));
        break;
      }
      case 'cat': {
        if (!args[0]) { print('err', 'cat: missing file'); break; }
        let path = args[0].startsWith('/') ? args[0] : '/' + args[0];
        const node = window.resolveFS(path);
        if (!node || node.type !== 'file') { print('err', `cat: ${args[0]}: No such file`); break; }
        const content = node.render();
        print('raw', `<pre style="white-space:pre-wrap;margin:0">${content.replace(/</g,'&lt;')}</pre>`);
        break;
      }
      case 'open': {
        if (!args[0]) { print('err', 'open: missing file'); break; }
        let path = args[0].startsWith('/') ? args[0] : '/' + args[0];
        const node = window.resolveFS(path);
        if (!node) { print('err', `open: ${args[0]}: No such file`); break; }
        onOpenFile(path);
        print('muted', `Opened ${path} in editor`);
        break;
      }
      case 'projects':
        print('raw', D.projects.map(p =>
          `<span class="tok-fn">${p.slug}/</span>  <span class="term-muted">${p.tagline}</span>`
        ).join('\n'));
        break;
      case 'experience':
        print('raw', D.experience.map(e =>
          `<span class="term-arrow">▸</span> <span class="tok-kw">${e.role}</span> @ ${e.company}\n  <span class="term-muted">${e.period}</span>`
        ).join('\n\n'));
        break;
      case 'skills': {
        const s = D.skills;
        const groups = [
          ['languages', s.languages],
          ['backend',   s.backend],
          ['frontend',  s.frontend],
          ['databases', s.databases],
          ['tools',     s.tools],
        ];
        print('raw', groups.map(([k, arr]) =>
          `<span class="tok-var">${k.padEnd(10)}</span>: <span class="tok-str">${arr.join(', ')}</span>`
        ).join('\n'));
        break;
      }
      case 'contact':
        print('raw',
`<span class="tok-var">email</span>    → <span class="tok-link" data-link="mailto:${D.profile.email}">${D.profile.email}</span>
<span class="tok-var">phone</span>    → ${D.profile.phone}
<span class="tok-var">location</span> → ${D.profile.location}`);
        break;
      case 'social':
        print('raw',
`<span class="tok-var">github</span>   → <a href="${D.profile.social.github}" target="_blank">${D.profile.social.github}</a>
<span class="tok-var">linkedin</span> → <a href="${D.profile.social.linkedin}" target="_blank">${D.profile.social.linkedin}</a>
<span class="tok-var">email</span>    → <a href="mailto:${D.profile.email}">${D.profile.email}</a>`);
        break;
      case 'neofetch':
        print('raw', neofetch());
        break;
      case 'echo':
        print('out', args.join(' '));
        break;
      case 'date':
        print('out', new Date().toString());
        break;
      case 'clear':
      case 'cls':
        setLines([]);
        break;
      case 'cv': {
        const link = document.createElement('a');
        link.href = 'uploads/Leyder_Herrera_CV.pdf';
        link.download = 'LeyderCV.pdf';
        link.click();
        print('out', 'Downloading CV...');
        break;
      }
      case 'sudo':
        if (args.join(' ') === 'hire-me') {
          print('raw', `<span class="tok-str">[sudo] password for leyder:</span> ****
<span class="term-arrow">✓</span> Permission granted.
Send an email to <a href="mailto:${D.profile.email}">${D.profile.email}</a> — I'll get back within 24h.`);
        } else {
          print('err', `sudo: ${args.join(' ')}: command not found. Try: sudo hire-me`);
        }
        break;
      case 'exit':
        onToggle(true);
        break;
      default:
        print('err', `zsh: command not found: ${name}. Type "help".`);
    }
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      runCommand(input);
      setInput('');
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      const next = histIdx < 0 ? history.length - 1 : Math.max(0, histIdx - 1);
      if (history[next] !== undefined) { setHistIdx(next); setInput(history[next]); }
    } else if (e.key === 'ArrowDown') {
      e.preventDefault();
      if (histIdx < 0) return;
      const next = histIdx + 1;
      if (next >= history.length) { setHistIdx(-1); setInput(''); }
      else { setHistIdx(next); setInput(history[next]); }
    } else if (e.key === 'l' && e.ctrlKey) {
      e.preventDefault();
      setLines([]);
    }
  };

  return (
    <div className={`terminal ${collapsed ? 'collapsed' : ''}`}>
      <div className="terminal-header">
        <span className="tab-t active">Terminal</span>
        <span className="tab-t">Problems</span>
        <span className="tab-t">Output</span>
        <span className="tab-t">Debug Console</span>
        <span className="spacer" />
        <button className="icon-btn" onClick={() => onToggle(!collapsed)} title="Toggle Terminal">
          {collapsed ? '▲' : '▼'}
        </button>
      </div>
      {!collapsed && (
        <div className="terminal-body" ref={bodyRef} onClick={() => inputRef.current && inputRef.current.focus()}>
          {lines.map((l, i) => {
            if (l.t === 'prompt') {
              return (
                <div key={i} className="term-line">
                  <span className="term-prompt">leyder@portfolio</span>
                  <span className="term-muted">:</span>
                  <span className="term-path">~</span>
                  <span className="term-muted">$ </span>
                  <span>{l.cmd}</span>
                </div>
              );
            }
            if (l.t === 'raw') {
              return <div key={i} className="term-line" dangerouslySetInnerHTML={{ __html: l.text }} />;
            }
            return <div key={i} className={`term-line term-${l.t}`}>{l.text}</div>;
          })}
          <div className="term-line term-input-line">
            <span className="term-prompt">leyder@portfolio</span>
            <span className="term-muted">:</span>
            <span className="term-path">~</span>
            <span className="term-muted">$&nbsp;</span>
            <input
              ref={inputRef}
              className="term-input"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              autoFocus
              spellCheck={false}
            />
          </div>
        </div>
      )}
    </div>
  );
}

window.Terminal = Terminal;
