/**
 * Sandbox URLs must point to your deployed API and connection frontend.
 * Load after these elements; both buttons use the same Meta WhatsApp channel:
 * <button type="button" data-omnizapi-connect>Connect with default flow</button>
 * <button type="button" data-omnizapi-connect data-direct="true">Connect directly</button>
 * <p id="status" role="status"></p>
 * Channel config or the connection frontend origin may select native signup
 * even with direct: false, and direct: true degrades to the proxy flow when
 * this page cannot run the native setup (for example a conflicting or unknown
 * host Meta SDK). Only native login still awaiting its FB.login callback
 * blocks another native attempt: wait for that callback or reload the page.
 * Native signup still needs real-browser testing with the Meta SDK's user gesture.
 */
import Omnizapi, { Environment, OmnizapiError } from "@omnizapi/connect";
import type { OmnizapiClient } from "@omnizapi/connect";

let client: OmnizapiClient | undefined;

if (typeof document !== "undefined") {
  const buttons = document.querySelectorAll<HTMLButtonElement>("[data-omnizapi-connect]");
  const statusElement = document.querySelector<HTMLElement>("#status");

  if (statusElement) {
    buttons.forEach((button) => {
      button.addEventListener("click", async () => {
        if (button.disabled) return;
        buttons.forEach((item) => { item.disabled = true; });
        statusElement.textContent = "Connecting...";

        try {
          client ??= Omnizapi.newClient({
            publicKey: "your-public-key",
            logo: "https://app.example.com/logo.png",
            environment: Environment.SANDBOX,
            apiUrl: "https://api.example.com",
            frontUrl: "https://connect.example.com",
          });
          const result = await client.connect({
            channelId: "your-meta-whatsapp-channel-id",
            direct: button.dataset.direct === "true",
            timeoutMs: 5 * 60 * 1000,
          });

          if (!result.success) {
            statusElement.textContent = `Connection not completed (${result.reason}).`;
            return;
          }

          const response = await fetch("/api/connect-channel", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(result),
          });
          if (!response.ok) {
            statusElement.textContent = "The backend could not finalize the connection.";
            return;
          }

          statusElement.textContent = "Channel connected!";
        } catch (error) {
          statusElement.textContent = error instanceof OmnizapiError
            ? `Connection error (${error.code}). Check the integration before retrying.`
            : "Could not confirm the connection. Check its backend status before retrying.";
        } finally {
          buttons.forEach((item) => { item.disabled = false; });
        }
      });
    });
  }
}
