// ─────── CHROME: tabline, winbar, tree, statusline, cmdline ───────

function Tabline({ buffers, active, onSelect, modified }) {
  return (
    <div className="tabline">
      {buffers.map((b, i) => (
        <div
          key={b.id}
          className={'tab ' + (b.id === active ? 'active' : '')}
          onClick={() => onSelect(b.id)}
        >
          <span className="tab-idx">{i + 1}</span>
          <span>{b.file}</span>
          {modified[b.id] && <span className="tab-dot">●</span>}
        </div>
      ))}
      <div className="tab-spacer" />
      <div className="tab-meta">
        <span>~/portfolio</span>
        <span style={{ color: 'var(--green)' }}>● main</span>
      </div>
    </div>
  );
}

function Winbar({ buffer }) {
  const crumbs = ['~', 'portfolio', buffer.file];
  return (
    <div className="winbar">
      {crumbs.map((c, i) => (
        <React.Fragment key={i}>
          <span className={'crumb' + (i === crumbs.length - 1 ? ' accent' : '')}>{c}</span>
          {i < crumbs.length - 1 && <span className="sep">›</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function FileTree({ buffers, active, onSelect, deps }) {
  const data = deps.data;
  return (
    <div className="tree">
      <div className="tree-header">NETRW — ~/portfolio</div>

      <div className="tree-group">── buffers ──</div>
      {buffers.map((b) => (
        <div
          key={b.id}
          className={'tree-item' + (b.id === active ? ' active' : '')}
          onClick={() => onSelect(b.id)}
        >
          <span className="glyph">▸</span>
          <span>{b.file}</span>
          <span className="key">{b.key}</span>
        </div>
      ))}

      <div className="tree-group">── links ──</div>
      <a className="tree-item" href={`https://${data.github}`} target="_blank" rel="noreferrer">
        <span className="glyph">↗</span>
        <span>github</span>
      </a>
      <a className="tree-item" href={`https://${data.linkedin}`} target="_blank" rel="noreferrer">
        <span className="glyph">↗</span>
        <span>linkedin</span>
      </a>
      <a className="tree-item" href={`mailto:${data.email}`}>
        <span className="glyph">↗</span>
        <span>email</span>
      </a>

      <div className="tree-group">── shortcuts ──</div>
      <div className="tree-item" style={{ cursor: 'default' }}>
        <span className="glyph"></span>
        <span>press</span>
        <span className="key">?</span>
      </div>
      <div className="tree-item" style={{ cursor: 'default' }}>
        <span className="glyph"></span>
        <span>open cmd</span>
        <span className="key">:</span>
      </div>
      <div className="tree-item" style={{ cursor: 'default' }}>
        <span className="glyph"></span>
        <span>search</span>
        <span className="key">/</span>
      </div>
    </div>
  );
}

function Statusline({ mode, buffer, line, total, search }) {
  const modeLabel =
    {
      NORMAL: 'NORMAL',
      INSERT: 'INSERT',
      VISUAL: 'VISUAL',
      COMMAND: 'COMMAND',
      SEARCH: 'SEARCH',
    }[mode] || 'NORMAL';
  const modeColor = {
    NORMAL: 'var(--blue)',
    INSERT: 'var(--green)',
    VISUAL: 'var(--purple)',
    COMMAND: 'var(--yellow)',
    SEARCH: 'var(--orange)',
  }[mode];
  const pct = total > 0 ? Math.round((line / total) * 100) : 0;
  return (
    <div className="statusline">
      <div className="sl-mode" style={{ background: modeColor }}>
        {modeLabel}
      </div>
      <div className="sl-seg git"> main</div>
      <div className="sl-seg">{buffer.file}</div>
      {search && <div className="sl-seg diag">/{search}</div>}
      <div className="sl-spacer" />
      <div className="sl-right">
        <span>{line},1</span>
        <span className="sep">│</span>
        <span>{pct}%</span>
      </div>
    </div>
  );
}

function Cmdline({ mode, cmd, setCmd, onSubmit, onCancel, hint, completions = [] }) {
  const inputRef = React.useRef(null);
  const [wildItems, setWildItems] = React.useState([]);
  const compList = React.useRef([]);
  const compIdx = React.useRef(-1);

  function resetComp() {
    compList.current = [];
    compIdx.current = -1;
    setWildItems([]);
  }

  React.useEffect(() => {
    if ((mode === 'COMMAND' || mode === 'SEARCH') && inputRef.current) {
      inputRef.current.focus();
    }
    resetComp();
  }, [mode]);

  if (mode === 'COMMAND' || mode === 'SEARCH') {
    const prefix = mode === 'COMMAND' ? ':' : '/';
    return (
      <div className="cmdline active">
        {wildItems.length > 0 && (
          <div className="cmd-wildmenu">
            {wildItems.map((item, i) => (
              <span
                key={item}
                className={'cmd-wm-item' + (i === compIdx.current ? ' on' : '')}
              >
                {item}
              </span>
            ))}
          </div>
        )}
        <span className="prefix">{prefix}</span>
        <input
          ref={inputRef}
          value={cmd}
          onChange={(e) => {
            resetComp();
            setCmd(e.target.value);
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              resetComp();
              onSubmit();
            } else if (e.key === 'Escape') {
              e.preventDefault();
              resetComp();
              onCancel();
            } else if (e.key === 'Tab' && mode === 'COMMAND') {
              e.preventDefault();
              let list = compList.current;
              if (!list.length) {
                const base = cmd.trim().toLowerCase();
                list = completions.filter((c) => c.startsWith(base));
                if (!list.length) return;
                compList.current = list;
              }
              const dir = e.shiftKey ? -1 : 1;
              const len = list.length;
              compIdx.current = ((compIdx.current + dir) % len + len) % len;
              setCmd(list[compIdx.current]);
              setWildItems([...list]);
            }
          }}
          placeholder={mode === 'COMMAND' ? 'command — Tab to complete' : 'search buffer…'}
        />
      </div>
    );
  }

  return (
    <div className="cmdline">
      <span className="hint">
        {hint ||
          '-- press ? for which-key, : for command, / to search, hjkl to move, gg/G to jump --'}
      </span>
    </div>
  );
}

function Splash() {
  const ascii = `   ▄▄▄       ▄▄▄·  ▄• ▄▌
   ▀▄ █·    ▐█ ▀█ █▪██▌
   ▐▀▀▄ ██▌ ▐█▀▀█ █▌▐█▌
   ▐█•█▌███▪▐█ ▪▐▌▐█▄█▌
   .▀  ▀·▀▀·  ▀  ▀  ▀▀▀
   love.sahaj - portfolio v26.04`;
  return (
    <div className="splash">
      <div className="splash-inner">
        <div className="logo">{ascii}</div>
        <div className="ver">a portfolio by Love Sahajbir Singh</div>
        <div className="tip">
          press <kbd>?</kbd> any time to learn the keys
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Tabline, Winbar, FileTree, Statusline, Cmdline, Splash });
