import type { VariantProps } from 'class-variance-authority'
import { cva } from 'class-variance-authority'
import type React from 'react'
import { cn } from '../../utils/cn'

const sectionVariants = cva(
  'py-8 px-6 lg:px-10 border-border border-0 border-solid',
  {
    variants: {
      variant: {
        default: 'bg-background',
        alt: 'bg-background-alt border-t',
      },
      border: {
        true: 'border-t',
        false: 'border-t-0',
      },
      width: {
        default: '',
        fluid: '',
        narrow: '',
      },
    },
    defaultVariants: {
      variant: 'default',
    },
  },
)

interface SectionProps
  extends React.HTMLAttributes<HTMLDivElement>,
    VariantProps<typeof sectionVariants> {
  fluid?: boolean
  ref?: React.Ref<HTMLDivElement>
}

function InnerWrapper({
  width,
  children,
}: {
  width: 'default' | 'fluid' | 'narrow'
  children: React.ReactNode
}) {
  if (width === 'fluid') {
    return children
  }
  return (
    <div
      className={cn(
        'container mx-auto w-full',
        width === 'narrow' && 'max-w-screen-lg',
      )}
    >
      {children}
    </div>
  )
}

const Section = ({
  variant,
  className,
  children,
  border,
  width = 'default',
  ref,
  ...props
}: SectionProps) => {
  return (
    <section
      className={cn(sectionVariants({ variant, className, border }))}
      {...props}
      ref={ref}
    >
      <InnerWrapper width={width ?? 'default'}>{children}</InnerWrapper>
    </section>
  )
}
Section.displayName = 'Section'

export { Section, type SectionProps }
