import { h } from 'preact';
import { useMemo, useState } from 'preact/hooks';

export type AccordionItem<T extends string = string> = {
  id: T;
  title: string;
  right?: preact.ComponentChildren;
  content: preact.ComponentChildren;
  defaultOpen?: boolean;
};

/** Small reusable multi-open accordion. */
export function Accordion<T extends string = string>(props: {
  items: AccordionItem<T>[];
  className?: string;
}): h.JSX.Element {
  const defaultOpen = useMemo(() => {
    const open = new Set<string>();
    props.items.forEach((it) => {
      if (it.defaultOpen) open.add(it.id);
    });
    return open;
  }, [props.items]);

  const [open, setOpen] = useState<Set<string>>(defaultOpen);

  return (
    <div className={props.className ?? ''}>
      {props.items.map((it) => {
        const isOpen = open.has(it.id);
        return (
          <section
            key={it.id}
            className={[
              'ask-mb-2 ask-overflow-hidden ask-rounded-[18px] ask-border ask-transition',
              isOpen
                ? 'ask-border-primary/15 ask-bg-surface ask-shadow-[0_8px_20px_rgba(15,23,42,0.05)]'
                : 'ask-border-borderSubtle/80 ask-bg-surfaceAlt/70 hover:ask-border-primary/20 hover:ask-bg-surface',
            ].join(' ')}
          >
            <button
              type="button"
              className="ask-flex ask-w-full ask-items-center ask-justify-between ask-gap-3 ask-px-3 ask-py-2.5 ask-text-left"
              onClick={() => {
                setOpen((prev) => {
                  const next = new Set(prev);
                  if (next.has(it.id)) next.delete(it.id);
                  else next.add(it.id);
                  return next;
                });
              }}
            >
              <span className="ask-min-w-0 ask-flex-1 ask-truncate ask-text-[13px] ask-font-semibold ask-text-textMain">{it.title}</span>
              <span className="ask-flex ask-shrink-0 ask-items-center ask-gap-2">
                {it.right}
                <span className={[
                  'ask-flex ask-h-7 ask-w-7 ask-items-center ask-justify-center ask-rounded-full ask-border ask-border-borderSubtle ask-bg-surface ask-text-[15px] ask-text-textMuted ask-transition',
                  isOpen ? 'ask-rotate-90' : '',
                ].join(' ')} aria-hidden>›</span>
              </span>
            </button>
            {isOpen ? <div className="ask-border-t ask-border-borderSubtle/70 ask-p-2.5">{it.content}</div> : null}
          </section>
        );
      })}
    </div>
  );
}
