import { useEffect, useRef } from "preact/hooks";
import { text } from "../lib/config";
import { NetworkIcon } from "./NetworkIcon";

/**
 * "Share via" list under the Share button: one link per network, Copy
 * link and, where the browser has it, the native share sheet. Esc or a
 * click outside closes it (Esc doesn't reach the popup's own handler).
 */
export function ShareMenu({
  id,
  url,
  title,
  networks,
  onCopy,
  onNative,
  onClose,
}) {
  const ref = useRef(null);

  useEffect(() => {
    ref.current?.querySelector("a, button")?.focus();

    const outside = (event) => {
      if (!ref.current?.parentElement?.contains(event.target)) {
        onClose(false);
      }
    };

    document.addEventListener("pointerdown", outside);

    return () => document.removeEventListener("pointerdown", outside);
  }, [onClose]);

  const onKeyDown = (event) => {
    if (event.key === "Escape") {
      event.stopPropagation();
      onClose(true);
    }
  };

  return (
    <div
      ref={ref}
      id={id}
      className="pcfw-share__menu"
      role="group"
      aria-label={text("shareVia", "Share via")}
      onKeyDown={onKeyDown}
    >
      {networks.map((network) => (
        <a
          key={network.key}
          className={`pcfw-share__item pcfw-share__item--${network.key}`}
          href={network.href(url, title)}
          target={network.key === "email" ? undefined : "_blank"}
          rel="noopener noreferrer nofollow"
          onClick={() => onClose(false)}
        >
          <NetworkIcon name={network.key} />
          {network.label}
        </a>
      ))}
      <button type="button" className="pcfw-share__item" onClick={onCopy}>
        <NetworkIcon name="link" />
        {text("copyLink", "Copy link")}
      </button>
      {onNative && (
        <button type="button" className="pcfw-share__item" onClick={onNative}>
          <NetworkIcon name="more" />
          {text("moreOptions", "More options…")}
        </button>
      )}
    </div>
  );
}
