/* global React, ReactDOM, Wordmark, Navbar, Hero, Ethos, CollectionsSection, Atelier, Maison, Occasions, AppointmentBand, Showrooms, Footer, QuickView, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakSelect */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero_variant": "noir",
  "accent": "#b8954e",
  "hero_image": "media/sway-bracelet-wing.webp"
}/*EDITMODE-END*/;

// ────────────────────────────────────────────────────────────
// Appointment Modal — multi-step flow
// ────────────────────────────────────────────────────────────
function AppointmentModal({ open, onClose }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    showroom: "Dubai",
    date: "",
    time: "",
    interest: "",
    name: "",
    email: "",
    phone: "",
    message: "",
    whatsapp: true,
  });
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  useEffect(() => {
    if (open) { setStep(0); }
  }, [open]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  const steps = ["Showroom", "When", "Interest", "Contact"];
  const next = () => setStep((s) => Math.min(s + 1, steps.length));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  return (
    <div className={"modal-backdrop " + (open ? "open" : "")} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-aside">
          <div>
            <Wordmark size={20} light />
            <h3 className="display" style={{ marginTop: 32 }}>
              An hour, in <em>private.</em>
            </h3>
            <div className="lede">
              "Spend an hour with a Lawson specialist. Preview Gate, Lamina &amp; Sway pieces in
              person — or commission something entirely your own."
            </div>
          </div>
          <div className="promise">Verified · WhatsApp +971 54 405 5525</div>
        </div>

        <div className="modal-form">
          <button className="modal-close" onClick={onClose}>
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.2">
              <line x1="1" y1="1" x2="13" y2="13" />
              <line x1="13" y1="1" x2="1" y2="13" />
            </svg>
          </button>

          <div className="steps">
            {steps.map((s, i) => (
              <div key={s} className={"step-pip " + (i === step ? "active" : i < step ? "done" : "")} />
            ))}
          </div>

          {step < steps.length && (
            <>
              <div className="step-label">Step {step + 1} of {steps.length}</div>
            </>
          )}

          {step === 0 && (
            <>
              <h4 className="display">Choose your <em>showroom.</em></h4>
              <div className="step-sub">Both are by invitation. Dubai is our flagship private showroom.</div>
              <div className="option-grid">
                {[
                  { city: "Dubai", sub: "Design District · d3 4A-506" },
                  { city: "London", sub: "One Seymour Street · W1H 7JW" },
                ].map((o) => (
                  <button
                    key={o.city}
                    className={"option-tile " + (data.showroom === o.city ? "selected" : "")}
                    onClick={() => set("showroom", o.city)}
                  >
                    <div className="ot-city">{o.city}</div>
                    <div className="ot-sub">{o.sub}</div>
                  </button>
                ))}
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h4 className="display">When suits you <em>best?</em></h4>
              <div className="step-sub">Slots are confirmed by phone or WhatsApp within 24 hours.</div>
              <div className="field-row">
                <div className="field">
                  <label>Preferred date</label>
                  <input type="date" value={data.date} onChange={(e) => set("date", e.target.value)} />
                </div>
                <div className="field">
                  <label>Time</label>
                  <select value={data.time} onChange={(e) => set("time", e.target.value)}>
                    <option value="">Select a time</option>
                    <option>Morning · 10:00 – 12:00</option>
                    <option>Afternoon · 13:00 – 15:00</option>
                    <option>Late afternoon · 15:00 – 17:00</option>
                    <option>Evening · by request</option>
                  </select>
                </div>
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <h4 className="display">What brings you <em>in?</em></h4>
              <div className="step-sub">Tell us a little — we'll prepare a tray ahead of your visit.</div>
              <div className="option-grid">
                {[
                  { v: "Proposal / engagement", s: "Sway · Gate · Lamina rings" },
                  { v: "Gifting", s: "Studs · Pendants · Lamina" },
                  { v: "Bespoke commission", s: "One-of-a-kind, made in Italy" },
                  { v: "Just to browse", s: "Tea and the current collections" },
                ].map((o) => (
                  <button
                    key={o.v}
                    className={"option-tile " + (data.interest === o.v ? "selected" : "")}
                    onClick={() => set("interest", o.v)}
                  >
                    <div className="ot-city" style={{ fontSize: 18 }}>{o.v}</div>
                    <div className="ot-sub">{o.s}</div>
                  </button>
                ))}
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <h4 className="display">Where shall we <em>reach you?</em></h4>
              <div className="step-sub">We'll confirm within 24 hours and never share your details.</div>
              <div className="field">
                <label>Your name</label>
                <input value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="Full name" />
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Email</label>
                  <input type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" />
                </div>
                <div className="field">
                  <label>Phone (with country code)</label>
                  <input value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+971 …" />
                </div>
              </div>
              <div className="field">
                <label>Anything else</label>
                <textarea value={data.message} onChange={(e) => set("message", e.target.value)} rows={2} placeholder="A piece you're curious about, a budget range, an occasion…" />
              </div>
              <label style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12, letterSpacing: "0.04em", color: "rgba(20,16,12,0.7)" }}>
                <input type="checkbox" checked={data.whatsapp} onChange={(e) => set("whatsapp", e.target.checked)} style={{ width: "auto" }} />
                I'd prefer a WhatsApp confirmation.
              </label>
            </>
          )}

          {step === steps.length && (
            <div className="success-state">
              <div className="check">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="var(--accent)" strokeWidth="1.4">
                  <path d="M4 10.5l4 4 8-9" />
                </svg>
              </div>
              <h4 className="display">Your request is <em>with us.</em></h4>
              <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", color: "rgba(20,16,12,0.65)", maxWidth: "36ch", margin: "12px auto 24px", fontSize: 16 }}>
                A specialist will reach out within 24 hours to confirm your visit at the {data.showroom} showroom.
              </div>
              <a
                className="btn btn-primary"
                href={`https://wa.me/971544055525?text=Hi%20Lawson%2C%20I%27ve%20just%20requested%20an%20appointment%20in%20${data.showroom}.`}
                target="_blank"
                rel="noreferrer"
                style={{ marginBottom: 12 }}
              >
                Continue on WhatsApp <span className="arrow" />
              </a>
              <div>
                <button className="modal-back" onClick={onClose}>Close</button>
              </div>
            </div>
          )}

          {step < steps.length && (
            <div className="modal-nav">
              <button className="modal-back" onClick={back} disabled={step === 0}>← Back</button>
              <button className="btn btn-primary" onClick={next}>
                {step === steps.length - 1 ? "Confirm request" : "Continue"} <span className="arrow" />
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Tweaks — accent metal, hero variant, hero image
// ────────────────────────────────────────────────────────────
function LawsonTweaks() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // apply accent color CSS var live
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
    // derive accent-deep by darkening
    const darken = (hex) => {
      const h = hex.replace("#", "");
      const r = parseInt(h.slice(0,2),16), g = parseInt(h.slice(2,4),16), b = parseInt(h.slice(4,6),16);
      const f = 0.72;
      const to = (x) => Math.max(0, Math.min(255, Math.round(x*f))).toString(16).padStart(2,"0");
      return "#" + to(r) + to(g) + to(b);
    };
    document.documentElement.style.setProperty("--accent-deep", darken(t.accent));
  }, [t.accent]);

  return (
    <TweaksPanel>
      <TweakSection label="Hero">
        <TweakRadio
          label="Variant"
          value={t.hero_variant}
          onChange={(v) => setTweak("hero_variant", v)}
          options={[
            { value: "noir", label: "Noir" },
            { value: "editorial", label: "Editorial" },
            { value: "split", label: "Split" },
          ]}
        />
        <TweakSelect
          label="Hero piece"
          value={t.hero_image}
          onChange={(v) => setTweak("hero_image", v)}
          options={[
            { value: "media/sway-bracelet-wing.webp", label: "Sway bracelet, on hand (dramatic)" },
            { value: "media/lifestyle-sway-necklace.webp", label: "Sway necklace, on neckline" },
            { value: "media/lifestyle-gate-rings.webp", label: "Gate double rings, on hand" },
            { value: "media/lifestyle-sway-ring.webp", label: "Sway ring, on hand" },
            { value: "media/lifestyle-gate-him.webp", label: "Gate ring for him, styled" },
          ]}
        />
      </TweakSection>
      <TweakSection label="Accent metal">
        <TweakColor
          label="Accent"
          value={t.accent}
          onChange={(v) => setTweak("accent", v)}
          options={["#b8954e", "#c79b87", "#8a8884", "#9a7b3d", "#d8b878"]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ────────────────────────────────────────────────────────────
// App
// ────────────────────────────────────────────────────────────
function App() {
  const [t, _set] = useTweaks(TWEAK_DEFAULTS);
  const [bookOpen, setBookOpen] = useState(false);
  const [quickProduct, setQuickProduct] = useState(null);

  return (
    <>
      <Navbar onBook={() => setBookOpen(true)} mode={t.hero_variant === "editorial" ? "light" : "dark"} />
      <Hero variant={t.hero_variant} heroImage={t.hero_image} onBook={() => setBookOpen(true)} />
      <Ethos />
      <CollectionsSection />
      <Atelier onOpen={setQuickProduct} />
      <Maison />
      <Occasions />
      <AppointmentBand onBook={() => setBookOpen(true)} />
      <Showrooms />
      <Footer />

      <AppointmentModal open={bookOpen} onClose={() => setBookOpen(false)} />
      <QuickView product={quickProduct} onClose={() => setQuickProduct(null)} onBook={() => setBookOpen(true)} />
      <LawsonTweaks />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
