import { useState, useSyncExternalStore } from 'react';

const focusRing =
    'rounded-marketing-sm outline-marketing-primary focus-visible:outline-2 focus-visible:outline-offset-2';

const body = 'text-base leading-[1.6] text-marketing-ink/80';

const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';

function subscribeToReducedMotion(onChange: () => void): () => void {
    const query = window.matchMedia(REDUCED_MOTION_QUERY);
    query.addEventListener('change', onChange);

    return () => query.removeEventListener('change', onChange);
}

function usePrefersReducedMotion(): boolean {
    return useSyncExternalStore(
        subscribeToReducedMotion,
        () => window.matchMedia(REDUCED_MOTION_QUERY).matches,
        () => false,
    );
}

export type Faq = { question: string; answer: string };

function FaqItem({
    faq,
    open,
    onToggle,
    reducedMotion,
    index,
    idPrefix,
}: {
    faq: Faq;
    open: boolean;
    onToggle: () => void;
    reducedMotion: boolean;
    index: number;
    idPrefix: string;
}) {
    return (
        <div className="border-marketing-border border-b">
            <h3>
                <button
                    type="button"
                    aria-expanded={open}
                    aria-controls={`${idPrefix}-${index}`}
                    onClick={onToggle}
                    className={`font-display flex w-full items-center justify-between gap-4 py-5 text-left text-[1.125rem] leading-[1.35] font-semibold ${focusRing}`}
                >
                    <span>{faq.question}</span>
                    <span
                        aria-hidden="true"
                        className="text-marketing-primary relative inline-block size-3.5 shrink-0"
                    >
                        <span className="absolute top-1/2 left-0 h-[1.5px] w-full -translate-y-1/2 bg-current" />
                        <span
                            className={`absolute top-0 left-1/2 h-full w-[1.5px] -translate-x-1/2 bg-current ${
                                reducedMotion
                                    ? ''
                                    : 'transition-transform duration-200 ease-out'
                            } ${open ? 'scale-y-0' : 'scale-y-100'}`}
                        />
                    </span>
                </button>
            </h3>
            <div
                id={`${idPrefix}-${index}`}
                className={`grid ${
                    reducedMotion
                        ? ''
                        : 'transition-[grid-template-rows] duration-200 ease-out'
                } ${open ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'}`}
            >
                <div className="overflow-hidden" inert={!open}>
                    <p className={`max-w-[38rem] pb-5 ${body}`}>{faq.answer}</p>
                </div>
            </div>
        </div>
    );
}

/** Accordion FAQ riutilizzabile (vedi docs/design-system.md §5): una domanda aperta alla volta. */
export function FaqAccordion({
    faqs,
    idPrefix,
}: {
    faqs: Faq[];
    idPrefix: string;
}) {
    const reducedMotion = usePrefersReducedMotion();
    const [openFaq, setOpenFaq] = useState<number | null>(null);

    return (
        <div className="border-marketing-border max-w-[44rem] border-t">
            {faqs.map((faq, index) => (
                <FaqItem
                    key={faq.question}
                    faq={faq}
                    index={index}
                    idPrefix={idPrefix}
                    open={openFaq === index}
                    reducedMotion={reducedMotion}
                    onToggle={() =>
                        setOpenFaq((current) =>
                            current === index ? null : index,
                        )
                    }
                />
            ))}
        </div>
    );
}
