// components/download-buttons.jsx
// <DownloadIntentButtons> per Section 3.10. Two custom Fanish-branded peach pill
// buttons. NOT the official Apple App Store / Google Play badges.
//
// Behavior gated by COPY.isLaunched:
//   isLaunched: false  → opens <DownloadIntentModal>, fires *_button_click event
//   isLaunched: true   → navigates to App Store / Google Play, fires app_store_redirect

function DownloadIntentButtons({ source, onIntent, fullWidth }) {
  const C = window.COPY;
  const evName =
    source === "hero" ? "hero_download_button_click"
    : source === "final_cta" ? "final_cta_download_button_click"
    : "header_cta_click";

  // iOS is live → the badge is a real <a> to the App Store; we only fire
  // tracking and let the anchor navigate. Pre-launch (or missing URL) we
  // preventDefault and fall back to the modal / prototype alert.
  const iosLive = C.iosLaunched && C.cta.appStoreUrl;
  const onIos = (e) => {
    window.trackEvent(evName, { source, platform: "ios" });
    if (iosLive) {
      window.trackEvent("app_store_redirect", { source, platform: "ios" });
      // anchor href handles the navigation
    } else {
      e.preventDefault();
      if (C.iosLaunched) alert("(prototype) Would navigate to: App Store");
      else onIntent(source, "ios");
    }
  };

  // Android not yet live → open the "coming soon" modal (social-follow path).
  const onAndroid = () => {
    window.trackEvent(evName, { source, platform: "android" });
    if (C.androidLaunched && C.cta.googlePlayUrl) {
      window.trackEvent("app_store_redirect", { source, platform: "android" });
      window.location.href = C.cta.googlePlayUrl;
    } else {
      onIntent(source, "android");
    }
  };

  return (
    <div className={"dl-row dl-row-launch" + (fullWidth ? " dl-row-full" : "")}>
      <a
        className="appstore-badge"
        href={iosLive ? C.cta.appStoreUrl : "#"}
        onClick={onIos}
        data-track={evName}
        aria-label="Download Fanish on the App Store"
      >
        <span className="appstore-badge-apple"><IconApple /></span>
        <span className="appstore-badge-txt">
          <span className="appstore-badge-small">Download on the</span>
          <span className="appstore-badge-big">App Store</span>
        </span>
      </a>
      <button
        type="button"
        className="android-secondary"
        data-track={evName}
        onClick={onAndroid}
        aria-label="Android coming soon — follow for updates"
      >
        <span>Android coming soon</span>
        <span className="android-secondary-arrow" aria-hidden="true">›</span>
      </button>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// <DownloadIntentModal>. Section 3.11. Renders pre-launch only.
// Per-platform variant: iOS launches June 1, Android coming later.
// Both variants list the event chips that moved out of the hero.

function DownloadIntentModal({ source, platform = "android", onClose }) {
  const C = window.COPY;
  const headlineRef = React.useRef(null);
  const triggerRef = React.useRef(null);
  const variant = C.modal[platform] || C.modal.android;

  React.useEffect(() => {
    triggerRef.current = document.activeElement;
    window.trackEvent("download_intent_modal_shown", { source, platform });

    document.body.style.overflow = "hidden";

    // Move focus to headline. Delay so the dialog is mounted.
    setTimeout(() => { if (headlineRef.current) headlineRef.current.focus(); }, 50);

    const onKey = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        dismiss("esc");
      }
      if (e.key === "Tab") {
        // Simple focus trap. Keep tab inside the dialog.
        const dialog = document.getElementById("dl-modal");
        if (!dialog) return;
        const focusables = dialog.querySelectorAll(
          'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])'
        );
        if (!focusables.length) return;
        const first = focusables[0];
        const last = focusables[focusables.length - 1];
        if (e.shiftKey && document.activeElement === first) {
          e.preventDefault(); last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault(); first.focus();
        }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
      if (triggerRef.current && triggerRef.current.focus) triggerRef.current.focus();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const dismiss = (method) => {
    window.trackEvent("download_intent_modal_dismissed", { source, dismiss_method: method });
    onClose();
  };

  const followClick = (platform) => {
    window.trackEvent("download_intent_social_follow_click", { source, platform });
    const url = platform === "instagram" ? C.modal.instagramUrl : C.modal.tiktokUrl;
    window.open(url, "_blank", "noopener,noreferrer");
  };

  const onBackdrop = (e) => { if (e.target === e.currentTarget) dismiss("backdrop"); };

  return (
    <div className="modal-backdrop" onClick={onBackdrop}>
      <div
        id="dl-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="dl-modal-headline"
        className="modal-card"
      >
        <button
          type="button"
          className="modal-x"
          onClick={() => dismiss("x_button")}
          aria-label="Close modal"
        >
          <IconClose />
        </button>

        <h2
          id="dl-modal-headline"
          ref={headlineRef}
          tabIndex={-1}
          className="modal-headline"
        >
          {variant.headline}
        </h2>
        <p className="modal-body">{variant.body}</p>

        {C.modal.events && C.modal.events.length > 0 && (
          <div className="modal-events" aria-label="Events at launch">
            {C.modal.events.map((ev) => (
              <span key={ev.name} className="modal-event">
                <span className="modal-event-name">{ev.name}</span>
                <span className="modal-event-dates">{ev.dates}</span>
              </span>
            ))}
          </div>
        )}

        <div className="modal-cta-row">
          <button
            type="button"
            className="dl-btn"
            data-track="download_intent_social_follow_click"
            onClick={() => followClick("instagram")}
          >
            <span className="dl-btn-icon"><IconInstagram size={18} /></span>
            <span>{C.modal.instagram}</span>
          </button>
          <button
            type="button"
            className="dl-btn"
            data-track="download_intent_social_follow_click"
            onClick={() => followClick("tiktok")}
          >
            <span className="dl-btn-icon"><IconTikTok size={18} /></span>
            <span>{C.modal.tiktok}</span>
          </button>
        </div>

        <button
          type="button"
          className="modal-close-link"
          data-track="download_intent_modal_dismissed"
          onClick={() => dismiss("close_link")}
        >
          {C.modal.closeLink}
        </button>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// <ContactLink>. Section 9.2.1. mailto with clipboard-copy fallback + toast.

function ContactLink({ children, source = "footer", className = "contact-link" }) {
  const C = window.COPY;
  const [toast, setToast] = React.useState(false);

  const onClick = (e) => {
    window.trackEvent("contact_link_click", { source });
    // Try mailto. If that fails or is blocked, copy to clipboard.
    // Most browsers will silently swallow a blocked mailto, so we copy anyway as a fallback affordance.
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(C.contactEmail).then(
          () => { setToast(true); setTimeout(() => setToast(false), 2400); },
          () => {}
        );
      }
    } catch (err) { /* noop */ }
    // Allow the mailto: navigation to proceed.
  };

  return (
    <>
      <a
        href={`mailto:${C.contactEmail}`}
        onClick={onClick}
        data-track="contact_link_click"
        className={className}
      >
        {children || C.contactEmail}
      </a>
      {toast && <div className="toast" role="status" aria-live="polite">Email copied to clipboard.</div>}
    </>
  );
}

Object.assign(window, { DownloadIntentButtons, DownloadIntentModal, ContactLink });
