'use client';
import { useEffect, useRef, useState } from 'react';
import {
  ArrowUpRight,
  ArrowRight,
  RotateCcw,
  Play,
  Pause,
  Check,
  Move,
  Plus,
} from 'lucide-react';
import { AdvancedMotion } from './advanced-motion';
import { expandedMotion } from '@/lib/expanded-showcase';
import { Demo } from './demos';
const existing = [
  'spring',
  'magnetic',
  'reveal',
  'transition',
  'parallax',
  'stack',
  'marquee',
];
export function MotionDemo({ id }: { id: string }) {
  const [changed, setChanged] = useState(false),
    [run, setRun] = useState(0),
    [paused, setPaused] = useState(false),
    [ripples, setRipples] = useState<{ x: number; y: number; id: number }[]>(
      [],
    );
  const root = useRef<HTMLDivElement>(null),
    visual = useRef<HTMLDivElement>(null),
    trail = useRef<HTMLDivElement>(null),
    frame = useRef(0),
    timeouts = useRef<ReturnType<typeof setTimeout>[]>([]);
  useEffect(
    () => () => {
      cancelAnimationFrame(frame.current);
      timeouts.current.forEach(clearTimeout);
    },
    [],
  );
  if (expandedMotion.some((m) => m.id === id))
    return <AdvancedMotion id={id} />;
  if (existing.includes(id)) return <Demo id={id} compact />;
  return (
    <div
      ref={root}
      className={`motion-extra me-${id} ${changed ? 'changed' : ''} ${paused ? 'paused' : ''}`}
      onPointerLeave={() => {
        if (visual.current && id === 'tilt-card')
          visual.current.style.transform = 'rotateX(0deg) rotateY(0deg)';
      }}
      onPointerMove={(e) => {
        if (matchMedia('(prefers-reduced-motion:reduce)').matches) return;
        const b = e.currentTarget.getBoundingClientRect(),
          x = e.clientX - b.left,
          y = e.clientY - b.top;
        if (id === 'spotlight' && visual.current)
          visual.current.style.background = `radial-gradient(circle 125px at ${x}px ${y}px, #697d4d 0%, transparent 100%)`;
        if (id === 'tilt-card' && visual.current)
          visual.current.style.transform = `perspective(700px) rotateX(${-(y / b.height - 0.5) * 22}deg) rotateY(${(x / b.width - 0.5) * 26}deg)`;
        if (id === 'cursor-trail' && trail.current) {
          [...trail.current.children].forEach((n, i) => {
            (n as HTMLElement).style.transform =
              `translate(${x - 15}px, ${y - 15}px) scale(${1 - i * 0.11})`;
          });
        }
      }}
    >
      {id === 'spotlight' && (
        <>
          <div ref={visual} className="spotlight-layer" />
          <div className="spotlight-copy">
            <span>Stay curious.</span>
            <ArrowUpRight size={35} />
          </div>
          <small className="extra-hint">Проведи курсором</small>
        </>
      )}
      {id === 'tilt-card' && (
        <div ref={visual} className="tilt-object">
          <span>MEMBERSHIP / 001</span>
          <strong>
            A different
            <br />
            perspective.
          </strong>
          <ArrowUpRight size={24} />
        </div>
      )}
      {id === 'cursor-trail' && (
        <>
          <div ref={trail} className="cursor-trail">
            {[0, 1, 2, 3, 4, 5].map((i) => (
              <span
                key={i}
                style={{
                  transitionDuration: `${80 + i * 70}ms`,
                  opacity: 1 - i * 0.12,
                }}
              />
            ))}
          </div>
          <span className="extra-hint">Нарисуй траекторию курсором</span>
        </>
      )}
      {id === 'stagger' && (
        <>
          <div className="stagger-items" key={run}>
            {['First thought.', 'A new direction.', 'The final detail.'].map(
              (t, i) => (
                <div key={t} style={{ animationDelay: `${i * 110}ms` }}>
                  <span>{t}</span>
                  <ArrowUpRight size={16} />
                </div>
              ),
            )}
          </div>
          <button
            className="extra-control"
            onClick={() => setRun((r) => r + 1)}
          >
            <RotateCcw size={14} />
            Повторить
          </button>
        </>
      )}
      {id === 'mask-wipe' && (
        <>
          <div className="wipe-base">
            A fresh
            <br />
            <em>start.</em>
          </div>
          <div className="wipe-cover">
            Another
            <br />
            <em>perspective.</em>
          </div>
          <button
            className="extra-control"
            onClick={() => setChanged(!changed)}
          >
            <ArrowRight size={14} />
            Сменить слой
          </button>
        </>
      )}
      {id === 'flip' && (
        <>
          <button
            aria-label="Перевернуть карточку"
            className="flip-target"
            onClick={() => setChanged(!changed)}
          >
            <span className="flip-inner">
              <span className="flip-front">
                Hello,
                <br />
                <em>curiosity.</em>
                <ArrowUpRight size={23} />
              </span>
              <span className="flip-back">
                There is
                <br />
                another side.
                <ArrowRight size={23} />
              </span>
            </span>
          </button>
          <span className="extra-hint">Нажми на карточку</span>
        </>
      )}
      {id === 'morph' && (
        <>
          <button
            className="morph-shape"
            onClick={() => setChanged(!changed)}
            aria-label="Изменить форму"
          >
            <Plus size={26} />
          </button>
          <span className="extra-hint">Нажми, чтобы изменить контур</span>
        </>
      )}
      {id === 'scroll-progress' && (
        <div
          className="progress-scroll"
          tabIndex={0}
          aria-label="Прокручиваемый текст с индикатором"
          onScroll={(e) => {
            const el = e.currentTarget;
            if (visual.current)
              visual.current.style.transform = `scaleX(${el.scrollTop / (el.scrollHeight - el.clientHeight)})`;
          }}
        >
          <div className="progress-track">
            <div ref={visual} />
          </div>
          <article>
            <h3>Take your time.</h3>
            <p>
              Это отдельная область прокрутки. Полоса сверху показывает, какую
              часть текста ты прочитал.
            </p>
            <p>
              Индикатор связан с реальным положением прокрутки. Он не меняет
              скорость и не перехватывает управление.
            </p>
            <p>
              Читатель может использовать колесо мыши, касание или клавиатуру.
            </p>
            <h3>You made it.</h3>
          </article>
        </div>
      )}
      {id === 'orbit-motion' && (
        <>
          <div className="orbital-system">
            <i />
            <i />
            <i />
            <b />
          </div>
          <button className="extra-control" onClick={() => setPaused(!paused)}>
            {paused ? <Play size={14} /> : <Pause size={14} />}{' '}
            {paused ? 'Продолжить' : 'Пауза'}
          </button>
        </>
      )}
      {id === 'border-draw' && (
        <>
          <div className="border-draw-object">
            <svg key={run} viewBox="0 0 240 150" aria-hidden="true">
              <rect
                x="2"
                y="2"
                width="236"
                height="146"
                rx="15"
                pathLength="1"
              />
            </svg>
            <strong>
              Details
              <br />
              make the difference.
            </strong>
          </div>
          <button
            className="extra-control"
            onClick={() => setRun((r) => r + 1)}
          >
            <RotateCcw size={14} />
            Повторить
          </button>
        </>
      )}
      {id === 'ripple' && (
        <button
          className="ripple-target"
          onClick={(e) => {
            const b = e.currentTarget.getBoundingClientRect(),
              key = Date.now();
            setRipples((r) => [
              ...r.slice(-3),
              {
                x: e.detail ? e.clientX - b.left : b.width / 2,
                y: e.detail ? e.clientY - b.top : b.height / 2,
                id: key,
              },
            ]);
            timeouts.current.push(
              setTimeout(
                () => setRipples((r) => r.filter((x) => x.id !== key)),
                750,
              ),
            );
          }}
        >
          Make an impression.
          <ArrowUpRight size={21} />
          {ripples.map((r) => (
            <i key={r.id} style={{ left: r.x, top: r.y }} />
          ))}
        </button>
      )}
    </div>
  );
}
