// [nexus] History slide-over sheet for the Assistant (Phase 9).
//
// Left-side slide-over that butts against the 56px icon rail. Wraps the
// existing ChatConversationList so we preserve the conversation model
// without reimplementing search, pinning, or create/rename.
import { useEffect } from "react";
import { X } from "lucide-react";
import { ChatConversationList } from "../ChatConversationList";
import { cn } from "@/lib/utils";

export interface HistorySheetProps {
  open: boolean;
  onClose: () => void;
  companyId: string | null;
  className?: string;
}

export function HistorySheet({ open, onClose, companyId, className }: HistorySheetProps) {
  // ESC closes the sheet.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.stopPropagation();
        onClose();
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <>
      {/* Backdrop — click to dismiss */}
      <button
        type="button"
        onClick={onClose}
        aria-label="Close history"
        data-testid="history-sheet-backdrop"
        className="fixed inset-0 z-40 bg-black/40"
      />
      {/* Panel */}
      <aside
        role="dialog"
        aria-modal="true"
        aria-label="Conversation history"
        data-testid="history-sheet-panel"
        className={cn(
          "fixed top-12 bottom-0 left-[56px] z-50 w-[320px] flex flex-col",
          "border-r border-border bg-background",
          className,
        )}
      >
        <header className="flex items-center justify-between px-4 py-3 border-b border-border">
          <h2 className="text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground">
            History
          </h2>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close history"
            className={cn(
              "flex h-7 w-7 items-center justify-center rounded-[4px] text-muted-foreground hover:text-primary",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background",
            )}
          >
            <X className="h-4 w-4" />
          </button>
        </header>
        <div className="flex-1 min-h-0 overflow-hidden">
          {companyId ? (
            <ChatConversationList companyId={companyId} />
          ) : (
            <p className="px-4 py-6 text-xs text-muted-foreground">
              Select a workspace to view conversations.
            </p>
          )}
        </div>
      </aside>
    </>
  );
}
