/* ============================================================
   Shared GayCard visuals — used on landing, checkout, certificate
   Exposes to window: PrideFlag, Barcode, GayCardVisual,
   LetterDocument, QRCode, buildLetter, makeMemberNo
   ============================================================ */

/* ---- Waving pride flag (6 stripes) ---- */
function PrideFlag({ width = 64, style = {} }) {
  const colors = ["#E40303", "#FF8C00", "#FFCE00", "#1FA63A", "#1257FF", "#8B14C9"];
  const h = width * 0.66;
  const band = h / 6;
  return (
    <svg viewBox={`0 0 100 66`} width={width} height={h} style={style} aria-label="Bandeira do orgulho">
      <defs>
        <clipPath id="flagwave">
          <path d="M0,4 C25,-3 75,11 100,3 L100,66 C75,74 25,60 0,68 Z" />
        </clipPath>
      </defs>
      <g clipPath="url(#flagwave)">
        {colors.map((c, i) => (
          <path
            key={i}
            d={`M0,${i * band + 4} C25,${i * band - 3} 75,${i * band + 11} 100,${i * band + 3} L100,${(i + 1) * band + 3} C75,${(i + 1) * band + 11} 25,${(i + 1) * band - 3} 0,${(i + 1) * band + 4} Z`}
            fill={c}
          />
        ))}
      </g>
    </svg>
  );
}

/* ---- Deterministic Code128-ish barcode ---- */
function Barcode({ seed = "GAYCARD", height = 46, style = {} }) {
  // build a pseudo-random but stable set of bar widths from the seed
  let h = 2166136261;
  for (let i = 0; i < seed.length; i++) { h ^= seed.charCodeAt(i); h = Math.imul(h, 16777619); }
  const rng = () => { h = Math.imul(h ^ (h >>> 15), 2246822519); h ^= h >>> 13; return ((h >>> 0) % 1000) / 1000; };
  const bars = [];
  let x = 0;
  const total = 58;
  for (let i = 0; i < total; i++) {
    const w = 1 + Math.round(rng() * 3);
    bars.push({ x, w, on: i % 2 === 0 });
    x += w;
  }
  return (
    <svg viewBox={`0 0 ${x} 50`} width="100%" height={height} preserveAspectRatio="none" style={style} aria-label="código de barras">
      {bars.map((b, i) => b.on ? <rect key={i} x={b.x} y="0" width={b.w} height="50" fill="#121212" /> : null)}
    </svg>
  );
}

/* ---- build the certificate URL a card's QR points to ---- */
function buildCertUrl(memberNo) {
  try {
    var base = location.href.replace(/[?#].*$/, "").replace(/[^/]*$/, "");
    return base + "Certificado.html?id=" + (memberNo || "");
  } catch (e) { return "Certificado.html?id=" + (memberNo || ""); }
}

/* ---- Pride flag badge for the center of a QR ----
   A compact flat 6-stripe flag on a white rounded backing. Kept small (~27%)
   so the code stays scannable; pair it with error-correction level "H" (which
   tolerates ~30% occlusion) on the QR itself. Scales with its container. */
function QRFlagBadge() {
  const colors = ["#E40303", "#FF8C00", "#FFCE00", "#1FA63A", "#1257FF", "#8B14C9"];
  return (
    <div aria-hidden="true" style={{
      position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)",
      width: "27%", aspectRatio: "1 / 1", background: "#fff", borderRadius: "22%",
      boxShadow: "0 0 0 3px #fff", padding: "7%", display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <div style={{ width: "100%", height: "72%", borderRadius: "12%", overflow: "hidden", display: "flex", flexDirection: "column", boxShadow: "0 1px 3px rgba(0,0,0,0.18)" }}>
        {colors.map((c) => <div key={c} style={{ flex: 1, background: c }} />)}
      </div>
    </div>
  );
}

/* ---- a QR that scales to fill its container (needs global `qrcode`) ----
   `flag` overlays a pride flag in the center (and bumps error correction to H). */
function ScalableQR({ value, flag = false, style = {} }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !window.qrcode) return;
    try {
      const qr = window.qrcode(0, flag ? "H" : "M");
      qr.addData(value || " "); qr.make();
      ref.current.innerHTML = qr.createSvgTag({ cellSize: 2, margin: 0, scalable: true });
      const svg = ref.current.querySelector("svg");
      if (svg) { svg.style.width = "100%"; svg.style.height = "100%"; svg.style.display = "block"; svg.setAttribute("shape-rendering", "crispEdges"); }
    } catch (e) { ref.current.textContent = "QR"; }
  }, [value, flag]);
  return (
    <div style={{ position: "relative", width: "100%", height: "100%", ...style }}>
      <div ref={ref} style={{ width: "100%", height: "100%" }} />
      {flag && <QRFlagBadge />}
    </div>
  );
}

/* ---- The membership card: flips on click (front = QR, back = barcode + note) ---- */
function GayCardVisual({ photo, name, username = "@seu_usuario", memberNo = "", qrValue, floating = false, flippable = true, forceFace = null, style = {}, innerRef }) {
  const [flipped, setFlipped] = React.useState(false);
  const [touched, setTouched] = React.useState(false);
  const faceRef = React.useRef(null);
  // Safety net: if the runtime freezes the flip animation, settle the face flat.
  React.useEffect(() => {
    if (!touched || !faceRef.current) return;
    const el = faceRef.current;
    const t = setTimeout(() => { el.style.animation = "none"; el.style.transform = "none"; el.style.opacity = "1"; }, 680);
    return () => clearTimeout(t);
  }, [flipped, touched]);
  const seed = (username || "") + (memberNo || "GAYCARD");
  // Name on the card: first name on top, the rest below (no @). Falls back to handle.
  const nm = (name || "").trim();
  const nmParts = nm ? nm.split(/\s+/) : [];
  const nameLine1 = nmParts.length ? nmParts[0] : null;
  const nameLine2 = nmParts.length > 1 ? nmParts.slice(1).join(" ") : "";
  // Auto-size the name so the longest line always fits the column (no ellipsis).
  const nameMaxLen = Math.max((nameLine1 || "").length, (nameLine2 || "").length, 1);
  const nameFs = `clamp(7px, ${Math.min(5.0, 58 / nameMaxLen).toFixed(2)}cqw, 50px)`;
  const qr = qrValue || buildCertUrl(memberNo);
  // forceFace pins a side (used by the admin print/PDF export); otherwise the
  // card flips on click as usual.
  const forced = forceFace === "front" || forceFace === "back";
  const showBack = forced ? forceFace === "back" : flipped;
  const canFlip = flippable && !forced;
  const shadow = floating
    ? "0 40px 80px -28px rgba(18,18,18,0.45), 0 8px 22px -10px rgba(18,18,18,0.25)"
    : "0 14px 36px -16px rgba(18,18,18,0.3)";
  const face = {
    position: "relative", width: "100%", aspectRatio: "1.585 / 1", containerType: "inline-size",
    background: "#ffffff", borderRadius: "18px", boxShadow: shadow, padding: "6.2% 6.5%",
    display: "flex", flexDirection: "column", overflow: "hidden", fontFamily: 'Archivo, system-ui, sans-serif',
    cursor: canFlip ? "pointer" : "default",
  };
  const hint = (label) => (
    <div style={{ display: "flex", alignItems: "center", gap: "1.6cqw", color: "#9a9aa2", fontWeight: 700, fontSize: "clamp(7px,2.6cqw,15px)", letterSpacing: "0.04em" }}>
      <svg viewBox="0 0 24 24" style={{ width: "3.6cqw", height: "3.6cqw", minWidth: 11 }} fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5" strokeLinecap="round" strokeLinejoin="round"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5" strokeLinecap="round" strokeLinejoin="round"/></svg>
      {label}
    </div>
  );

  const front = (
    <React.Fragment>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "4%" }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 900, color: "#121212", lineHeight: 0.86, fontSize: "clamp(20px, 9.2cqw, 100px)", letterSpacing: "-0.04em" }}>GAY CARD</div>
          <div style={{ color: "#E40303", fontWeight: 700, marginTop: "0.35em", fontSize: "clamp(7px, 3.3cqw, 34px)", letterSpacing: "0.34em" }}>PREMIUM MEMBERSHIP</div>
        </div>
        <PrideFlag width={84} style={{ flexShrink: 0, width: "26%", height: "auto" }} />
      </div>
      <div style={{ height: "2.5px", background: "#121212", margin: "5.5% 0 6%" }} />
      <div style={{ display: "flex", gap: "5%", flex: 1, minHeight: 0, alignItems: "stretch" }}>
        <div style={{ width: "30%", aspectRatio: "1 / 1", borderRadius: "12px", background: "#e9e9ec", overflow: "hidden", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
          {photo ? <img src={photo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            : <svg viewBox="0 0 24 24" style={{ width: "64%", height: "64%", color: "#b6b6bd" }} fill="currentColor"><circle cx="12" cy="8.5" r="4" /><path d="M4 21c0-4.4 3.6-7 8-7s8 2.6 8 7v1H4v-1z" /></svg>}
        </div>
        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", justifyContent: "center", gap: "3%" }}>
          {nameLine1 ? (
            <React.Fragment>
              <div style={{ fontWeight: 800, color: "#121212", letterSpacing: "-0.02em", lineHeight: 1.04, fontSize: nameFs, whiteSpace: "nowrap" }}>{nameLine1}</div>
              {nameLine2 ? <div style={{ fontWeight: 800, color: "#121212", letterSpacing: "-0.02em", lineHeight: 1.04, fontSize: nameFs, whiteSpace: "nowrap" }}>{nameLine2}</div> : null}
            </React.Fragment>
          ) : (
            <div style={{ fontWeight: 800, color: "#121212", letterSpacing: "-0.01em", fontSize: "clamp(11px, 5.2cqw, 54px)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{username}</div>
          )}
        </div>
        <div style={{ width: "29%", aspectRatio: "1 / 1", alignSelf: "center", flexShrink: 0, borderRadius: "10px", overflow: "hidden", background: "#fff", padding: "2%" }}>
          <ScalableQR value={qr} flag />
        </div>
      </div>
    </React.Fragment>
  );

  const back = (
    <React.Fragment>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "4%" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "3%" }}>
          <PrideFlag width={40} style={{ width: "16%", minWidth: 26, height: "auto" }} />
          <span style={{ fontWeight: 900, color: "#121212", fontSize: "clamp(13px,5.4cqw,52px)", letterSpacing: "-0.03em" }}>GAY CARD</span>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ color: "#9a9aa2", fontWeight: 700, fontSize: "clamp(6px,2.4cqw,13px)", letterSpacing: "0.2em" }}>MEMBRO</div>
          <div style={{ fontFamily: "Space Mono, monospace", color: "#121212", fontWeight: 700, fontSize: "clamp(8px,3.2cqw,18px)" }}>{memberNo || "BR-000000"}</div>
        </div>
      </div>
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "3% 2%" }}>
        <p style={{ margin: 0, textAlign: "center", color: "#23211c", fontWeight: 600, lineHeight: 1.42, fontSize: "clamp(9px,4cqw,26px)" }}>
          Obrigado por fazer parte. Aqui, você tem o direito de ser exatamente quem é. Bem-vindo(a) à comunidade. <span style={{ whiteSpace: "nowrap" }}>🏳️‍🌈</span>
        </p>
      </div>
      <Barcode seed={seed} height={"clamp(16px, 7cqw, 70px)"} style={{ height: "clamp(16px, 7cqw, 70px)" }} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "3%" }}>
        <span style={{ fontFamily: "Space Mono, monospace", color: "#9a9aa2", fontSize: "clamp(6px,2.4cqw,13px)", letterSpacing: "0.1em" }}>GAYCARD · BRASIL</span>
        <span style={{ fontFamily: "Space Mono, monospace", color: "#c9c9cf", fontSize: "clamp(6px,2.4cqw,13px)", letterSpacing: "0.1em" }}>PREMIUM</span>
      </div>
    </React.Fragment>
  );

  return (
    <div ref={innerRef} style={{ width: "100%", perspective: "1400px", ...style }}>
      <div
        key={showBack ? "back" : "front"}
        ref={faceRef}
        className={touched && !forced ? "card-flip-face" : ""}
        onClick={() => { if (canFlip) { setFlipped((f) => !f); setTouched(true); } }}
        style={face}>
        {showBack ? back : front}
      </div>
    </div>
  );
}

/* ---- QR code (needs global `qrcode` from qrcode-generator CDN) ----
   `flag` overlays a pride flag in the center (and bumps error correction to H).
   Do NOT enable `flag` on the Pix payment QR — keep that one clean for banks. */
function QRCode({ value, size = 132, flag = false, style = {} }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    try {
      const qr = window.qrcode(0, flag ? "H" : "M");
      qr.addData(value || " ");
      qr.make();
      ref.current.innerHTML = qr.createSvgTag({ cellSize: 4, margin: 0, scalable: true });
      const svg = ref.current.querySelector("svg");
      if (svg) { svg.setAttribute("width", size); svg.setAttribute("height", size); svg.style.display = "block"; }
    } catch (e) {
      ref.current.textContent = "QR";
    }
  }, [value, size, flag]);
  return (
    <div style={{ position: "relative", width: size, height: size, ...style }}>
      <div ref={ref} style={{ width: size, height: size }} />
      {flag && <QRFlagBadge />}
    </div>
  );
}

/* ---- Letter copy builder ----
   For gifts (gift=true) with the giver's name (fromName): if there is a custom
   message, the name signs it (customFrom, shown below the message); if there is
   no message, the name joins the sign-off ("Comunidade GayCard e <nome>"). */
function buildLetter({ name = "Membro", custom = "", date = "", fromName = "", gift = false } = {}) {
  const base = [
    `Caro(a) ${name || "Membro"},`,
    "Em nome da comunidade LGBTQ+, temos o prazer de lhe dar as boas-vindas e expressar nosso sincero apoio.",
    "Bem-vindo(a) a um espaço onde respeito, abertura e apoio mútuo são valores fundamentais. Aqui, todos têm o direito de serem eles mesmos, de se sentirem seguros e de se conectarem com pessoas que pensam de forma semelhante. Temos orgulho de reunir indivíduos de diferentes origens, culturas e perspectivas, criando uma comunidade forte e inspiradora.",
    "Sua presença é uma parte importante desta jornada compartilhada. Estamos felizes em tê-lo(a) conosco e esperamos que você encontre apoio, amizade e inspiração aqui.",
    "Como símbolo da sua associação, anexamos um cartão de membro Premium. Ele concede acesso a uma variedade de privilégios e ofertas especiais em locais e estabelecimentos LGBTQ+ por todo o Brasil.",
  ];
  const custTrim = (custom || "").trim();
  const from = gift ? (fromName || "").trim() : "";
  return {
    paragraphs: base,
    custom: custTrim,
    customFrom: (from && custTrim) ? from : "",
    signoff: "Com os melhores cumprimentos,",
    org: (from && !custTrim) ? `Comunidade GayCard e ${from}` : "Comunidade GayCard",
    date,
  };
}

/* ---- Printed letter document ---- */
function LetterDocument({ name = "Membro", custom = "", date = "", fromName = "", gift = false, style = {}, innerRef }) {
  const L = buildLetter({ name, custom, date, fromName, gift });
  return (
    <div ref={innerRef} style={{
      background: "var(--paper, #f7f3ea)",
      borderRadius: "10px",
      padding: "clamp(22px, 5%, 52px)",
      color: "#23211c",
      fontFamily: 'Archivo, system-ui, sans-serif',
      boxShadow: "0 20px 50px -24px rgba(18,18,18,0.35)",
      position: "relative",
      lineHeight: 1.62,
      ...style,
    }}>
      <div style={{ display: "flex", justifyContent: "center", marginBottom: "1.6rem" }}>
        <PrideFlag width={56} />
      </div>
      <p style={{ fontWeight: 700, fontSize: "1.05rem", margin: "0 0 1.1rem" }}>{L.paragraphs[0]}</p>
      {L.paragraphs.slice(1).map((p, i) => (
        <p key={i} style={{ margin: "0 0 1rem", fontSize: "0.96rem", color: "#3a372f" }}>{p}</p>
      ))}
      {L.custom ? (
        <React.Fragment>
          <p style={{ margin: "1.2rem 0 0.4rem", fontSize: "0.98rem", fontStyle: "italic", paddingLeft: "1rem", borderLeft: "3px solid var(--purple, #8B14C9)", color: "#23211c" }}>
            “{L.custom}”
          </p>
          {L.customFrom ? <p style={{ margin: "0 0 1.2rem", paddingLeft: "1rem", fontWeight: 700, fontSize: "0.92rem", color: "#23211c" }}>— {L.customFrom}</p> : null}
        </React.Fragment>
      ) : null}
      <p style={{ margin: "1.6rem 0 0.2rem", fontSize: "0.96rem" }}>{L.signoff}</p>
      <p style={{ margin: 0, fontWeight: 700, fontSize: "0.96rem" }}>{L.org}</p>
      {L.date ? <p className="mono" style={{ margin: "1.4rem 0 0", letterSpacing: "0.1em", color: "#6b675c", fontSize: "0.8rem" }}>{L.date}</p> : null}
    </div>
  );
}

/* ---- Member number ---- */
function makeMemberNo() {
  const n = Math.floor(100000 + Math.random() * 899999);
  return `BR-${n}`;
}

Object.assign(window, { PrideFlag, Barcode, GayCardVisual, QRCode, LetterDocument, buildLetter, makeMemberNo });
