"use client";

import cx from "classnames";
import React, { ReactNode } from "react";
import { useStatic } from "@/utils/hooks";
import AccordionStatic from "./Accordion.static";
import HeadingContext from "./HeadingContext";

const CLASS_ROOT = "accordion";

interface AccordionProps {
  /** Heading level from 1 to 6 */
  headingLevel?: number;
  /** Accordion is enclosed in another component */
  isEnclosed?: boolean;
  /** If true, the top border on the first item will be removed */
  noTopBorder?: boolean;
  /** Adjustable spacing */
  size?: "large";
  /** Additional CSS classes */
  className?: string;
  /** Accordion content */
  children: ReactNode;
  /** Additional HTML attributes */
  [key: string]: any;
}

const Accordion: React.FC<AccordionProps> = ({
  className,
  children,
  headingLevel = 3,
  size,
  isEnclosed,
  noTopBorder,
  ...other
}) => {
  const [accordionRef] = useStatic(AccordionStatic);

  const classes = cx(
    CLASS_ROOT,
    {
      [`${CLASS_ROOT}--${size}`]: size,
      [`${CLASS_ROOT}--enclosed`]: isEnclosed,
      [`${CLASS_ROOT}--no-top-border`]: noTopBorder,
    },
    className,
  );

  return (
    <HeadingContext.Provider value={headingLevel}>
      <ul
        className={classes}
        ref={accordionRef}
        data-accordion="true"
        {...other}
      >
        {children}
      </ul>
    </HeadingContext.Provider>
  );
};

Accordion.displayName = "Accordion";

export { Accordion };
