"use client";

import { useEffect, useId, useRef, useState } from "react";
import { CircleHelp } from "lucide-react";
import { useT } from "@/i18n";
import type { Dictionary } from "@/i18n/dictionaries/en";
import { cn } from "@/lib/cn";
import type { WidgetId } from "./types";

/**
 * The question mark on a card: what the card shows and how to read it, in a sentence or two, for someone opening the dashboard
 * for the first time. Closes on Escape, on a click elsewhere, and when focus leaves.
 */
export function WidgetHelp({ id }: { id: WidgetId }) {
  const t = useT();
  const [open, setOpen] = useState(false);
  const root = useRef<HTMLDivElement>(null);
  const panelId = useId();

  useEffect(() => {
    if (!open) return;
    const onPointer = (event: PointerEvent) => {
      if (!root.current?.contains(event.target as Node)) setOpen(false);
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    document.addEventListener("pointerdown", onPointer);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("pointerdown", onPointer);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <div ref={root} className="relative">
      <button
        type="button"
        aria-label={t("widgets.help.open")}
        aria-expanded={open}
        aria-controls={panelId}
        title={t("widgets.help.open")}
        onClick={() => setOpen((value) => !value)}
        className={cn(
          "rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
          open && "bg-muted text-foreground",
        )}
      >
        <CircleHelp className="h-4 w-4" aria-hidden />
      </button>
      {open ? (
        <div
          id={panelId}
          role="note"
          className="absolute end-0 top-full z-30 mt-2 w-64 rounded-lg border bg-surface p-4 text-xs leading-5 text-muted-foreground shadow-xl motion-safe:animate-[kap-help-in_0.16s_ease-out]"
        >
          {t(`widgets.help.${id}` as keyof Dictionary)}
        </div>
      ) : null}
    </div>
  );
}
