"use client";

import { useState, useRef, useEffect } from "react";
import { firework } from "@/lib/particles";
import { sfx } from "@/lib/sfx";
import { useClickOutside } from "@/lib/use-click-outside";

export const REACTIONS = [
  { emoji: "❤️", key: "heart", color: "#ff5a7a" },
  { emoji: "👍", key: "thumb", color: "#3aa0ff" },
  { emoji: "😂", key: "laugh", color: "#f5b400" },
  { emoji: "🎉", key: "party", color: "#b06dff" },
  { emoji: "😮", key: "wow", color: "#8cf3ff" },
  { emoji: "😢", key: "sad", color: "#5aa7ff" },
  { emoji: "😡", key: "angry", color: "#ff4d4d" },
  { emoji: "🔥", key: "fire", color: "#ff8a3c" },
] as const;

export type ReactionKey = (typeof REACTIONS)[number]["key"];

/**
 * Facebook-style reaction picker. Hovering (or tapping) the like button
 * opens a row of animated emoji; choosing one bursts a giant copy over the
 * post media and leaves the chosen emoji on the action bar.
 */
export function useReactionBurst() {
  const [burst, setBurst] = useState<{ emoji: string; color: string } | null>(null);
  function fire(emoji: string, color: string) {
    setBurst({ emoji, color });
    setTimeout(() => setBurst(null), 1000);
  }
  return { burst, fire };
}

export function ReactionBurst({ burst }: { burst: { emoji: string; color: string } | null }) {
  const bigRef = useRef<HTMLSpanElement>(null);

  // Fire the particle burst from the giant emoji once it has scaled up.
  useEffect(() => {
    if (!burst || !bigRef.current) return;
    const el = bigRef.current;
    const t = setTimeout(() => firework(el, [burst.color, "#ffffff", "#ffd9a0"]), 380);
    return () => clearTimeout(t);
  }, [burst]);

  if (!burst) return null;
  return (
    <>
      <span
        className="rx-flash"
        style={{
          background: `radial-gradient(circle at 50% 50%, ${burst.color}66, transparent 72%)`,
          animation: "rx-flashA 950ms ease-out forwards",
        }}
      />
      <span
        ref={bigRef}
        className="rx-big"
        style={{ animation: "rx-bigA 1000ms cubic-bezier(.3,1.5,.4,1) forwards" }}
      >
        {burst.emoji}
      </span>
    </>
  );
}

export function ReactionPicker({
  current,
  onPick,
  onQuickPick,
  children,
}: {
  current: ReactionKey | null;
  onPick: (r: (typeof REACTIONS)[number] | null) => void;
  /** A plain click, when the picker isn't wanted. */
  onQuickPick?: () => void;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const ref = useClickOutside<HTMLDivElement>(open, () => setOpen(false));
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(
    () => () => {
      if (timer.current) clearTimeout(timer.current);
      if (closeTimer.current) clearTimeout(closeTimer.current);
    },
    []
  );

  return (
    <div
      ref={ref}
      className="relative"
      onMouseEnter={() => {
        timer.current = setTimeout(() => setOpen(true), 260);
      }}
      onMouseLeave={() => {
        if (timer.current) clearTimeout(timer.current);
        // Small delay so moving up into the picker doesn't close it.
        closeTimer.current = setTimeout(() => setOpen(false), 320);
      }}
      onMouseOver={() => {
        if (closeTimer.current) clearTimeout(closeTimer.current);
      }}
    >
      <div
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();

          // A click likes or unlikes. Choosing a different reaction is a
          // hover on a mouse, or a long press on touch — a click opening the
          // picker meant a single tap never liked anything.
          if (onQuickPick) {
            onQuickPick();
            return;
          }

          if (!current) {
            setOpen((v) => !v);
            if (!open) sfx.comment();
          } else {
            onPick(null);
          }
        }}
        onContextMenu={(e) => {
          // Long press and right-click both open the picker.
          e.preventDefault();
          setOpen(true);
        }}
      >
        {children}
      </div>

      {open && (
        <div className="rx-picker" onMouseEnter={() => setOpen(true)}>
          {REACTIONS.map((r, i) => (
            <span
              key={r.key}
              style={{ ["--i" as string]: i, color: r.color }}
              className={current === r.key ? "sel" : ""}
              title={r.key}
              onClick={(e) => {
                e.stopPropagation();
                setOpen(false);
                if (current !== r.key) sfx.reaction(r.key);
                onPick(current === r.key ? null : r);
              }}
            >
              {r.emoji}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
