"use client";

import { useChatStore } from "@/lib/store";
import { ConversationItem } from "./conversation-item";
import { PersonSwitcher } from "./person-switcher";

interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

export function Sidebar({ isOpen, onClose }: SidebarProps) {
  const conversations = useChatStore((s) => s.conversations);
  const activeId = useChatStore((s) => s.activeConversationId);
  const createConversation = useChatStore((s) => s.createConversation);
  const switchConversation = useChatStore((s) => s.switchConversation);

  const sorted = [...conversations].sort(
    (a, b) => b.lastMessageAt - a.lastMessageAt
  );

  const handleNew = () => {
    createConversation();
    onClose();
  };

  const handleSwitch = (id: string) => {
    switchConversation(id);
    onClose();
  };

  return (
    <>
      {/* Backdrop on mobile */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/40 z-30 md:hidden"
          onClick={onClose}
        />
      )}

      <aside
        className={`fixed md:static inset-y-0 left-0 z-40 w-64 bg-bg-surface border-r border-border flex flex-col transition-transform duration-200 ${
          isOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
        }`}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-border">
          <span className="text-text-muted text-xs font-medium tracking-wide uppercase">
            aeries
          </span>
          <button
            onClick={handleNew}
            className="text-text-muted hover:text-text text-sm transition-colors px-2 py-1 rounded hover:bg-bg-hover"
          >
            + new
          </button>
        </div>

        {/* Person identity */}
        <PersonSwitcher />

        {/* Conversation list */}
        <div className="flex-1 overflow-y-auto px-2 py-2 space-y-0.5">
          {sorted.length === 0 && (
            <p className="text-text-faint text-xs px-3 py-4 text-center">
              no conversations yet
            </p>
          )}
          {sorted.map((conv) => (
            <ConversationItem
              key={conv.id}
              conversation={conv}
              isActive={conv.id === activeId}
              onClick={() => handleSwitch(conv.id)}
            />
          ))}
        </div>
      </aside>
    </>
  );
}
