"use client";

import { useEffect, useState } from "react";
import QRCode from "qrcode";

interface RealQRCodeProps {
  url: string;
  size?: number;
  className?: string;
}

export default function RealQRCode({ url, size = 220, className = "" }: RealQRCodeProps) {
  const [src, setSrc] = useState<string>("");
  const [error, setError] = useState(false);

  useEffect(() => {
    if (!url) return;
    QRCode.toDataURL(url, {
      width: size * 2,         // 2x for retina sharpness
      margin: 2,
      errorCorrectionLevel: "H", // highest — tolerates up to 30% damage, more robust
      color: {
        dark: "#000000",         // pure black modules for maximum camera contrast
        light: "#FFFFFF",
      },
    })
      .then((dataUrl) => setSrc(dataUrl))
      .catch(() => setError(true));
  }, [url, size]);

  if (error) {
    return (
      <div
        className={`flex items-center justify-center bg-sage text-ink-soft text-xs text-center p-4 rounded-sm ${className}`}
        style={{ width: size, height: size }}
      >
        Could not generate QR code
      </div>
    );
  }

  if (!src) {
    return (
      <div
        className={`flex items-center justify-center bg-sage rounded-sm ${className}`}
        style={{ width: size, height: size }}
      >
        <div className="w-6 h-6 border-2 border-forest border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt={`QR code — scan with your phone camera to open: ${url}`}
      width={size}
      height={size}
      className={`block rounded-sm ${className}`}
      style={{ imageRendering: "pixelated" }} // keeps QR modules sharp at any display size
    />
  );
}
