// portfolio/overlays.jsx — Terminal + CmdPalette

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

// ── Command processor ─────────────────────────────────────────────────────
function runCommand(raw, navigate, onClose) {
  const P = window.PORTFOLIO;
  const parts = raw.trim().split(/\s+/);
  const cmd = parts[0].toLowerCase();
  const args = parts.slice(1);

  const out = (text, type = 'out') => ({ text, type });
  const hdr = (text) => ({ text, type: 'hdr' });
  const err = (text) => ({ text, type: 'err' });
  const art = (text) => ({ text, type: 'art' });

  switch (cmd) {
    case 'help': case '?':
      return [
        hdr('Information:'),
        out('  whoami              Display user info'),
        out('  ls [projects|posts] List content'),
        out('  cat <file>          Read a file  (about.txt · skills.txt · now.txt)'),
        out('  neofetch            Display system info'),
        out('  date                Current date and time'),
        hdr('Navigation:'),
        out('  home | about | projects | blog | contact | gallery | now'),
        hdr('Social:'),
        out('  github    Open GitHub profile'),
        out('  linkedin  Open LinkedIn profile'),
        out('  twitter   Open Twitter / X profile'),
        out('  email     Copy email to clipboard'),
        hdr('Utility:'),
        out('  clear     Clear terminal   (or Ctrl+L)'),
        out('  exit      Close terminal   (or Esc)'),
      ];

    case 'whoami':
      return [
        out(`Name:     Chibuzor Adigwe`),
        out(`Handle:   iamphantasm0`),
        out(`Role:     ${P.role}`),
        out(`Location: ${P.location}`),
        out(`Stack:    Python · FastAPI · PostgreSQL · Docker · Redis`),
        out(`GitHub:   ${P.social.github.replace('https://', '')}`),
        out(`Status:   ${P.available ? 'Available for backend engineering opportunities' : 'Currently unavailable'}`),
      ];

    case 'ls': {
      const sub = args[0];
      if (sub === 'projects') {
        return P.projects.map(p =>
          out(`  ${p.id.padEnd(22)} ${p.year.padEnd(12)} [${p.status}]`)
        );
      }
      if (sub === 'posts') {
        return P.posts.map(p =>
          out(`  ${p.id.padEnd(30)} ${p.date}`)
        );
      }
      return [out('about.txt    skills.txt   now.txt      projects/    posts/')];
    }

    case 'cat': {
      const file = args[0];
      if (!file) return [err('Usage: cat <filename>')];
      if (file === 'about.txt') return [
        out('Backend engineer with 4+ years building production REST APIs'),
        out('using FastAPI and PostgreSQL. Experienced in startup environments'),
        out('designing scalable systems, database schemas, and integrations.'),
        out(''),
        out('Strong foundation in Linux infrastructure, Docker, and automation.'),
        out('Comfortable working in remote teams using Git-based workflows.'),
      ];
      if (file === 'skills.txt') {
        return P.skills.flatMap(s => [
          hdr(s.cat.toUpperCase()),
          out(`  ${s.items.join('  ·  ')}`),
        ]);
      }
      if (file === 'now.txt') return [
        out(`Focus:    ${P.now.focus}`),
        out(`Reading:  ${P.now.reading}`),
        out(`Building: ${P.now.building.join(', ')}`),
        out(`Updated:  ${P.now.updated}`),
      ];
      return [err(`cat: ${file}: No such file or directory`)];
    }

    case 'neofetch':
      return [
        art('  ██████╗    iamphantasm0@portfolio'),
        art(' ██╔════╝    ─────────────────────────────────'),
        art(' ██║  ███╗   OS:       Portfolio OS v2025'),
        art(' ██║   ██║   Role:     Backend Engineer'),
        art(' ╚██████╔╝   Location: Lagos, Nigeria'),
        art('  ╚═════╝    Stack:    Python · FastAPI · PostgreSQL'),
        art('             Tools:    Docker · Redis · Linux · Bash'),
        art('             GitHub:   iamphantasm0'),
        art(`             Status:   ${P.available ? 'Available' : 'Busy'}`),
        art('             Uptime:   4+ years production experience'),
      ];

    case 'date':
      return [out(new Date().toLocaleString('en-GB', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', timeZoneName: 'short' }))];

    case 'contact':
      return [
        out(`Email:    ${P.email}`),
        out(`GitHub:   ${P.social.github}`),
        out(`LinkedIn: ${P.social.linkedin}`),
        out(`Twitter:  ${P.social.twitter}`),
      ];

    case 'github': case 'gh':
      window.open(P.social.github, '_blank');
      return [out('Opening GitHub…')];

    case 'linkedin': case 'li':
      window.open(P.social.linkedin, '_blank');
      return [out('Opening LinkedIn…')];

    case 'twitter': case 'tw':
      window.open(P.social.twitter, '_blank');
      return [out('Opening Twitter / X…')];

    case 'email':
      navigator.clipboard.writeText(P.email).catch(() => {});
      return [out(`Copied to clipboard: ${P.email}`)];

    // Quick nav
    case 'home':     navigate('/');          return [out('Navigating…')];
    case 'about':    navigate('/about');     return [out('Navigating…')];
    case 'projects': navigate('/projects');  return [out('Navigating…')];
    case 'blog':     navigate('/blog');      return [out('Navigating…')];
    case 'contact':  navigate('/contact');   return [out('Navigating…')];
    case 'gallery':  navigate('/gallery');   return [out('Navigating…')];
    case 'now':      navigate('/now');       return [out('Navigating…')];

    case 'clear': return [{ type: 'CLEAR' }];
    case 'exit':  return [{ type: 'EXIT' }];
    case '':      return [];

    default:
      return [err(`Command not found: ${cmd}  —  type 'help' for available commands`)];
  }
}

// ── Terminal ──────────────────────────────────────────────────────────────
const WELCOME = [
  { text: 'iamphantasm0\'s portfolio terminal — type \'help\' to see commands', type: 'dim' },
  { text: '', type: 'out' },
];

const PROMPT = 'iamphantasm0@portfolio:~$';

function Terminal({ onClose, navigate }) {
  const [lines, setLines]   = useState(WELCOME);
  const [input, setInput]   = useState('');
  const [hist,  setHist]    = useState([]);
  const [histI, setHistI]   = useState(-1);
  const outputRef = useRef(null);
  const inputRef  = useRef(null);

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

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

  const submit = useCallback(() => {
    if (!input.trim() && input === '') return;
    const cmd = input.trim();
    const promptLine = { text: `${PROMPT} ${cmd}`, type: 'prompt' };
    const result = runCommand(cmd, navigate, onClose);

    if (result[0]?.type === 'CLEAR') { setLines(WELCOME); setInput(''); return; }
    if (result[0]?.type === 'EXIT')  { onClose(); return; }

    setLines(prev => [...prev, promptLine, ...result]);
    if (cmd) setHist(prev => [cmd, ...prev]);
    setHistI(-1);
    setInput('');
  }, [input, navigate, onClose]);

  const onKey = (e) => {
    if (e.key === 'Enter') { submit(); return; }
    if (e.key === 'ArrowUp') {
      e.preventDefault();
      const next = Math.min(histI + 1, hist.length - 1);
      setHistI(next);
      setInput(hist[next] ?? '');
    }
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      const next = Math.max(histI - 1, -1);
      setHistI(next);
      setInput(next === -1 ? '' : (hist[next] ?? ''));
    }
    if (e.key === 'l' && e.ctrlKey) {
      e.preventDefault();
      setLines(WELCOME);
    }
  };

  const lineColor = { out: '#ece9e4', hdr: '#888', err: '#c97', dim: '#444', art: '#6a8', prompt: '#666' };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.82)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9000, animation: 'fadeIn 0.15s ease',
    }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        width: '760px', maxWidth: '92vw', height: '480px',
        background: '#0e0e0e', border: '1px solid #262626',
        borderRadius: '10px', display: 'flex', flexDirection: 'column',
        overflow: 'hidden', boxShadow: '0 24px 80px rgba(0,0,0,0.7)',
        animation: 'fadeUp 0.2s ease',
      }}>
        {/* Chrome */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: '7px',
          padding: '11px 14px', background: '#131313',
          borderBottom: '1px solid #1e1e1e', flexShrink: 0,
        }}>
          <div onClick={onClose} style={{ width: '11px', height: '11px', borderRadius: '50%', background: '#ff5f57', cursor: 'pointer' }} />
          <div style={{ width: '11px', height: '11px', borderRadius: '50%', background: '#febc2e' }} />
          <div style={{ width: '11px', height: '11px', borderRadius: '50%', background: '#28c840' }} />
          <span style={{
            fontFamily: "'JetBrains Mono', monospace", fontSize: '11px',
            color: '#3a3a3a', marginLeft: '8px', letterSpacing: '0.02em',
          }}>{PROMPT}</span>
        </div>

        {/* Output */}
        <div ref={outputRef} style={{
          flex: 1, overflowY: 'auto', padding: '16px 20px',
          fontFamily: "'JetBrains Mono', monospace", fontSize: '12px',
          lineHeight: 1.7, display: 'flex', flexDirection: 'column', gap: '1px',
        }}>
          {lines.map((ln, i) => (
            <div key={i} style={{ color: lineColor[ln.type] ?? '#ece9e4', whiteSpace: 'pre' }}>
              {ln.text}
            </div>
          ))}
        </div>

        {/* Input row */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: '8px',
          padding: '10px 20px', borderTop: '1px solid #1a1a1a', flexShrink: 0,
        }}>
          <span style={{
            fontFamily: "'JetBrains Mono', monospace", fontSize: '12px',
            color: '#4a9', whiteSpace: 'nowrap',
          }}>{PROMPT}</span>
          <input
            ref={inputRef}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={onKey}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              fontFamily: "'JetBrains Mono', monospace", fontSize: '12px',
              color: '#ece9e4', caretColor: '#ece9e4',
            }}
            placeholder=""
            spellCheck={false}
            autoComplete="off"
          />
        </div>
      </div>
    </div>
  );
}

// ── CmdPalette ────────────────────────────────────────────────────────────
const CMD_ACTIONS = (navigate, close) => [
  { label: 'Home',         cat: 'Navigate', fn: () => { navigate('/');         close(); } },
  { label: 'About',        cat: 'Navigate', fn: () => { navigate('/about');    close(); } },
  { label: 'Projects',     cat: 'Navigate', fn: () => { navigate('/projects'); close(); } },
  { label: 'Blog',         cat: 'Navigate', fn: () => { navigate('/blog');     close(); } },
  { label: 'Contact',      cat: 'Navigate', fn: () => { navigate('/contact');  close(); } },
  { label: 'Gallery',      cat: 'Navigate', fn: () => { navigate('/gallery');  close(); } },
  { label: '/now',         cat: 'Navigate', fn: () => { navigate('/now');      close(); } },
  { label: 'Copy email',   cat: 'Contact',  fn: () => { navigator.clipboard.writeText(window.PORTFOLIO.email).catch(() => {}); close(); } },
  { label: 'Open GitHub',  cat: 'Social',   fn: () => { window.open(window.PORTFOLIO.social.github,   '_blank'); close(); } },
  { label: 'Open LinkedIn',cat: 'Social',   fn: () => { window.open(window.PORTFOLIO.social.linkedin, '_blank'); close(); } },
  { label: 'Open Twitter', cat: 'Social',   fn: () => { window.open(window.PORTFOLIO.social.twitter,  '_blank'); close(); } },
];

function CmdPalette({ onClose, navigate }) {
  const [query, setQuery]    = useState('');
  const [selIdx, setSelIdx]  = useState(0);
  const inputRef = useRef(null);
  const actions  = CMD_ACTIONS(navigate, onClose);

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

  const filtered = query
    ? actions.filter(a => a.label.toLowerCase().includes(query.toLowerCase()) || a.cat.toLowerCase().includes(query.toLowerCase()))
    : actions;

  const execute = (idx) => { filtered[idx]?.fn(); };

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSelIdx(i => Math.min(i + 1, filtered.length - 1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setSelIdx(i => Math.max(i - 1, 0)); }
    if (e.key === 'Enter')     { execute(selIdx); }
    if (e.key === 'Escape')    { onClose(); }
  };

  useEffect(() => { setSelIdx(0); }, [query]);

  const catColors = { Navigate: '#555', Contact: '#7a8', Social: '#78a' };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      paddingTop: '18vh', zIndex: 9000, animation: 'fadeIn 0.12s ease',
    }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        width: '520px', maxWidth: '90vw',
        background: '#141414', border: '1px solid #282828',
        borderRadius: '10px', overflow: 'hidden',
        boxShadow: '0 20px 60px rgba(0,0,0,0.6)',
        animation: 'fadeUp 0.15s ease',
      }}>
        {/* Input */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: '10px',
          padding: '12px 16px', borderBottom: '1px solid #1e1e1e',
        }}>
          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: '13px', color: '#3a3a3a' }}>⌘K</span>
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={onKey}
            placeholder="Type a command or search…"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              fontFamily: "'DM Sans', system-ui, sans-serif", fontSize: '14px',
              color: '#ece9e4',
            }}
          />
          {query && (
            <button onClick={() => setQuery('')} style={{
              background: 'none', border: 'none', color: '#444', fontSize: '12px', cursor: 'pointer',
            }}>✕</button>
          )}
        </div>

        {/* Results */}
        <div style={{ maxHeight: '320px', overflowY: 'auto' }}>
          {filtered.length === 0 ? (
            <div style={{ padding: '20px 16px', fontFamily: "'DM Sans', system-ui, sans-serif", fontSize: '13px', color: '#444', textAlign: 'center' }}>
              No results
            </div>
          ) : filtered.map((action, i) => (
            <div key={i} onClick={() => execute(i)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '10px 16px', cursor: 'pointer',
                background: i === selIdx ? '#1c1c1c' : 'transparent',
                transition: 'background .1s',
              }}
              onMouseEnter={() => setSelIdx(i)}>
              <span style={{ fontFamily: "'DM Sans', system-ui, sans-serif", fontSize: '13px', color: '#ece9e4' }}>
                {action.label}
              </span>
              <span style={{
                fontFamily: "'JetBrains Mono', monospace", fontSize: '10px',
                color: catColors[action.cat] ?? '#555', letterSpacing: '0.04em',
              }}>
                {action.cat}
              </span>
            </div>
          ))}
        </div>

        {/* Footer hint */}
        <div style={{
          padding: '8px 16px', borderTop: '1px solid #1a1a1a',
          display: 'flex', gap: '16px',
        }}>
          {[['↵', 'select'], ['↑↓', 'navigate'], ['esc', 'close']].map(([k, v]) => (
            <span key={k} style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: '10px', color: '#3a3a3a' }}>
              <span style={{ color: '#555' }}>{k}</span> {v}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Terminal, CmdPalette });
