"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

interface CollapsibleContextType {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}
const CollapsibleContext = React.createContext<CollapsibleContextType | null>(null);

function Collapsible({ open, onOpenChange, className, children, ...props }: React.ComponentProps<"div"> & CollapsibleContextType) {
  return (
    <CollapsibleContext.Provider value={{ open, onOpenChange }}>
      <div data-slot="collapsible" className={cn("flex flex-col gap-2", className)} {...props}>
        {children}
      </div>
    </CollapsibleContext.Provider>
  );
}

function CollapsibleTrigger({ className, children, ...props }: React.ComponentProps<"button">) {
  const ctx = React.useContext(CollapsibleContext);
  return (
    <button
      data-slot="collapsible-trigger"
      className={cn("flex items-center gap-2 text-sm font-medium [&[data-state=open]>svg]:rotate-180", className)}
      onClick={() => ctx?.onOpenChange(!ctx?.open)}
      data-state={ctx?.open ? "open" : "closed"}
      {...props}
    >
      {children}
    </button>
  );
}

function CollapsibleContent({ className, children, ...props }: React.ComponentProps<"div">) {
  const ctx = React.useContext(CollapsibleContext);
  if (!ctx?.open) return null;
  return (
    <div data-slot="collapsible-content" className={cn("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down", className)} data-state={ctx.open ? "open" : "closed"} {...props}>
      {children}
    </div>
  );
}

export { Collapsible, CollapsibleTrigger, CollapsibleContent };
