'use client'

import { createContext, forwardRef, ReactNode, useContext } from 'react'
import type { TAccordionSkin } from 'shared-types'

export type TPktAccordionSkin = TAccordionSkin

export interface IPktAccordion {
  compact?: boolean
  /**
   * @default skin: "borderless"
   */
  skin?: TPktAccordionSkin
  /**
   * @description A unique identifier to connect the accordion with a heading
   */
  ariaLabelledBy?: string
  children?: ReactNode
  name?: string
  className?: string
}

// Send name som context til AccordionItem-children
const AccordionContext = createContext<{ name?: string }>({})

export const useAccordionContext = () => useContext(AccordionContext)

export const PktAccordion = forwardRef<HTMLDivElement, IPktAccordion>(
  ({ compact = false, skin = 'borderless', ariaLabelledBy, children, name, className }, ref) => {
    const accordionClasses = [
      'pkt-accordion',
      compact && 'pkt-accordion--compact',
      skin && `pkt-accordion--${skin}`,
      className,
    ]
      .filter(Boolean)
      .join(' ')

    return (
      <AccordionContext.Provider value={{ name }}>
        <div
          ref={ref}
          className={accordionClasses}
          data-testid="pkt-accordion"
          aria-labelledby={ariaLabelledBy || undefined}
        >
          {children}
        </div>
      </AccordionContext.Provider>
    )
  },
)

PktAccordion.displayName = 'PktAccordion'
