'use client';

import { ReactNode, useId, useState } from 'react';

interface DisclosureProps {
  icon?: ReactNode;
  title: ReactNode;
  subtitle?: ReactNode;
  defaultOpen?: boolean;
  className?: string;
  children: ReactNode;
}

export function Disclosure({
  icon,
  title,
  subtitle,
  defaultOpen = false,
  className = '',
  children,
}: DisclosureProps) {
  const [isOpen, setIsOpen] = useState(defaultOpen);
  const contentId = useId();

  return (
    <div className={`overflow-hidden rounded-xl border border-border bg-card ${className}`}>
      <button
        type="button"
        onClick={() => setIsOpen((prev) => !prev)}
        aria-expanded={isOpen}
        aria-controls={contentId}
        className={`
          flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition-colors
          ${isOpen ? 'bg-card-hover/60' : 'hover:bg-card-hover/60'}
        `}
      >
        <div className="min-w-0 flex flex-1 items-start gap-2">
          {icon && (
            <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center self-center text-base leading-none">
              {icon}
            </span>
          )}
          <div className="min-w-0">
            <div className="text-sm font-medium text-foreground">{title}</div>
            {subtitle && <div className="mt-0.5 text-xs text-muted">{subtitle}</div>}
          </div>
        </div>
        <span className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-card-hover text-muted">
          <svg
            className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </span>
      </button>
      {isOpen && (
        <div id={contentId} className="border-t border-border bg-card px-4 py-3">
          {children}
        </div>
      )}
    </div>
  );
}
