import { useState, useRef } from 'react'
import styles from './Collapsible.module.css'
import type { ReactNode } from 'react'

interface CollapsibleProps {
  title: ReactNode
  children: ReactNode
  defaultOpen?: boolean
  open?: boolean
  onToggle?: (open: boolean) => void
  className?: string
}

export function Collapsible({
  title,
  children,
  defaultOpen = false,
  open: controlledOpen,
  onToggle,
  className,
}: CollapsibleProps) {
  const isControlled = controlledOpen !== undefined
  const [internalOpen, setInternalOpen] = useState(defaultOpen)
  const open = isControlled ? controlledOpen : internalOpen
  const contentRef = useRef<HTMLDivElement>(null)

  function handleToggle() {
    const next = !open
    if (!isControlled) setInternalOpen(next)
    onToggle?.(next)
  }

  return (
    <div className={`${styles.root} ${className ?? ''}`}>
      <button
        type="button"
        className={styles.trigger}
        onClick={handleToggle}
        aria-expanded={open}
      >
        <span className={styles.title}>{title}</span>
        <span className={`${styles.chevron} ${open ? styles.chevronOpen : ''}`}>▾</span>
      </button>
      <div
        ref={contentRef}
        className={`${styles.content} ${open ? styles.contentOpen : ''}`}
        hidden={!open}
      >
        <div className={styles.inner}>{children}</div>
      </div>
    </div>
  )
}
