'use client';

import { Plus } from 'lucide-react';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { useId, useState } from 'react';

import { faqs } from '@/lib/marketing';
import { cn } from '@/lib/utils';

export function FaqAccordion({ items = faqs }: { items?: typeof faqs }) {
  const [open, setOpen] = useState(0);
  const reduce = useReducedMotion();
  const baseId = useId();

  return (
    <div className="grid gap-3">
      {items.map((item, index) => {
        const isOpen = open === index;
        const buttonId = `${baseId}-q-${index}`;
        const panelId = `${baseId}-a-${index}`;
        return (
          <div
            key={item.question}
            className={cn(
              'rounded-lg border bg-surface transition-[border-color,box-shadow] duration-180 ease-brand',
              isOpen ? 'border-primary/40 shadow-md' : 'border-border shadow-xs hover:border-border-strong',
            )}
          >
            <h3>
              <button
                id={buttonId}
                type="button"
                className="flex min-h-14 w-full items-center justify-between gap-4 rounded-lg px-5 py-4 text-left"
                aria-expanded={isOpen}
                aria-controls={panelId}
                onClick={() => setOpen(isOpen ? -1 : index)}
              >
                <span className="text-[16px] font-semibold leading-6 text-foreground">{item.question}</span>
                <span
                  className={cn(
                    'grid h-8 w-8 shrink-0 place-items-center rounded-full transition-colors duration-180',
                    isOpen ? 'bg-primary-soft text-primary' : 'bg-surface-muted text-muted-foreground',
                  )}
                  aria-hidden="true"
                >
                  <Plus className={cn('h-4 w-4 transition-transform duration-180 ease-brand', isOpen && 'rotate-45')} />
                </span>
              </button>
            </h3>
            <AnimatePresence initial={false}>
              {isOpen ? (
                <motion.div
                  id={panelId}
                  role="region"
                  aria-labelledby={buttonId}
                  initial={reduce ? { opacity: 0 } : { height: 0, opacity: 0 }}
                  animate={reduce ? { opacity: 1 } : { height: 'auto', opacity: 1 }}
                  exit={reduce ? { opacity: 0 } : { height: 0, opacity: 0 }}
                  transition={{ duration: 0.28, ease: [0.2, 0.8, 0.2, 1] }}
                  className="overflow-hidden"
                >
                  <p className="px-5 pb-5 pr-16 text-body text-muted-foreground">{item.answer}</p>
                </motion.div>
              ) : null}
            </AnimatePresence>
          </div>
        );
      })}
    </div>
  );
}
