"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

/**
 * What a badge means, on hover.
 *
 * A symbol beside a name is only useful if people can find out what it
 * stands for, and nobody reads a legend page. The tooltip is rendered into
 * the body so a card with hidden overflow can't clip it.
 */
export function BadgeTip({
  title,
  detail,
  children,
}: {
  /** What it is, in a couple of words. */
  title: string;
  /** Why this person has it. */
  detail?: string;
  children: React.ReactNode;
}) {
  const [at, setAt] = useState<{ x: number; y: number } | null>(null);
  const holder = useRef<HTMLSpanElement | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const show = () => {
    // A short wait, so passing the cursor over a row of badges doesn't
    // flash a tooltip for each one.
    timer.current = setTimeout(() => {
      const r = holder.current?.getBoundingClientRect();
      if (!r) return;
      setAt({ x: r.left + r.width / 2, y: r.top });
    }, 320);
  };

  const hide = () => {
    if (timer.current) clearTimeout(timer.current);
    setAt(null);
  };

  // Scrolling moves the badge out from under its own tooltip.
  useEffect(() => {
    if (!at) return;
    window.addEventListener("scroll", hide, true);
    return () => window.removeEventListener("scroll", hide, true);
  }, [at]);

  return (
    <>
      <span
        ref={holder}
        onPointerEnter={show}
        onPointerLeave={hide}
        onFocus={show}
        onBlur={hide}
        className="bt-holder"
      >
        {children}
      </span>

      {at &&
        typeof document !== "undefined" &&
        createPortal(
          <span
            className="bt-tip"
            style={{ left: at.x, top: at.y }}
            role="tooltip"
          >
            <b>{title}</b>
            {detail && <em>{detail}</em>}
          </span>,
          document.body
        )}
    </>
  );
}

/** What each badge stands for, in one place so they can't disagree. */
export const BADGE_MEANINGS: Record<
  string,
  { title: string; detail: string }
> = {
  pro: {
    title: "Pro member",
    detail: "Pays monthly. Can message anyone and use every profile effect.",
  },
  ultra: {
    title: "Ultra member",
    detail: "Everything Pro has, without adverts, and with priority support.",
  },
  verified: {
    title: "Verified",
    detail: "An admin has confirmed this is who they say they are.",
  },
  admin: {
    title: "Admin",
    detail: "Runs this site.",
  },
  premium: {
    title: "Premium",
    detail: "Supports the site with a paid account.",
  },
};
