import { useId, type ReactNode } from 'react'
import { safeHttpUrl } from './safe-url'

export interface SectionCardAction {
  label: string
  href?: string
  onClick?: () => void
}

export interface SectionCardProps {
  title: string
  /** Rendered inline after the title, e.g. a `StaleBadge` for this panel's adapter. */
  titleBadge?: ReactNode
  collapsible?: { expanded: boolean; onToggle(): void }
  action?: SectionCardAction
  children: ReactNode
  className?: string
}

/** `.card`/`.sec` — the shared header+body card shell every panel in the deck sits in. */
export function SectionCard({ title, titleBadge, action, children, className, collapsible }: SectionCardProps) {
  const bodyId = useId()
  const hasCollapsible = collapsible !== undefined
  return (
    <div
      className={`min-w-0 rounded-xl border border-border bg-surface px-4 py-3.5 ${className ?? ''}`.trim()}
    >
      <h4 className="mb-2.5 flex items-baseline justify-between text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">
        <span className="flex min-w-0 flex-1 items-center gap-1.5">
          {hasCollapsible ? (
            <button
              type="button"
              aria-expanded={collapsible.expanded}
              aria-controls={bodyId}
              onClick={collapsible.onToggle}
              className="flex min-h-11 min-w-0 items-center gap-2 text-left font-semibold text-fg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
            >
              <span
                aria-hidden="true"
                className={`shrink-0 text-fg-subtle transition-transform ${collapsible.expanded ? 'rotate-90' : ''}`}
              >
                ▸
              </span>
              <span className="block truncate">{title}</span>
            </button>
          ) : (
            <span className="block truncate">{title}</span>
          )}
          {titleBadge}
        </span>
        {action &&
          (action.href ? (
            <a
              href={safeHttpUrl(action.href)}
              className="shrink-0 text-[11px] font-normal normal-case tracking-normal text-fg-subtle no-underline"
            >
              {action.label}
            </a>
          ) : (
            <button
              type="button"
              onClick={action.onClick}
              className="shrink-0 cursor-pointer border-0 bg-transparent p-0 text-[11px] font-normal normal-case tracking-normal text-fg-subtle"
            >
              {action.label}
            </button>
          ))}
      </h4>
      {hasCollapsible ? (
        <div id={bodyId}>
          {collapsible.expanded ? children : null}
        </div>
      ) : (
        children
      )}
    </div>
  )
}
