"use client";

import { useTranslations } from "next-intl";
import { useEffect } from "react";
import { THREEMA_GATEWAY } from "@/lib/threema-gateway-config";

interface ThreemaQrModalProps {
  open: boolean;
  onClose: () => void;
}

/**
 * On-demand modal showing the QR for adding the assistant on Threema.
 * Triggered by the "Show QR" button in the threema channel card and
 * closes on overlay click, ESC, or the close button.
 *
 * Uses a plain <img> not next/image — image optimization adds nothing
 * for a 57KB static PNG and removes a potential source of rendering
 * bugs in the Next.js standalone build.
 */
export function ThreemaQrModal({ open, onClose }: ThreemaQrModalProps) {
  const t = useTranslations("channelUsers.threemaSetup");

  useEffect(() => {
    if (!open) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-md bg-surface-1 border border-border rounded-2xl p-6 shadow-2xl shadow-black/40 space-y-4"
      >
        <div className="flex items-start justify-between">
          <h3 className="text-base font-semibold text-text-primary">
            {t("title")}
          </h3>
          <button
            onClick={onClose}
            className="text-text-muted hover:text-text-primary text-xl leading-none"
            aria-label="Close"
          >
            ×
          </button>
        </div>

        <div className="flex justify-center">
          <div className="bg-white p-3 rounded-md">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={THREEMA_GATEWAY.qrCodePath}
              alt={t("qrAlt", { gateway: THREEMA_GATEWAY.displayName })}
              width={220}
              height={220}
              style={{ display: "block" }}
            />
          </div>
        </div>

        <p className="text-center text-xs text-text-muted font-mono">
          {THREEMA_GATEWAY.displayName}
        </p>

        <ol className="list-decimal list-inside text-xs text-text-secondary space-y-1.5">
          <li>{t("step1")}</li>
          <li>{t("step2")}</li>
          <li>{t("step3")}</li>
        </ol>
      </div>
    </div>
  );
}
