"use client";

/**
 * Mira widget — drop-in component for Next.js App Router.
 *
 * Mount once, ideally in `app/layout.tsx`, so client-side navigation does not
 * unmount it. The widget bundle is a single IIFE: `next/script` loads it once
 * per page with `strategy="afterInteractive"`. On unmount the component
 * removes the widget host and the globals it published (ref-counted so nested
 * layouts do not tear each other down).
 *
 * Copy this file into your app (e.g. `components/MiraWidget.tsx`).
 */

import Script from "next/script";
import { useEffect } from "react";

/** Shape of `window.MIRA_CONFIG` understood by the widget bundle. */
export interface MiraConfig {
  tenantId?: string;
  apiBase?: string;
  storeUrl?: string;
  customerId?: string;
  name?: string;
  avatar?: string;
  primaryColor?: string;
  greeting?: string;
  position?: "bottom-right" | "bottom-left";
  autoMinimize?: boolean;
  requireConsent?: boolean;
  currency?: string;
  /** Forward-compatible voice toggle; ignored by widget builds without voice UI. */
  voice?: boolean;
}

declare global {
  interface Window {
    MIRA_TENANT_ID?: string;
    MIRA_API_URL?: string;
    MIRA_STORE_URL?: string;
    MIRA_CUSTOMER_ID?: string;
    MIRA_CONFIG?: MiraConfig;
    /** Internal ref count so multiple layout instances share one safe cleanup. */
    __miraWidgetMounts?: number;
  }
}

export interface MiraWidgetProps {
  /** Public tenant id from the Mira dashboard. Required. */
  tenantId: string;
  /** Mira API base URL; defaults to NEXT_PUBLIC_API_URL at build time. */
  apiUrl?: string;
  /** Opaque id of the logged-in shopper; omit for anonymous visitors. */
  customerId?: string;
  position?: "bottom-right" | "bottom-left";
  primaryColor?: string;
  /** Emoji or short text used as the assistant avatar. */
  avatar?: string;
  autoMinimize?: boolean;
  /** Published on window.MIRA_CONFIG; safe with builds that ignore it. */
  voice?: boolean;
}

const SCRIPT_ID = "mira-widget-script";
const HOST_ID = "mira-widget-host";
const MOUNTS_KEY = "__miraWidgetMounts";

const trimTrailingSlashes = (value: string): string => value.replace(/\/+$/, "");

export function MiraWidget({
  tenantId,
  apiUrl = process.env.NEXT_PUBLIC_API_URL ?? "https://api.mira.app",
  customerId,
  position = "bottom-right",
  primaryColor = "#7C5CFC",
  avatar = "🤖",
  autoMinimize = true,
  voice = false,
}: MiraWidgetProps) {
  const apiBase = trimTrailingSlashes(apiUrl);
  const scriptSrc = `${apiBase}/mira-widget.js`;

  useEffect(() => {
    const w = window;
    if (!tenantId) return;

    // Publish configuration before the script executes.
    w[MOUNTS_KEY] = (w[MOUNTS_KEY] ?? 0) + 1;
    w.MIRA_TENANT_ID = tenantId;
    w.MIRA_API_URL = apiBase;
    w.MIRA_STORE_URL = w.location.origin;

    if (customerId) w.MIRA_CUSTOMER_ID = customerId;
    else delete w.MIRA_CUSTOMER_ID;

    w.MIRA_CONFIG = {
      ...w.MIRA_CONFIG,
      tenantId,
      apiBase,
      storeUrl: w.location.origin,
      ...(customerId ? { customerId } : {}),
      position,
      primaryColor,
      avatar,
      autoMinimize,
      voice,
    };

    return () => {
      const remaining = Math.max(0, (w[MOUNTS_KEY] ?? 1) - 1);
      w[MOUNTS_KEY] = remaining;
      if (remaining === 0) {
        delete w[MOUNTS_KEY];
        document.getElementById(HOST_ID)?.remove();
        delete w.MIRA_CONFIG;
        delete w.MIRA_TENANT_ID;
        delete w.MIRA_API_URL;
        delete w.MIRA_STORE_URL;
        delete w.MIRA_CUSTOMER_ID;
      }
    };
  }, [tenantId, apiBase, customerId, position, primaryColor, avatar, autoMinimize, voice]);

  if (!tenantId) return null;

  return (
    <Script
      id={SCRIPT_ID}
      src={scriptSrc}
      strategy="afterInteractive"
      // Data attributes mirror MIRA_CONFIG so the current widget bundle also
      // applies branding without a remote config round-trip.
      data-tenant={tenantId}
      data-api={apiBase}
      data-position={position}
      data-color={primaryColor}
      data-avatar={avatar}
      data-auto-minimize={autoMinimize ? "true" : "false"}
    />
  );
}

export default MiraWidget;
