import { Browser } from "@capacitor/browser";
import { useRef, useState } from "react";
import { useBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { ForwardIcon, LegalSupportIcon } from "../../shared/ActionIcons.jsx";
import { useOutsideDismiss } from "../../shared/hooks/useOutsideDismiss.js";
import { platformRuntime } from "../../platform/runtime.js";
import { LEGAL_SUPPORT_LINKS, PRODUCT_CONTACT } from "./legal-support.js";

function openOfficialPage(event, url, closeMenu) {
  closeMenu();
  if (!platformRuntime.isNative) return;
  event.preventDefault();
  void Browser.open({ url });
}

export function LegalSupportSection() {
  const { t } = useI18n();
  const [menuOpen, setMenuOpen] = useState(false);
  const controlRef = useRef(null);
  const triggerRef = useRef(null);
  const closeMenu = useBackLayer(menuOpen, () => setMenuOpen(false), "settings-legal-menu");
  useOutsideDismiss(controlRef, closeMenu, menuOpen, { returnFocusRef: triggerRef });

  return <section className="settings-section settings-legal-section" aria-label={t("settings.legalSupport")}>
    <div className="settings-legal-control" ref={controlRef}>
      <button ref={triggerRef} className="settings-action settings-legal-trigger" type="button" aria-haspopup="menu" aria-expanded={menuOpen} onClick={() => menuOpen ? closeMenu() : setMenuOpen(true)}>
        <LegalSupportIcon className="settings-row-icon" /><span>{t("settings.legalSupport")}</span><ForwardIcon className="settings-navigation-chevron" />
      </button>
      {menuOpen && <div className="settings-legal-menu" role="menu" aria-label={t("settings.legalSupport")}>
        <a role="menuitem" href={`mailto:${PRODUCT_CONTACT.email}`} onClick={() => closeMenu()}>
          <span>{t("settings.contactEmail")}</span>
          <strong>{PRODUCT_CONTACT.email}</strong>
        </a>
        {LEGAL_SUPPORT_LINKS.map(({ id, labelKey, url }) => <a role="menuitem" key={id} href={url} target="_blank" rel="noreferrer" onClick={(event) => openOfficialPage(event, url, closeMenu)}>
          <span>{t(labelKey)}</span>
          <span aria-hidden="true">↗</span>
        </a>)}
        <p className="settings-contact-warning">{t("settings.policyEffectiveDate")}: {PRODUCT_CONTACT.policyEffectiveDate}</p>
        <p className="settings-contact-warning">{t("settings.contactWarning")}</p>
      </div>}
    </div>
  </section>;
}
