// Order.jsx — "Order a print" flow.
//
// The customer designs the poster themselves, then this modal:
//   1. generates a short design code (e.g. LPS-7F3K2),
//   2. renders 300 DPI print files named after the code and downloads them
//      as the customer's backup copy,
//   3. uploads the design JSON + print PNG to the shop's print queue
//      (Cloudflare Pages Functions + R2) keyed by the same code,
//   4. sends the customer to the shop listing, where the code goes in the
//      "Personalisation" field at checkout.
// If the upload can't reach the queue, the downloaded files become the master
// copies and the modal tells the customer to message them after ordering.
//
// We are a printing service for customer-created designs. The rights
// confirmation below is required before any files are generated.

const ORDER_CONFIG = {
  shopUrl: "https://www.etsy.com/listing/4535309714/custom-song-lyrics-print-design-your-own",
  shopLabel: "Open the Etsy listing",
  // Same-origin Pages Functions ("/api"). Set to "" to disable uploads and
  // fall back to the manual message-us-the-files flow. window.LPS_API_BASE
  // overrides for local testing.
  apiBase: (typeof window !== "undefined" && window.LPS_API_BASE !== undefined) ? window.LPS_API_BASE : "/api",
};

function generateDesignCode() {
  // Unambiguous alphabet (no 0/O, 1/I/L)
  const abc = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
  let s = "";
  for (let i = 0; i < 5; i++) s += abc[Math.floor(Math.random() * abc.length)];
  return `LPS-${s}`;
}

const STATUS_LABEL = {
  render: "Rendering print files…",
  "save-design": "Saving your design to the print queue…",
  "save-print": "Uploading the print file…",
};

function OrderModal({ open, onClose, width, height, sizeKey, layout, photo, onOrder }) {
  const { useState, useEffect } = React;
  const [agreed, setAgreed] = useState(false);
  const [code, setCode] = useState(null);
  const [busy, setBusy] = useState(false);
  const [statusStep, setStatusStep] = useState(null);
  const [result, setResult] = useState(null);
  const [copied, setCopied] = useState(false);
  const [photoDims, setPhotoDims] = useState(null);

  // Fresh form every time the modal opens — the design may have changed, so a
  // previous code must not be reused (each code maps to one stored design).
  useEffect(() => {
    if (open) {
      setAgreed(false);
      setCode(null);
      setResult(null);
      setBusy(false);
      setStatusStep(null);
      setCopied(false);
    }
  }, [open]);

  // Measure the artwork photo so we can warn about soft prints at big sizes
  useEffect(() => {
    if (!open || !photo) { setPhotoDims(null); return; }
    const img = new Image();
    img.onload = () => setPhotoDims({ w: img.width, h: img.height });
    img.src = photo;
  }, [open, photo]);

  if (!open) return null;

  // Player art fills ~the poster width; the vinyl label is ~30% of it.
  const photoUsed = photo && (layout === "player" || layout === "vinyl");
  const neededPx = width * 11.811 * (layout === "player" ? 0.92 : 0.3);
  const photoMax = photoDims ? Math.max(photoDims.w, photoDims.h) : null;
  const photoSoft = photoUsed && photoMax && photoMax < neededPx * 0.6;

  const start = async () => {
    const c = generateDesignCode();
    setBusy(true);
    const res = await onOrder(c, setStatusStep);
    setBusy(false);
    setStatusStep(null);
    if (res && res.ok) {
      setResult(res);
      setCode(c);
    }
  };
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    });
  };

  const savedToQueue = result && result.saved;

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(20,18,14,.45)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 440, maxWidth: "100%", maxHeight: "90vh", overflow: "auto",
          background: "white", borderRadius: 8, padding: "22px 24px",
          boxShadow: "0 30px 80px rgba(0,0,0,.3)",
        }}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
          <div style={{ fontSize: 16, fontWeight: 700 }}>Order a print</div>
          <button onClick={onClose} style={{ background: "none", border: "none", fontSize: 16, color: "#999", cursor: "pointer" }}>✕</button>
        </div>
        <div style={{ fontSize: 11, color: "#888", fontFamily: '"JetBrains Mono", monospace', marginBottom: 14 }}>
          {width} × {height} mm · {sizeKey} · 300 DPI
        </div>

        {!code ? (
          <>
            <ol style={{ margin: "0 0 14px", paddingLeft: 20, fontSize: 13, lineHeight: 1.6, color: "#333" }}>
              <li>We generate your <b>design code</b>, save your design to our print queue, and download backup copies to your device.</li>
              <li>Buy the print size you want in our shop and paste the code into the <b>Personalisation</b> box at checkout.</li>
              <li>That's it — we print from your saved design and post it to your Etsy address.</li>
            </ol>
            {photoSoft && (
              <div style={{ background: "#fdf3da", border: "1px solid #e8c96a", borderRadius: 6, padding: "9px 12px", fontSize: 11.5, lineHeight: 1.5, color: "#5a4a1a", marginBottom: 12 }}>
                <b>Heads-up on your photo:</b> it's {photoMax}px on its longest side, which may
                print soft at {sizeKey === "Custom" ? "this size" : sizeKey}. It'll look sharpest
                at a smaller print size — or swap in a higher-resolution photo before ordering.
              </div>
            )}
            <label style={{ display: "flex", gap: 8, alignItems: "flex-start", background: "#f7f7f5", borderRadius: 6, padding: "10px 12px", cursor: "pointer", marginBottom: 14 }}>
              <input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} style={{ marginTop: 2 }} />
              <span style={{ fontSize: 11.5, lineHeight: 1.5, color: "#444" }}>
                This is my own design and I have the right to use its text and imagery
                for a personal print. I understand this shop prints customer-created
                files and doesn't sell or reproduce third-party artwork.
              </span>
            </label>
            <button
              onClick={start}
              disabled={!agreed || busy}
              style={{
                width: "100%", padding: "11px 14px", fontSize: 13, fontWeight: 600,
                fontFamily: "inherit", borderRadius: 6, cursor: agreed && !busy ? "pointer" : "default",
                border: "1px solid #c8262a",
                background: agreed && !busy ? "#c8262a" : "#e8b5b6",
                color: "white",
              }}
            >
              {busy ? (STATUS_LABEL[statusStep] || "Working…") : "Generate my code & save my design"}
            </button>
            <div style={{ fontSize: 10, color: "#999", marginTop: 10, lineHeight: 1.5 }}>
              Large sizes can take a few seconds to render. Your design is stored only
              so we can print your order.
            </div>
          </>
        ) : (
          <>
            <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
              <div style={{ fontSize: 11, color: "#888", letterSpacing: ".12em", textTransform: "uppercase", marginBottom: 8 }}>Your design code</div>
              <div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 30, fontWeight: 700, letterSpacing: ".06em" }}>{code}</div>
              <button
                onClick={copy}
                style={{ marginTop: 8, padding: "5px 14px", fontSize: 11, fontFamily: "inherit", borderRadius: 999, border: "1px solid #d8d8d6", background: "white", cursor: "pointer" }}
              >
                {copied ? "Copied ✓" : "Copy code"}
              </button>
            </div>

            {savedToQueue ? (
              <div style={{ background: "#e9f2e8", border: "1px solid #9dbb98", borderRadius: 6, padding: "10px 12px", fontSize: 12, lineHeight: 1.6, color: "#1f3526", margin: "14px 0" }}>
                <b>✓ Design saved to our print queue{result.savedPng ? " (with print file)" : ""}.</b> Just
                order with <b>{code}</b> in the Personalisation box — nothing else to send.
                Backup copies downloaded to your device too.
              </div>
            ) : (
              <div style={{ background: "#fdf3da", border: "1px solid #e8c96a", borderRadius: 6, padding: "10px 12px", fontSize: 12, lineHeight: 1.6, color: "#5a4a1a", margin: "14px 0" }}>
                <b>We couldn't reach the print queue</b>, so the files downloading now
                (<b>{code}-…png</b> and <b>{code}.json</b>) are the master copies. Order with
                <b> {code}</b> in the Personalisation box, then <b>message us the files</b> on Etsy.
              </div>
            )}

            <a
              href={ORDER_CONFIG.shopUrl}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: "block", textAlign: "center", padding: "11px 14px",
                fontSize: 13, fontWeight: 600, borderRadius: 6,
                background: "#1a1a1a", color: "white", textDecoration: "none",
              }}
            >
              {ORDER_CONFIG.shopLabel} →
            </a>
            <button
              onClick={onClose}
              style={{ width: "100%", marginTop: 8, padding: "9px 14px", fontSize: 12, fontFamily: "inherit", borderRadius: 6, border: "1px solid #d8d8d6", background: "white", cursor: "pointer" }}
            >
              Done
            </button>
          </>
        )}
      </div>
    </div>
  );
}

window.OrderModal = OrderModal;
window.ORDER_CONFIG = ORDER_CONFIG;
