import { useEffect, useState, type ReactNode } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";

export interface SectionProps {
  title: string;
  description?: string;
  children: ReactNode;
  defaultExpanded?: boolean;
  alwaysExpanded?: boolean;
}

export function Section({
  title,
  description,
  children,
  defaultExpanded = false,
  alwaysExpanded = false,
}: SectionProps) {
  const storageKey = `section-${title.toLowerCase().replace(/\s+/g, '-')}`;
  
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  const [isHydrated, setIsHydrated] = useState(false);

  useEffect(() => {
    if (alwaysExpanded) {
      setIsExpanded(true);
      setIsHydrated(true);
      return;
    }
    
    const stored = sessionStorage.getItem(storageKey);
    if (stored !== null) {
      setIsExpanded(JSON.parse(stored));
    }
    setIsHydrated(true);
  }, [alwaysExpanded, storageKey]);

  const handleToggle = () => {
    if (alwaysExpanded) return;
    
    const newExpanded = !isExpanded;
    setIsExpanded(newExpanded);
    
    if (typeof window !== 'undefined') {
      sessionStorage.setItem(storageKey, JSON.stringify(newExpanded));
    }
  };

  const effectiveExpanded = alwaysExpanded || (isHydrated ? isExpanded : defaultExpanded);

  return (
    <section className="flex flex-col gap-3">
      <div 
        className={cn(
          "flex items-center gap-2 cursor-pointer",
          !alwaysExpanded && "hover:text-foreground transition-colors"
        )}
        onClick={handleToggle}
      >
        {!alwaysExpanded && (
          effectiveExpanded ? (
            <ChevronDown className="h-4 w-4 text-muted-foreground" />
          ) : (
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
          )
        )}
        <div className="flex flex-col gap-1 flex-1">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">{title}</h2>
          {description && <p className="text-xs text-muted-foreground/80">{description}</p>}
        </div>
      </div>
      {effectiveExpanded && (
        <div className="flex flex-col gap-2 ml-2 pl-2 border-l-2 border-border/30">{children}</div>
      )}
    </section>
  );
}
