// Sticker label component — renders the physical product sticker with QR code.
// Used in both Admin (preview + sheet print) and warranty (showing what they got).

function QRCode({ value, size = 80, fg = "#0a0a0b", bg = "transparent" }) {
  const qr = React.useMemo(() => {
    try { return window.ADRO_qr(value || "https://warranty.adro.com"); }
    catch (e) { return null; }
  }, [value]);
  if (!qr) return <div style={{ width: size, height: size, background: "#222" }} />;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${qr.size} ${qr.size}`} shapeRendering="crispEdges" style={{ display: "block" }}>
      {bg !== "transparent" && <rect width={qr.size} height={qr.size} fill={bg} />}
      <path d={qr.d} fill={fg} />
    </svg>
  );
}

// One sticker. Sizes & toggles drive layout. Always white/black for print fidelity.
function Sticker({
  product,
  ttg,
  sn,
  country,                     // ISO-2, e.g. "US"
  date,                        // YYYY-MM-DD or Date
  size = "M",                  // S / M / L / XL
  fields = { name: true, sku: true, ttg: true, sn: true, qr: true, logo: true, country: true, date: true },
  font = "default",            // default | condensed | mono
  highlight = "red",           // red | none | accent
}) {
  const dateStr = React.useMemo(() => {
    if (!date) return "";
    const d = date instanceof Date ? date : new Date(date);
    if (isNaN(d)) return String(date);
    const y = String(d.getFullYear()).slice(2);
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    return `${y}.${m}.${dd}`;
  }, [date]);
  const dims = {
    S:  { w: 38.1, h: 23.5, padX: 1.6, padY: 1.6, qr: 8,  logoH: 2.8 },
    M:  { w: 60,   h: 40,   padX: 2.5, padY: 2.5, qr: 13, logoH: 3.6 },
    L:  { w: 90,   h: 55,   padX: 3.5, padY: 3.5, qr: 22, logoH: 4.6 },
    XL: { w: 100,  h: 65,   padX: 4,   padY: 4,   qr: 23, logoH: 5 },
  }[size];

  const fontFamily = {
    default: "'Inter', system-ui, sans-serif",
    condensed: "'Anton', 'Bebas Neue', 'Arial Narrow', sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  }[font];

  const qrPayload = `https://warranty.adro.com/?sn=${sn}`;

  // Scale all internal sizes to mm using a base
  const mm = (v) => `${v}mm`;

  return (
    <div style={{
      width: mm(dims.w), height: mm(dims.h),
      background: "#fff", color: "#0a0a0b",
      borderRadius: "1mm",
      padding: `${dims.padY}mm ${dims.padX}mm`,
      display: "flex", flexDirection: "column", justifyContent: "space-between",
      fontFamily,
      position: "relative",
      boxSizing: "border-box",
      boxShadow: "0 0 0 0.2mm rgba(0,0,0,0.08)",
    }}>
      {/* Top: logo + product line */}
      {fields.logo && (
        <div style={{ display: "flex", alignItems: "center", gap: "1.2mm" }}>
          <AdroMark height={dims.logoH} />
          {highlight === "red" && (
            <div style={{ flex: 1, height: "0.4mm", background: "#e0201c" }} />
          )}
          <div style={{ fontSize: `${dims.logoH * 0.55}mm`, fontWeight: 600, letterSpacing: "0.04em", color: "#888", textTransform: "uppercase" }}>
            MADE IN KOREA
          </div>
        </div>
      )}

      {/* Middle row: name + QR */}
      <div style={{ display: "flex", gap: `${dims.padX}mm`, flex: 1, alignItems: "stretch", marginTop: "0.6mm" }}>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", minWidth: 0 }}>
          {fields.sku && (
            <div style={{
              fontSize: size === "S" ? "2.6mm" : size === "M" ? "4.5mm" : "5.5mm",
              fontWeight: 800,
              letterSpacing: "0.02em",
              lineHeight: 1,
              fontFamily: font === "default" ? "'Anton', 'Bebas Neue', sans-serif" : fontFamily,
            }}>
              {product?.sku || "—"}
            </div>
          )}
          {fields.name && (
            <div style={{
              fontSize: size === "S" ? "1.6mm" : size === "M" ? "2.3mm" : "2.8mm",
              fontWeight: 600, color: "#222", lineHeight: 1.15,
              marginTop: "0.4mm",
              textWrap: "pretty",
            }}>
              {product?.line} {product?.name}
            </div>
          )}
          {product?.note && size !== "S" && (
            <div style={{ fontSize: size === "M" ? "1.5mm" : "1.8mm", color: "#888", marginTop: "0.3mm", letterSpacing: "0.03em" }}>
              {product.note}
            </div>
          )}
        </div>

        {fields.qr && (
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "center",
            padding: "0.4mm", borderRadius: "0.6mm",
            background: "#fff",
          }}>
            <QRCode value={qrPayload} size={`${dims.qr}mm`} />
          </div>
        )}
      </div>

      {/* Bottom: meta row (date only) + TTG + SN */}
      {fields.date && dateStr && (
        <div style={{
          display: "flex", justifyContent: "flex-end", alignItems: "center",
          gap: "1mm", marginTop: "0.4mm",
          fontSize: size === "S" ? "1.3mm" : "1.7mm",
          color: "#666",
          letterSpacing: "0.04em",
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontWeight: 500,
        }}>
          <span><span style={{ color: "#999", fontWeight: 600 }}>DATE</span> {dateStr}</span>
        </div>
      )}

      {/* Bottom: TTG + SN */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        gap: "1mm", marginTop: "0.6mm",
        borderTop: highlight === "red" ? "0.3mm solid #e0201c" : "0.2mm solid #ddd",
        paddingTop: "0.6mm",
      }}>
        {fields.ttg && (
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
            <span style={{ fontSize: size === "S" ? "1.2mm" : "1.6mm", color: "#888", letterSpacing: "0.06em", fontWeight: 600 }}>TTG</span>
            <span style={{
              fontSize: size === "S" ? "1.8mm" : "2.4mm",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontWeight: 600,
            }}>{ttg}</span>
          </div>
        )}
        {fields.sn && (
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1, textAlign: "right" }}>
            <span style={{ fontSize: size === "S" ? "1.2mm" : "1.6mm", color: "#888", letterSpacing: "0.06em", fontWeight: 600 }}>S/N</span>
            <span style={{
              fontSize: size === "S" ? "2mm" : "2.8mm",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontWeight: 700,
            }}>{window.ADRO_formatSN(sn)}</span>
          </div>
        )}
      </div>
    </div>
  );
}

// Wrapper that measures available width and CSS-scales the sticker to fit.
// Use whenever a Sticker is shown in a flexible UI container (preview pane).
function StickerFit({ children, maxWidth = 360 }) {
  const ref = React.useRef(null);
  const inner = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  const [innerSize, setInnerSize] = React.useState({ w: 0, h: 0 });

  React.useLayoutEffect(() => {
    const measure = () => {
      if (!ref.current || !inner.current) return;
      const avail = Math.min(ref.current.clientWidth, maxWidth);
      const child = inner.current.firstElementChild;
      if (!child) return;
      const rect = child.getBoundingClientRect();
      // Read intrinsic via reset-then-measure to avoid feedback loops
      const naturalW = rect.width / (scale || 1);
      const naturalH = rect.height / (scale || 1);
      const next = avail > 0 ? Math.min(1, avail / naturalW) : 1;
      if (Math.abs(next - scale) > 0.01) setScale(next);
      setInnerSize({ w: naturalW * next, h: naturalH * next });
    };
    measure();
    const ro = new ResizeObserver(measure);
    if (ref.current) ro.observe(ref.current);
    return () => ro.disconnect();
    // eslint-disable-next-line
  }, [children]);

  return (
    <div ref={ref} style={{ width: "100%", display: "flex", justifyContent: "center" }}>
      <div style={{ width: innerSize.w || "auto", height: innerSize.h || "auto" }}>
        <div ref={inner} style={{ transform: `scale(${scale})`, transformOrigin: "top left", display: "inline-block" }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function AdroMark({ height = 4, color = "#0a0a0b" }) {
  // Real ADRO logo — width follows native 2.81:1 aspect ratio
  return (
    <img
      src="assets/adro-logo.png"
      alt="ADRO"
      style={{
        height: `${height}mm`,
        width: "auto",
        display: "block",
        // Recolor black PNG via filter when needed (default keeps it black)
        filter: color === "#0a0a0b" ? "none" : "brightness(0) invert(1)",
      }}
    />
  );
}

Object.assign(window, { Sticker, StickerFit, QRCode, AdroMark });
