"use client";

import { useEffect, useRef } from "react";

declare global {
  interface Window {
    Trustpilot?: {
      loadFromElement: (element: HTMLElement | null, forceReload?: boolean) => void;
    };
  }
}

interface TrustpilotWidgetProps {
  locale?: string;
}

/**
 * Renders the Trustpilot "Review Collector" TrustBox.
 * The bootstrap script (loaded in `ClientLayoutAddons`) mounts widgets present
 * in the DOM at load time only — on client-side route changes we re-invoke
 * `Trustpilot.loadFromElement` ourselves, polling briefly in case the
 * bootstrap script hasn't finished loading yet.
 */
export default function TrustpilotWidget({ locale = "en-US" }: TrustpilotWidgetProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const tryLoad = () => {
      if (window.Trustpilot && ref.current) {
        window.Trustpilot.loadFromElement(ref.current, true);
        return true;
      }
      return false;
    };

    if (tryLoad()) return;

    const interval = setInterval(() => {
      if (tryLoad()) clearInterval(interval);
    }, 400);

    return () => clearInterval(interval);
  }, [locale]);

  return (
    <div
      ref={ref}
      className="trustpilot-widget azzle-footer-trustpilot-box"
      data-locale={locale}
      data-template-id="56278e9abfbbba0bdcd568bc"
      data-businessunit-id="69eeb3548f6ce4ecc37e399d"
      data-style-height="52px"
      data-style-width="100%"
      data-theme="dark"
      data-token="83911cf0-8d17-404e-851f-7747c5d654da"
    >
      <a href="https://www.trustpilot.com/review/skylightchat.com" target="_blank" rel="noopener noreferrer">
        Trustpilot
      </a>
    </div>
  );
}
