// Warranty registration site components
// Multi-step flow: 1) Validate S/N → 2) Customer info → 3) Vehicle/purchase → 4) Success

function WarrantyShell({ children, step, totalSteps }) {
  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>
      <WHeader />
      <main style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        {step != null && <ProgressBar step={step} total={totalSteps} />}
        {children}
      </main>
      <WFooter />
    </div>
  );
}

function WHeader() {
  return (
    <header style={{
      borderBottom: "1px solid var(--line)",
      background: "rgba(10,10,11,0.85)",
      backdropFilter: "blur(20px)",
      position: "sticky", top: 0, zIndex: 50,
    }}>
      <div className="hazard" style={{ height: 3 }} />
      <div style={{
        maxWidth: 1180, margin: "0 auto", padding: "0 24px",
        height: 68, display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <img
            src="assets/adro-logo.png"
            alt="ADRO"
            style={{
              height: 26, width: "auto", display: "block",
              filter: "brightness(0) invert(1)",
            }}
          />
          <div style={{ width: 1, height: 22, background: "var(--line-2)" }} />
          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-2)", letterSpacing: "0.04em" }}>
            Warranty Registration
          </div>
        </div>
        <div style={{ display: "flex", gap: 24, fontSize: 13, color: "var(--ink-3)" }}>
          <a href="#" style={{ color: "inherit", textDecoration: "none" }}>Support</a>
          <a href="#" style={{ color: "inherit", textDecoration: "none" }}>FAQ</a>
          <a href="#" style={{ color: "inherit", textDecoration: "none" }}>EN ▾</a>
        </div>
      </div>
    </header>
  );
}

function WFooter() {
  return (
    <footer style={{
      borderTop: "1px solid var(--line)",
      padding: "32px 24px",
      background: "var(--bg-2)",
      marginTop: 60,
    }}>
      <div style={{
        maxWidth: 1180, margin: "0 auto",
        display: "flex", justifyContent: "space-between", alignItems: "center",
        fontSize: 12, color: "var(--ink-4)",
      }}>
        <div style={{ display: "flex", gap: 24 }}>
          <span>© 2026 ADRO Performance · Made in USA</span>
          <a href="#" style={{ color: "inherit" }}>Privacy</a>
          <a href="#" style={{ color: "inherit" }}>Terms</a>
        </div>
        <div className="mono">warranty.adro.com</div>
      </div>
    </footer>
  );
}

function ProgressBar({ step, total }) {
  const labels = ["Verify", "Owner", "Purchase", "Done"];
  return (
    <div style={{ borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
      <div style={{
        maxWidth: 760, margin: "0 auto", padding: "16px 24px",
        display: "grid", gridTemplateColumns: `repeat(${total}, 1fr)`, gap: 12,
      }}>
        {Array.from({ length: total }).map((_, i) => {
          const done = i < step;
          const active = i === step;
          return (
            <div key={i} style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <div style={{
                height: 3, borderRadius: 2,
                background: done ? "var(--red)" : active ? "var(--red)" : "var(--line)",
                opacity: done ? 1 : active ? 1 : 1,
                position: "relative",
              }}>
                {active && (
                  <div style={{
                    position: "absolute", inset: 0, borderRadius: 2,
                    background: "linear-gradient(90deg, var(--red), transparent)",
                    backgroundSize: "200% 100%",
                    animation: "shimmer 1.6s linear infinite",
                  }} />
                )}
              </div>
              <div style={{
                fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase",
                color: done || active ? "var(--ink-2)" : "var(--ink-4)",
              }}>
                {String(i + 1).padStart(2, "0")} · {labels[i]}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// SN validation step
function StepValidate({ onValidated, prefilledSn }) {
  const [sn, setSn] = React.useState(prefilledSn || "");
  const [status, setStatus] = React.useState("idle");   // idle / checking / valid / invalid / used
  const [match, setMatch] = React.useState(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (prefilledSn) {
      setTimeout(() => check(prefilledSn), 400);
    } else {
      inputRef.current?.focus();
    }
  }, []);

  const check = async (raw) => {
    const clean = (raw || sn).replace(/[^A-Z0-9]/gi, "").toUpperCase();
    if (clean.length < 8) {
      setStatus("invalid");
      setMatch(null);
      return;
    }
    setStatus("checking");
    const res = await window.ADRO_sheetsSync.validate(clean);
    if (!res || !res.ok) {
      setStatus("invalid");
      setMatch(null);
      return;
    }
    const found = {
      sn: res.sn || clean,
      sku: res.sku,
      ttg: res.ttg,
      issued: res.issued,
      product: res.product,
    };
    if (res.registered) {
      setStatus("used"); setMatch(found); return;
    }
    setStatus("valid"); setMatch(found);
  };

  const product = match ? match.product : null;

  return (
    <div style={{ maxWidth: 760, margin: "0 auto", padding: "60px 24px 40px", width: "100%" }}>
      <div style={{ textAlign: "center", marginBottom: 40 }}>
        <div className="rule-red" style={{ margin: "0 auto 18px" }} />
        <h1 className="display" style={{ fontSize: 56, lineHeight: 0.95, margin: 0, fontWeight: 900 }}>
          Activate your<br /><span style={{ color: "var(--red)" }}>warranty</span>.
        </h1>
        <p style={{ fontSize: 16, color: "var(--ink-3)", margin: "20px auto 0", maxWidth: 480, lineHeight: 1.5 }}>
          Enter the serial number from your ADRO part's sticker to begin lifetime defect coverage.
        </p>
      </div>

      <div style={{
        background: "var(--panel)", border: "1px solid var(--line)",
        borderRadius: "var(--radius-xl)", padding: 32, position: "relative",
        boxShadow: status === "valid" ? "0 0 0 1px var(--green), 0 0 30px rgba(30,215,115,0.15)" :
                   status === "invalid" || status === "used" ? "0 0 0 1px var(--red), 0 0 30px rgba(255,59,50,0.15)" :
                   "0 12px 40px rgba(0,0,0,0.4)",
        transition: "box-shadow .25s ease",
      }}>
        <label className="lbl">Serial number</label>
        <div style={{ position: "relative" }}>
          <input
            ref={inputRef}
            value={sn}
            onChange={(e) => { setSn(e.target.value.toUpperCase()); setStatus("idle"); setMatch(null); }}
            onKeyDown={(e) => e.key === "Enter" && check()}
            className="field mono"
            placeholder="A7K2M-9P4XZ"
            style={{
              fontSize: 28, fontWeight: 700, letterSpacing: "0.1em",
              padding: "20px 130px 20px 20px", height: "auto",
              textTransform: "uppercase", textAlign: "center",
            }}
            maxLength={14}
          />
          <Btn variant="primary" size="lg" onClick={() => check()} disabled={status === "checking" || sn.length < 8}
            style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)" }}>
            {status === "checking" ? "Verifying…" : "Verify →"}
          </Btn>
        </div>

        {/* Result */}
        {status === "checking" && (
          <div style={{ marginTop: 20, display: "flex", alignItems: "center", gap: 10, color: "var(--ink-3)", fontSize: 13 }}>
            <div style={{
              width: 14, height: 14, borderRadius: 999,
              border: "2px solid var(--ink-3)", borderTopColor: "transparent",
              animation: "spin 0.8s linear infinite",
            }} />
            Checking against issued serials…
          </div>
        )}

        {status === "invalid" && (
          <div style={{
            marginTop: 20, padding: 16,
            background: "rgba(255,59,50,0.08)", border: "1px solid rgba(255,59,50,0.25)",
            borderRadius: 8, color: "var(--red-2)", fontSize: 13, lineHeight: 1.5,
            animation: "slideUp .25s ease",
          }}>
            <strong>Serial not recognized.</strong> Double-check the characters from your sticker (avoid confusing 0/O and 1/I — we don't use those).
          </div>
        )}

        {status === "used" && (
          <div style={{
            marginTop: 20, padding: 16,
            background: "rgba(255,176,32,0.08)", border: "1px solid rgba(255,176,32,0.25)",
            borderRadius: 8, color: "var(--amber)", fontSize: 13, lineHeight: 1.5,
            animation: "slideUp .25s ease",
          }}>
            <strong>This serial is already registered.</strong> If you believe this is a mistake, contact <a href="#" style={{ color: "var(--amber)" }}>support@adro.com</a>.
          </div>
        )}

        {status === "valid" && match && product && (
          <div style={{
            marginTop: 24, animation: "slideUp .3s ease",
          }}>
            <div style={{
              padding: 20, borderRadius: 10,
              background: "rgba(30,215,115,0.06)", border: "1px solid rgba(30,215,115,0.25)",
              display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 16, alignItems: "center",
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 999,
                background: "var(--green)", color: "#000",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 18, fontWeight: 700,
              }}>✓</div>
              <div>
                <div style={{ fontSize: 11, color: "var(--green)", fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase" }}>
                  Verified · Genuine ADRO part
                </div>
                <div className="display" style={{ fontSize: 22, marginTop: 4 }}>
                  {product.line} <span style={{ color: "var(--ink-2)" }}>{product.name}</span>
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>
                  SKU {product.sku} · TTG {match.ttg} · Issued {new Date(match.issued).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </div>
              </div>
              <Btn variant="primary" size="lg" onClick={() => onValidated(match, product)}>
                Continue →
              </Btn>
            </div>
          </div>
        )}
      </div>

      <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
        <Helper icon="◆" title="Where to find it">Bottom of the sticker on every ADRO part — labeled S/N.</Helper>
        <Helper icon="◇" title="Lifetime coverage">Defect protection for the original purchaser. Track installation date.</Helper>
        <Helper icon="◈" title="Why register">Faster RMA, member discounts, drop alerts before public release.</Helper>
      </div>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

function Helper({ icon, title, children }) {
  return (
    <div style={{
      padding: 18, background: "var(--panel)",
      border: "1px solid var(--line)", borderRadius: 10,
    }}>
      <div style={{ color: "var(--red)", fontSize: 18, marginBottom: 8 }}>{icon}</div>
      <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 4 }}>{title}</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>{children}</div>
    </div>
  );
}

Object.assign(window, { WarrantyShell, StepValidate });
