/**
 * Load as a browser module after these elements:
 * <button id="connect-btn" type="button">Connect channel</button>
 * <p id="status" role="status"></p>
 * /api/connect-channel is your authenticated backend, not an SDK route.
 */
import Omnizapi, { OmnizapiError } from "@omnizapi/connect";
import type { OmnizapiClient } from "@omnizapi/connect";

let client: OmnizapiClient | undefined;

if (typeof document !== "undefined") {
  const button = document.querySelector<HTMLButtonElement>("#connect-btn");
  const statusElement = document.querySelector<HTMLElement>("#status");

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

      try {
        client ??= Omnizapi.newClient({ publicKey: "your-public-key" });
        const result = await client.connect({ channelId: "your-channel-id" });

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

        // Includes channelId. Never log credentials; validate them on the server.
        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 {
        button.disabled = false;
      }
    });
  }
}
