// Searchable, category-tabbed picker over the named animation library
// (utils/animationPresets.ts). Editor-only — the WAAPI hover preview here
// never ships to the public frontend bundle; production playback is always
// the CSS @keyframes engine in assets/css/frontend.css.
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { createPortal } from 'react-dom';
import type { AnimationPreset, AnimationCategory } from '../../utils/animationPresets';
import { ANIMATION_PRESETS, ANIMATION_CATEGORIES, searchPresets, buildWaapiPreviewKeyframes } from '../../utils/animationPresets';

function PresetSwatch({ preset, onSelect }: { preset: AnimationPreset; onSelect: () => void }) {
  const boxRef = useRef<HTMLDivElement>(null);

  const play = () => {
    const el = boxRef.current;
    if (!el || typeof el.animate !== 'function') return;
    el.getAnimations().forEach((a) => a.cancel());
    el.animate(buildWaapiPreviewKeyframes(preset.action, preset.settings), {
      duration: 700,
      easing: preset.settings.easing && preset.settings.easing.startsWith('cubic-bezier') ? preset.settings.easing : 'ease-out',
      fill: 'both',
    });
  };

  return (
    <button
      type="button"
      className="jalpi-ap-item"
      onClick={onSelect}
      onMouseEnter={play}
      onFocus={play}
      aria-label={`Apply ${preset.label} animation`}
    >
      <span className="jalpi-ap-item__stage">
        <span className="jalpi-ap-item__box" ref={boxRef} aria-hidden="true" />
      </span>
      <span className="jalpi-ap-item__label">{preset.label}</span>
    </button>
  );
}

export default function AnimationPresetPicker({
  onClose,
  onSelect,
}: {
  onClose: () => void;
  onSelect: (preset: AnimationPreset) => void;
}) {
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState<AnimationCategory | 'All'>('All');
  const searchRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    searchRef.current?.focus();
    const h = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);

  const results = useMemo(() => searchPresets(query, category), [query, category]);

  return createPortal(
    <div className="jalpi-ap-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="jalpi-ap-modal" role="dialog" aria-label="Animation Presets">
        <div className="jalpi-ap-modal__header">
          <input
            ref={searchRef}
            type="text"
            className="jalpi-ap-search"
            placeholder="Search animations…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <button type="button" className="jalpi-ap-close" onClick={onClose} aria-label="Close animation picker">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <path d="M6 6l12 12M18 6L6 18" />
            </svg>
          </button>
        </div>

        <div className="jalpi-ap-cats" role="tablist" aria-label="Animation categories">
          <button
            type="button"
            className={`jalpi-ap-cat${category === 'All' ? ' is-active' : ''}`}
            onClick={() => setCategory('All')}
          >
            All
          </button>
          {ANIMATION_CATEGORIES.map((c) => (
            <button
              key={c}
              type="button"
              className={`jalpi-ap-cat${category === c ? ' is-active' : ''}`}
              onClick={() => setCategory(c)}
            >
              {c}
            </button>
          ))}
        </div>

        <div className="jalpi-ap-grid">
          {results.map((preset) => (
            <PresetSwatch key={preset.id} preset={preset} onSelect={() => onSelect(preset)} />
          ))}
          {results.length === 0 && (
            <p className="jalpi-ia-hint">No animations match "{query}".</p>
          )}
        </div>
        <p className="jalpi-ap-count">{results.length} of {ANIMATION_PRESETS.length} animations</p>
      </div>
    </div>,
    document.body
  );
}
