"use client";

import { useEffect, useState } from "react";
import { X } from "lucide-react";
import type { CrImage } from "@/lib/wp/site";

const LABELS = {
  ar: { aria: "عرض السجل التجاري", alt: "السجل التجاري", close: "إغلاق", title: "الرقم الموحد" },
  en: { aria: "View commercial registration", alt: "Commercial registration", close: "Close", title: "Unified number" },
} as const;

function detectLocale(): "ar" | "en" {
  if (typeof document === "undefined") return "ar";
  return document.documentElement.lang === "en" ? "en" : "ar";
}

interface CommercialRegistrationViewerProps {
  image: CrImage;
  number?: string;
}

/**
 * Footer badge that opens the full commercial-registration image in a
 * lightbox. Esc closes; backdrop click closes; body scroll is locked while
 * open.
 */
export function CommercialRegistrationViewer({ image, number }: CommercialRegistrationViewerProps) {
  const [open, setOpen] = useState(false);
  const [locale, setLocale] = useState<"ar" | "en">("ar");
  useEffect(() => setLocale(detectLocale()), []);
  const labels = LABELS[locale];

  useEffect(() => {
    if (!open) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = previous;
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <>
      <button
        type="button"
        className="cr-badge"
        aria-label={labels.aria}
        onClick={() => setOpen(true)}
      >
        <span className="cr-badge__thumb">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={image.thumb_url || image.url} alt={image.alt || labels.alt} />
        </span>
        <span className="cr-badge__text">
          <span className="cr-badge__title">{labels.title}</span>
          {number ? <span className="cr-badge__num">{number}</span> : null}
        </span>
      </button>

      {open ? (
        <div
          className="cr-lightbox"
          role="dialog"
          aria-modal="true"
          aria-label={labels.alt}
          onClick={(event) => {
            if (event.target === event.currentTarget) setOpen(false);
          }}
        >
          <button
            type="button"
            className="cr-lightbox__close"
            aria-label={labels.close}
            onClick={() => setOpen(false)}
          >
            <X width={18} height={18} aria-hidden />
          </button>
          <div className="cr-lightbox__stage">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={image.url} alt={image.alt || labels.alt} />
          </div>
        </div>
      ) : null}
    </>
  );
}
