import { useState } from "preact/hooks";
import { text } from "../lib/config";
import { format } from "../lib/format";
import { plainText } from "../lib/plain";
import { Html } from "./Html";

let counter = 0;

/**
 * "?" after a row label with the row's tooltip (Pro). Shows on hover and
 * keyboard focus; Esc hides it while the pointer or focus stays.
 */
export function RowTip({ tip, label }) {
  const [id] = useState(() => `pcfw-tip-${++counter}`);
  const [hidden, setHidden] = useState(false);

  return (
    <span
      className={`pcfw-tip${hidden ? " is-dismissed" : ""}`}
      onMouseLeave={() => setHidden(false)}
    >
      <button
        type="button"
        className="pcfw-tip__button"
        aria-describedby={id}
        aria-label={format(text("aboutRow", "About %s"), plainText(label))}
        onKeyDown={(event) => event.key === "Escape" && setHidden(true)}
        onBlur={() => setHidden(false)}
      >
        ?
      </button>
      <span id={id} role="tooltip" className="pcfw-tip__bubble">
        <Html html={tip} />
      </span>
    </span>
  );
}
