/* global React */
const { useState: uS3 } = React;

// ============================================================
// CUSTOM DESIGN FLOW — 5-step customizer with live preview
// ============================================================

function CustomPage({ setRoute, addToCart }) {
  const { waxColors, shapes, scripts } = window.EVERLIT_DATA;
  const [step, setStep] = uS3(1);
  const [config, setConfig] = uS3({
    type: "monogram", // monogram | logo | custom-art
    shape: shapes[0],
    script: scripts[0],
    initials: "EA",
    wax: waxColors[0],
    notes: "",
    rush: false,
  });
  const price = 65 + (config.type === "custom-art" ? 40 : 0) + (config.rush ? 25 : 0);

  return (
    <div className="page-enter">
      <section style={{ paddingTop: 60, paddingBottom: 0 }}>
        <div className="container">
          <div style={{ textAlign: "center", paddingBottom: 40, borderBottom: "1px solid var(--rule)" }}>
            <div className="eyebrow">Bespoke Commission</div>
            <h1 className="section-title" style={{ fontSize: "clamp(64px, 9vw, 140px)", marginTop: 18 }}>A seal <span className="italic-accent">of one's own.</span></h1>
            <p className="section-intro" style={{ margin: "28px auto 0" }}>
              From napkin sketch to a finished brass die in six weeks. Proofs before production. Revisions until you are delighted.
            </p>
          </div>
        </div>
      </section>

      <section style={{ paddingTop: 56 }}>
        <div className="container">
          <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 80, alignItems: "start" }}>
            {/* Left: form */}
            <div>
              {/* Step nav */}
              <div style={{ display: "flex", gap: 4, marginBottom: 36, borderBottom: "1px solid var(--rule)", paddingBottom: 20 }}>
                {["Artwork", "Form", "Script", "Wax", "Review"].map((s, i) => (
                  <button key={s} onClick={() => setStep(i+1)} style={{ flex: 1, padding: "10px 6px", textAlign: "center", fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", borderBottom: step === i+1 ? "2px solid var(--ink)" : "2px solid transparent", color: step === i+1 ? "var(--ink)" : "var(--ink-muted)", marginBottom: -21 }}>
                    <div style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: 18 }}>№ {String(i+1).padStart(2,"0")}</div>
                    <div style={{ marginTop: 4 }}>{s}</div>
                  </button>
                ))}
              </div>

              {step === 1 && (
                <div className="step-panel">
                  <h3 className="display" style={{ fontSize: 36, margin: "0 0 10px" }}>What shall we engrave?</h3>
                  <p style={{ color: "var(--ink-soft)", fontStyle: "italic", marginTop: 0 }}>Choose the kind of artwork. We'll ask for details shortly.</p>
                  <div style={{ display: "grid", gap: 12, marginTop: 28 }}>
                    {[
                      { id: "monogram", name: "A monogram", sub: "One, two or three letters drawn as a cipher", from: "$65" },
                      { id: "logo", name: "A logo or brand mark", sub: "Existing artwork you'll send us", from: "$78" },
                      { id: "custom-art", name: "A custom illustration", sub: "Our draughtsman draws from your brief", from: "$105" },
                      { id: "heraldic", name: "A family crest or heraldry", sub: "Re-engraved from your arms", from: "$125" },
                    ].map(o => (
                      <button key={o.id} onClick={() => setConfig({...config, type: o.id})} style={{
                        display: "flex", justifyContent: "space-between", alignItems: "center",
                        padding: "22px 24px", border: config.type === o.id ? "1px solid var(--ink)" : "1px solid var(--rule)",
                        background: config.type === o.id ? "var(--surface)" : "transparent", textAlign: "left", cursor: "pointer"
                      }}>
                        <div>
                          <div style={{ fontFamily: "var(--serif-display)", fontSize: 22 }}>{o.name}</div>
                          <div style={{ fontFamily: "var(--sans)", fontSize: 13, color: "var(--ink-muted)", marginTop: 4 }}>{o.sub}</div>
                        </div>
                        <div className="fig-caption">{o.from}</div>
                      </button>
                    ))}
                  </div>
                  {config.type === "monogram" && (
                    <div style={{ marginTop: 28 }}>
                      <label>Your initials (1–3 letters)</label>
                      <input type="text" maxLength={3} value={config.initials} onChange={e => setConfig({...config, initials: e.target.value.toUpperCase()})} style={{ fontSize: 32, fontFamily: "var(--serif-display)", letterSpacing: "0.12em" }} />
                    </div>
                  )}
                  {(config.type === "logo" || config.type === "custom-art" || config.type === "heraldic") && (
                    <div style={{ marginTop: 28, padding: 24, border: "1px dashed var(--rule)", textAlign: "center" }}>
                      <div style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: 20 }}>Upload your reference</div>
                      <div className="fig-caption" style={{ marginTop: 6 }}>JPG, PNG, SVG, PDF · up to 20MB · you can also email after</div>
                      <button className="btn btn-ghost" style={{ marginTop: 16 }}>Choose file…</button>
                    </div>
                  )}
                </div>
              )}

              {step === 2 && (
                <div className="step-panel">
                  <h3 className="display" style={{ fontSize: 36, margin: "0 0 10px" }}>The form of the die.</h3>
                  <p style={{ color: "var(--ink-soft)", fontStyle: "italic", marginTop: 0 }}>Round remains the most beloved. Shield and oval are for the ceremonial.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, marginTop: 24 }}>
                    {shapes.map(s => (
                      <button key={s.id} onClick={() => setConfig({...config, shape: s})} style={{
                        padding: "20px 18px", border: config.shape.id === s.id ? "1px solid var(--ink)" : "1px solid var(--rule)",
                        background: config.shape.id === s.id ? "var(--surface)" : "transparent", textAlign: "left", cursor: "pointer",
                        display: "flex", justifyContent: "space-between", alignItems: "center"
                      }}>
                        <div style={{ fontFamily: "var(--serif-display)", fontSize: 19 }}>{s.name}</div>
                        {s.note && <div className="fig-caption">{s.note}</div>}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {step === 3 && (
                <div className="step-panel">
                  <h3 className="display" style={{ fontSize: 36, margin: "0 0 10px" }}>Letterform.</h3>
                  <p style={{ color: "var(--ink-soft)", fontStyle: "italic", marginTop: 0 }}>Each script is hand-redrawn — not selected from a font.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12, marginTop: 24 }}>
                    {scripts.map(s => (
                      <button key={s.id} onClick={() => setConfig({...config, script: s})} style={{
                        padding: "36px 24px", border: config.script.id === s.id ? "1px solid var(--ink)" : "1px solid var(--rule)",
                        background: config.script.id === s.id ? "var(--surface)" : "transparent", textAlign: "center", cursor: "pointer"
                      }}>
                        <div style={{ fontFamily: "var(--serif-display)", fontSize: 72, lineHeight: 1 }}>{s.preview}</div>
                        <div className="fig-caption" style={{ marginTop: 12 }}>{s.name}</div>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {step === 4 && (
                <div className="step-panel">
                  <h3 className="display" style={{ fontSize: 36, margin: "0 0 10px" }}>Paired wax.</h3>
                  <p style={{ color: "var(--ink-soft)", fontStyle: "italic", marginTop: 0 }}>Three sticks of your chosen shade are included with every commission.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, marginTop: 24 }}>
                    {waxColors.map(w => (
                      <button key={w.id} onClick={() => setConfig({...config, wax: w})} style={{
                        display: "flex", gap: 18, alignItems: "center", padding: "14px 16px",
                        border: config.wax.id === w.id ? "1px solid var(--ink)" : "1px solid var(--rule)",
                        background: config.wax.id === w.id ? "var(--surface)" : "transparent", cursor: "pointer", textAlign: "left"
                      }}>
                        <div style={{ width: 36, height: 36, borderRadius: "50%", background: w.hex, flexShrink: 0 }} />
                        <div>
                          <div style={{ fontFamily: "var(--serif-display)", fontSize: 18 }}>{w.name}</div>
                          <div className="fig-caption" style={{ marginTop: 2 }}>{w.hex}</div>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {step === 5 && (
                <div className="step-panel">
                  <h3 className="display" style={{ fontSize: 36, margin: "0 0 10px" }}>Review your commission.</h3>
                  <div style={{ border: "1px solid var(--rule)", padding: 28, marginTop: 20 }}>
                    <Row label="Artwork" v={config.type.replace("-", " ")} />
                    {config.type === "monogram" && <Row label="Initials" v={config.initials} />}
                    <Row label="Form" v={config.shape.name} />
                    {config.type === "monogram" && <Row label="Script" v={config.script.name} />}
                    <Row label="Paired wax" v={config.wax.name} />
                    <Row label="Lead time" v={config.rush ? "3 weeks (rush)" : "6 weeks (standard)"} />
                  </div>
                  <label style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 24, cursor: "pointer" }}>
                    <input type="checkbox" checked={config.rush} onChange={e => setConfig({...config, rush: e.target.checked})} style={{ width: 18, height: 18 }} />
                    <span style={{ textTransform: "none", letterSpacing: 0, fontFamily: "var(--serif-display)", fontSize: 16, color: "var(--ink)" }}>
                      Rush — halve the lead time (+$25)
                    </span>
                  </label>
                  <label style={{ marginTop: 24 }}>Additional notes for our draughtsman</label>
                  <textarea value={config.notes} onChange={e => setConfig({...config, notes: e.target.value})} rows={4} placeholder="Reference artists, mood, wedding date, any rim-text, etc." />
                </div>
              )}

              {/* Step nav buttons */}
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 48, paddingTop: 24, borderTop: "1px solid var(--rule)" }}>
                <button className="btn-link" onClick={() => setStep(Math.max(1, step-1))} disabled={step===1} style={{ opacity: step === 1 ? 0.3 : 1 }}>← Previous</button>
                {step < 5 ? (
                  <button className="btn" onClick={() => setStep(step+1)}>Continue →</button>
                ) : (
                  <button className="btn" onClick={() => { addToCart({ id: "commission-" + Date.now(), name: "Bespoke Commission", subtitle: config.type, image: "assets/hero/detail-rose.jpg", price, qty: 1 }); setRoute("checkout"); }}>
                    Reserve — ${price}
                  </button>
                )}
              </div>
            </div>

            {/* Right: live preview */}
            <div style={{ position: "sticky", top: 140 }}>
              <div className="fig-caption" style={{ marginBottom: 16 }}>Fig. — Live preview</div>
              <div style={{ aspectRatio: "1/1", background: "var(--ink)", position: "relative", overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(ellipse at 30% 30%, rgba(255,255,255,0.1), transparent 60%)" }} />
                <WaxPreview config={config} />
              </div>
              <div style={{ border: "1px solid var(--rule)", padding: 20, marginTop: 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <div className="fig-caption">Est. total</div>
                  <div style={{ fontFamily: "var(--serif-display)", fontSize: 32, marginTop: 4 }}>${price}</div>
                </div>
                <div>
                  <div className="fig-caption">Lead time</div>
                  <div style={{ fontFamily: "var(--serif-display)", fontSize: 32, marginTop: 4 }}>{config.rush ? "3w" : "6w"}</div>
                </div>
              </div>
              <div style={{ marginTop: 20, fontSize: 14, color: "var(--ink-soft)", fontStyle: "italic", lineHeight: 1.5 }}>
                Includes: artwork proof before production · three sticks of paired wax · brass melting spoon · oxblood linen case · free international courier.
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function Row({ label, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderBottom: "1px solid var(--rule-soft)" }}>
      <div className="fig-caption">{label}</div>
      <div style={{ fontFamily: "var(--serif-display)", fontSize: 17, textTransform: "capitalize" }}>{v}</div>
    </div>
  );
}

function WaxPreview({ config }) {
  // Circular wax impression with monogram / initials
  const size = 280;
  const isRound = config.shape.id.startsWith("round") || config.shape.id === "scalloped";
  const isShield = config.shape.id === "shield";
  const isOval = config.shape.id === "oval";
  const color = config.wax.hex;
  const rim = 8;

  let clipPath = "circle(48% at 50% 50%)";
  if (isShield) clipPath = "polygon(50% 100%, 0 70%, 0 0, 100% 0, 100% 70%)";
  if (isOval) clipPath = "ellipse(42% 48% at 50% 50%)";
  if (config.shape.id === "hexagon") clipPath = "polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%)";
  if (config.shape.id === "scalloped") clipPath = "circle(46% at 50% 50%)";

  return (
    <div style={{ width: size, height: size, position: "relative" }}>
      <div style={{
        position: "absolute", inset: 0,
        background: `radial-gradient(ellipse at 30% 30%, ${shade(color, 55)} 0%, ${color} 35%, ${shade(color, -30)} 80%, ${shade(color, -50)} 100%)`,
        clipPath,
        boxShadow: `inset 0 0 30px ${shade(color, -45)}, inset 0 0 8px ${shade(color, 40)}`,
      }} />
      <div style={{
        position: "absolute", inset: rim * 2,
        clipPath,
        display: "flex", alignItems: "center", justifyContent: "center",
        filter: `drop-shadow(1px 1px 0 ${shade(color, 30)}) drop-shadow(-1px -1px 2px ${shade(color, -30)})`,
        color: shade(color, -25),
        fontFamily: "var(--serif-display)",
        fontSize: 96, lineHeight: 1,
        fontStyle: config.script.id === "chancery" ? "italic" : "normal",
        fontWeight: config.script.id === "roman" ? 600 : 400,
        letterSpacing: "-0.03em",
      }}>
        {config.type === "monogram" ? config.initials : "∴"}
      </div>
    </div>
  );
}

function shade(hex, pct) {
  const num = parseInt(hex.replace("#",""), 16);
  const r = Math.max(0, Math.min(255, (num >> 16) + pct));
  const g = Math.max(0, Math.min(255, ((num >> 8) & 0xff) + pct));
  const b = Math.max(0, Math.min(255, (num & 0xff) + pct));
  return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
}

window.CustomPage = CustomPage;
