// Warranty success step — celebration screen with confetti

// Deterministic cert no — must match Code.gs generateCertNo_() exactly.
function certNoFromSN(sn) {
  const s = String(sn || "").toUpperCase();
  let h = 0;
  for (let i = 0; i < s.length; i++) h = ((h * 31) + s.charCodeAt(i)) | 0;
  const num = (Math.abs(h) % 900000) + 100000;
  return "ADRO-W-" + num;
}

function StepSuccess({ serial, product, customer, onRestart, certNo: certNoProp, emailSent, regError }) {
  const [pieces, setPieces] = React.useState([]);
  const certNo = React.useMemo(
    () => certNoProp || certNoFromSN(serial && serial.sn),
    [certNoProp, serial && serial.sn]
  );

  React.useEffect(() => {
    const colors = ["#e0201c", "#ff3b32", "#ffffff", "#ffb020", "#1ed773"];
    const arr = Array.from({ length: 60 }, (_, i) => ({
      id: i,
      left: Math.random() * 100,
      delay: Math.random() * 0.8,
      duration: 2 + Math.random() * 2,
      color: colors[Math.floor(Math.random() * colors.length)],
      size: 6 + Math.random() * 8,
      rot: Math.random() * 360,
    }));
    setPieces(arr);
  }, []);

  return (
    <div style={{ maxWidth: 760, margin: "0 auto", padding: "60px 24px", width: "100%", position: "relative" }}>
      {/* Confetti */}
      <div style={{ position: "fixed", inset: 0, pointerEvents: "none", overflow: "hidden", zIndex: 1 }}>
        {pieces.map(p => (
          <div key={p.id} style={{
            position: "absolute", top: 0, left: `${p.left}%`,
            width: p.size, height: p.size * 0.4, background: p.color,
            transform: `rotate(${p.rot}deg)`,
            animation: `confetti-fall ${p.duration}s ease-in ${p.delay}s forwards`,
          }} />
        ))}
      </div>

      <div style={{ textAlign: "center", animation: "scale-in .5s ease both" }}>
        <div style={{
          width: 88, height: 88, borderRadius: 999, margin: "0 auto 24px",
          background: "var(--green)", color: "#000",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 44, fontWeight: 800, boxShadow: "0 0 60px rgba(30,215,115,0.4)",
        }}>✓</div>

        <div className="display" style={{ fontSize: 14, color: "var(--green)", letterSpacing: "0.2em", marginBottom: 12 }}>
          WARRANTY ACTIVATED
        </div>
        <h1 className="display" style={{ fontSize: 56, margin: 0, lineHeight: 0.95, fontWeight: 900 }}>
          You're <span style={{ color: "var(--red)" }}>covered</span>.
        </h1>
        {regError ? (
          <p style={{ color: "var(--amber)", fontSize: 14, marginTop: 18, lineHeight: 1.5, maxWidth: 480, margin: "18px auto 0" }}>
            ⚠ Your details have been recorded locally, but we couldn't reach our registry: <strong>{regError}</strong>. Please contact <a href="mailto:strain@adro.com" style={{ color: "var(--amber)" }}>strain@adro.com</a> with your S/N and we'll finalize it manually.
          </p>
        ) : emailSent ? (
          <p style={{ color: "var(--ink-2)", fontSize: 16, marginTop: 18, lineHeight: 1.5 }}>
            A confirmation has been sent to <strong style={{ color: "var(--ink)" }}>{customer.email}</strong>.
          </p>
        ) : (
          <p style={{ color: "var(--ink-2)", fontSize: 16, marginTop: 18, lineHeight: 1.5 }}>
            Save this certificate — your S/N is the only thing you'll need for RMA.
          </p>
        )}
      </div>

      {/* Certificate */}
      <div style={{
        marginTop: 40, padding: 0,
        background: "linear-gradient(135deg, #16161c, #0e0e12)",
        border: "1px solid var(--line-2)", borderRadius: "var(--radius-xl)",
        overflow: "hidden", position: "relative",
        animation: "slideUp .6s ease both",
        animationDelay: ".2s",
      }}>
        <div className="hazard" style={{ height: 4 }} />
        <div style={{ padding: 32 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
            <div>
              <div className="display" style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.2em" }}>WARRANTY CERTIFICATE</div>
              <div className="display" style={{ fontSize: 28, marginTop: 6, fontWeight: 800 }}>LIFETIME COVERAGE</div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700 }}>Cert. No</div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>{certNo}</div>
            </div>
          </div>

          <div className="rule-red" style={{ marginBottom: 20 }} />

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700, marginBottom: 4 }}>Product</div>
              <div className="display" style={{ fontSize: 22, fontWeight: 800, lineHeight: 1.1 }}>{product.line}</div>
              <div style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 600 }}>{product.name}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>SKU {product.sku}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700, marginBottom: 4 }}>Owner</div>
              <div style={{ fontSize: 16, fontWeight: 700 }}>{customer.name}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{customer.city}, {customer.country}</div>
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 20, padding: "16px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700 }}>Serial</div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, marginTop: 4 }}>{window.ADRO_formatSN(serial.sn)}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700 }}>TTG</div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, marginTop: 4 }}>{serial.ttg}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700 }}>Activated</div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, marginTop: 4 }}>{new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</div>
            </div>
          </div>

          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 20 }}>
            <div style={{ fontSize: 11, color: "var(--ink-3)", lineHeight: 1.5, maxWidth: 400 }}>
              Covers manufacturing defects for the lifetime of the original purchaser.<br/>
              Keep this certificate for your records.
            </div>
            <img
              src="assets/adro-logo.png"
              alt="ADRO"
              style={{
                height: 26, width: "auto", display: "block",
                filter: "brightness(0) invert(1)",
              }}
            />
          </div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 28 }}>
        <Btn variant="secondary" size="lg" onClick={() => window.print()} icon={<span>🖨</span>}>Save as PDF</Btn>
        <Btn variant="secondary" size="lg" onClick={() => navigator.clipboard?.writeText(certNo)} icon={<span>📋</span>}>Copy cert. no</Btn>
        <Btn variant="ghost" size="lg" onClick={onRestart}>Register another →</Btn>
      </div>

      <div style={{ marginTop: 40, padding: 24, background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 12, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 20 }}>
        <NextStep icon="◆" title="Follow @adroperformance" sub="Drop alerts before they go public." />
        <NextStep icon="◇" title="Join the build registry" sub="Show off the install with #adrobuilt." />
        <NextStep icon="◈" title="Need an RMA?" sub="warranty.adro.com/rma · 24h response." />
      </div>
    </div>
  );
}

function NextStep({ icon, title, sub }) {
  return (
    <div>
      <div style={{ color: "var(--red)", fontSize: 18, marginBottom: 8 }}>{icon}</div>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 4 }}>{title}</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>{sub}</div>
    </div>
  );
}

window.StepSuccess = StepSuccess;
