import { type FC, type MouseEvent, useEffect } from "react";
import { useTranslation } from "@/i18n/provider.js";
import "./actions.scss";

export interface SharePanelProps {
  url: string;
  locale: string;
  onClose: () => void;
}

export const SharePanel: FC<SharePanelProps> = ({ url, locale, onClose }) => {
  const { t } = useTranslation();
  const encoded = encodeURIComponent(url);

  // Close on Escape — matches Angular's PrimeNG p-overlayPanel dismissable behaviour.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const handleCopy = async (e: MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    try {
      await navigator.clipboard.writeText(url);
      onClose();
    } catch {
      // silent
    }
  };

  return (
    <div className="share-panel" data-testid="share-panel" role="dialog" aria-label={t("BOARD.SHARE")}>
      <div className="share-elements">
        <div>
          <a
            className="share-element facebook"
            data-testid="share-facebook"
            href={`https://www.facebook.com/sharer/sharer.php?u=${encoded}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {t("SHARE.FACEBOOK")}
          </a>
        </div>
        <div>
          <a
            className="share-element vk"
            data-testid="share-vk"
            href={`https://vk.com/share.php?url=${encoded}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {t("SHARE.VK")}
          </a>
        </div>
        <div>
          <a
            className="share-element twitter"
            data-testid="share-twitter"
            href={`https://twitter.com/share?text=${encodeURIComponent("My Flight")}&url=${encoded}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {t("SHARE.TWITTER")}
          </a>
        </div>
        {locale === "zh" && (
          <div>
            <a
              className="share-element weibo"
              data-testid="share-weibo"
              href={`https://service.weibo.com/share/share.php?url=${encoded}`}
              target="_blank"
              rel="noopener noreferrer"
            >
              {t("SHARE.WEIBO")}
            </a>
          </div>
        )}
        <div>
          <a
            className="share-element copy"
            data-testid="share-copy"
            href="#"
            onClick={handleCopy}
          >
            {t("SHARE.COPY")}
          </a>
        </div>
      </div>
    </div>
  );
};
