// ContextSidebar — the create-flow context panel (toggled by the composer's
// "+ Context"). Sits between the canvas and the chat. Two jobs:
//   • visualize every piece of context added so far (uploads, linked folders,
//     web links) — derived by the page from `attachment` events;
//   • add more: file uploads, an absolute folder path, or a web link.
// Pure renderer: all three add affordances are callbacks the PAGE implements
// (it owns fetch + the shared `attaching` flag). Mirrors ChatPanel's tier.
//
// Props:
//   items         — [{ label, files, bytes, source }] (source: upload|folder|link)
//   attaching     — true while any attach call is in flight (disables the adds)
//   onAttachFiles — (FileList) => void
//   onLinkFolder  — (path) => void
//   onAddLink     — (url) => void
//   onClose       — () => void

const CTX_ICON = { upload: '📄', folder: '📁', link: '🔗' };

const ContextSidebar = ({ items = [], attaching = false, onAttachFiles, onLinkFolder, onAddLink, onClose }) => {
  const fileInputRef = React.useRef(null);
  const [folderPath, setFolderPath] = React.useState('');
  const [linkUrl, setLinkUrl] = React.useState('');

  const onFilesChosen = (e) => {
    const files = e.target.files;
    if (files && files.length) onAttachFiles?.(files);
    e.target.value = '';
  };
  const submitFolder = () => {
    const p = folderPath.trim();
    if (!p || attaching) return;
    onLinkFolder?.(p);
    setFolderPath('');
  };
  const submitLink = () => {
    const u = linkUrl.trim();
    if (!u || attaching) return;
    onAddLink?.(u);
    setLinkUrl('');
  };

  return (
    <div className="h-full min-h-0 flex flex-col bg-white">
      <div className="px-3 py-3 border-b border-neutral-200 flex items-center justify-between gap-2">
        <span className="text-xs font-bold uppercase tracking-widest text-neutral-500">Context</span>
        <button type="button" onClick={() => onClose?.()} className="text-neutral-400 hover:text-neutral-700 font-semibold" aria-label="Close context panel">✕</button>
      </div>

      <div className="p-3 space-y-2 border-b border-neutral-200">
        <input ref={fileInputRef} type="file" multiple onChange={onFilesChosen} className="hidden" />
        <button
          type="button"
          disabled={attaching}
          onClick={() => fileInputRef.current?.click()}
          className="w-full px-3 py-2 text-xs font-semibold rounded-lg border border-neutral-200 text-neutral-700 hover:bg-neutral-50 disabled:opacity-40 text-left"
        >📄 Add files…</button>
        <div className="flex gap-1.5">
          <input
            type="text" value={folderPath} disabled={attaching}
            onChange={(e) => setFolderPath(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); submitFolder(); } }}
            placeholder="/absolute/folder/path"
            className="flex-1 min-w-0 font-mono text-[11px] px-2 py-1.5 rounded-md border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-neutral-300 disabled:bg-neutral-50"
          />
          <button type="button" disabled={attaching || !folderPath.trim()} onClick={submitFolder}
            className="px-2.5 py-1.5 text-xs font-semibold rounded-md bg-neutral-800 text-white hover:bg-neutral-900 disabled:opacity-40">Add</button>
        </div>
        <div className="flex gap-1.5">
          <input
            type="text" value={linkUrl} disabled={attaching}
            onChange={(e) => setLinkUrl(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); submitLink(); } }}
            placeholder="https://…"
            className="flex-1 min-w-0 text-[11px] px-2 py-1.5 rounded-md border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-neutral-300 disabled:bg-neutral-50"
          />
          <button type="button" disabled={attaching || !linkUrl.trim()} onClick={submitLink}
            className="px-2.5 py-1.5 text-xs font-semibold rounded-md bg-neutral-800 text-white hover:bg-neutral-900 disabled:opacity-40">Add</button>
        </div>
      </div>

      <div className="flex-1 min-h-0 overflow-y-auto p-3 space-y-1.5">
        {items.length === 0 ? (
          <div className="text-xs text-neutral-400 text-center py-6 px-2">
            No context yet. Files, folders and links you add here are shared with the interviewer and planner.
          </div>
        ) : items.map((it, i) => (
          <div key={i} className="flex items-start gap-2 rounded-lg border border-neutral-200 bg-neutral-50 px-2.5 py-2">
            <span aria-hidden>{CTX_ICON[it.source] || '📎'}</span>
            <div className="min-w-0">
              <div className="text-xs font-semibold text-neutral-700 break-all">{it.label}</div>
              {it.source !== 'link' && (
                <div className="text-[10px] text-neutral-400">{it.files} file(s) · {window.ChatEvents.formatBytes(it.bytes)}</div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

if (typeof window !== 'undefined') {
  window.ContextSidebar = ContextSidebar;
}
