// src/components/LogoCard.tsx
import React, { useMemo, useState } from "react";
import { normalizeSvg } from "../utils/normalizeSvg";

type LogoCardProps = {
  title: string;
  /** Can be a data URL, remote URL, or raw SVG string */
  source: string;
  /** Optional click behavior (e.g., set as primary) */
  onPrimary?: () => void;
  /** Optional favorite toggle */
  onFavorite?: () => void;
  /** Optional download handler */
  onDownload?: () => void;
};

function isLikelySvg(text: string) {
  if (!text) return false;
  if (text.trim().startsWith("<svg")) return true;
  if (/^data:image\/svg\+xml/i.test(text)) return true;
  if (/\.(svg)(\?|#|$)/i.test(text)) return true;
  return false;
}

export const LogoCard: React.FC<LogoCardProps> = ({
  title,
  source,
  onPrimary,
  onFavorite,
  onDownload,
}) => {
  const [zoom, setZoom] = useState(100); // percent

  const { renderType, normalizedSvg, imgSrc } = useMemo(() => {
    if (isLikelySvg(source)) {
      let raw = source;
      // If it's a data URL, decode for normalization then re-encode
      if (/^data:image\/svg\+xml/i.test(source)) {
        try {
          const comma = source.indexOf(",");
          const payload = source.slice(comma + 1);
          const svgDecoded = decodeURIComponent(payload);
          raw = svgDecoded;
        } catch {
          // best-effort; fall back to original
        }
      }
      const fixed = normalizeSvg(raw);

      // Use data URL so <img> fallback routes can download easily if needed
      const dataUrl =
        "data:image/svg+xml;charset=utf-8," + encodeURIComponent(fixed);

      return { renderType: "svg" as const, normalizedSvg: fixed, imgSrc: dataUrl };
    }

    // Raster path (png/jpg/webp)
    return { renderType: "img" as const, normalizedSvg: "", imgSrc: source };
  }, [source]);

  const openFull = () => {
    // Open full-size in a new tab (helps debugging and saves users)
    const win = window.open();
    if (!win) return;
    if (renderType === "svg") {
      win.document.write(`<html><head><title>${title}</title></head><body style="margin:0;background:#111;display:grid;place-items:center;">
      ${normalizedSvg.replace(
        "<svg",
        `<svg style="width:90vmin;height:90vmin;display:block"`
      )}
      </body></html>`);
      win.document.close();
    } else {
      win.document.write(
        `<html><head><title>${title}</title></head><body style="margin:0;background:#111;display:grid;place-items:center;">
         <img src="${imgSrc}" style="max-width:90vmin;max-height:90vmin;display:block" />
         </body></html>`
      );
      win.document.close();
    }
  };

  return (
    <div className="group rounded-2xl border border-neutral-200 bg-white/70 shadow-sm hover:shadow-md transition-shadow">
      <div className="flex items-center justify-between px-3 pt-3">
        <div className="truncate text-sm font-medium text-neutral-700" title={title}>
          {title}
        </div>
        <div className="flex items-center gap-2">
          <button
            className="text-xs px-2 py-1 rounded-md border hover:bg-neutral-50"
            onClick={onFavorite}
            title="Favorite"
          >
            ★
          </button>
          <button
            className="text-xs px-2 py-1 rounded-md border hover:bg-neutral-50"
            onClick={onPrimary}
            title="Set as primary"
          >
            📌
          </button>
          <button
            className="text-xs px-2 py-1 rounded-md border hover:bg-neutral-50"
            onClick={onDownload}
            title="Download"
          >
            ⬇
          </button>
        </div>
      </div>

      {/* Preview frame */}
      <div
        className="relative mx-3 my-3 rounded-xl overflow-hidden"
        style={{
          aspectRatio: "1 / 1",
          background:
            "conic-gradient(#f8fafc 25%, #f1f5f9 0 50%, #f8fafc 0 75%, #f1f5f9 0) 0 0/16px 16px",
        }}
      >
        <div
          className="absolute inset-2 rounded-lg bg-white/90 grid place-items-center"
          title="Click to open full size"
          onClick={openFull}
          role="button"
        >
          {/* Inner canvas with zoom support */}
          <div
            className="w-full h-full grid place-items-center"
            style={{
              transform: `scale(${zoom / 100})`,
              transformOrigin: "center",
            }}
          >
            {renderType === "svg" ? (
              // Render normalized SVG safely
              <div
                className="w-[90%] h-[90%]"
                // eslint-disable-next-line react/no-danger
                dangerouslySetInnerHTML={{
                  __html: normalizedSvg.replace(
                    "<svg",
                    `<svg width="100%" height="100%"`
                  ),
                }}
              />
            ) : (
              <img
                src={imgSrc}
                alt={title}
                className="max-w-[90%] max-h-[90%] object-contain"
                draggable={false}
              />
            )}
          </div>
        </div>

        {/* Zoom slider */}
        <div className="absolute left-3 right-3 bottom-3 flex items-center gap-2">
          <input
            type="range"
            min={50}
            max={200}
            value={zoom}
            onChange={(e) => setZoom(Number(e.target.value))}
            className="w-full accent-neutral-700"
          />
          <div className="text-[11px] text-neutral-600 w-10 text-right">{zoom}%</div>
        </div>
      </div>
    </div>
  );
};
