// app.jsx
// Mounts the Tweaks panel (palette/density/hero/RTL) and the multi-step Book-a-Tour modal.

const { useState, useEffect, useMemo, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "redwood",
  "density": "standard",
  "heroLayout": "split",
  "rtl": false,
  "showFab": true
}/*EDITMODE-END*/;

const PALETTE_OPTS = [
  ["#6E1F2D", "#FAF3E6", "#7B8E5E"],   // redwood (default)
  ["#5A1620", "#F6EDE0", "#A36C24"],   // bordeaux
  ["#4A6240", "#F6F1E4", "#6E1F2D"],   // sage-led
  ["#1F2A2B", "#F2EEE5", "#B57928"],   // ink
];
const PALETTE_NAMES = ["redwood", "bordeaux", "sage", "ink"];

const BRANCHES = [
  { id: "palm-jumeirah", name: "Palm Jumeirah", area: "Golden Mile, Building 8", phone: "04 422 8581", waText: "Palm%20Jumeirah" },
  { id: "al-garhoud",    name: "Al Garhoud",     area: "Villa 45, 20 C Street · MEAB", phone: "04 282 7046", waText: "Al%20Garhoud" },
  { id: "jumeirah-park", name: "Jumeirah Park",  area: "Level 1, East Pavilion", phone: "04 453 8688", waText: "Jumeirah%20Park" },
  { id: "al-furjan",     name: "Al Furjan",      area: "West Pavilion · new campus", phone: "04 886 0227", waText: "Al%20Furjan" },
  { id: "tilal-al-ghaf", name: "Tilal Al Ghaf",  area: "Tilal Al Ghaf community", phone: "050 213 8502", waText: "Tilal%20Al%20Ghaf" },
];

const AGE_GROUPS = [
  "3 – 12 months · Babies",
  "1 – 2 years · Toddlers",
  "2 – 3 years · Preschool",
  "3 – 4 years · Foundation",
  "4 – 6 years · Advanced Montessori",
];

// ────────────────────────────────────────────────────────────────────────────
// BOOK A TOUR MODAL
// ────────────────────────────────────────────────────────────────────────────
function TourModal({ open, prefill, onClose }) {
  const [step, setStep] = useState(0);
  const [branch, setBranch] = useState(prefill?.branch || "palm-jumeirah");
  const [age, setAge] = useState(prefill?.age || AGE_GROUPS[2]);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [date, setDate] = useState("");
  const [child, setChild] = useState("");

  useEffect(() => {
    if (open) {
      setStep(0);
      if (prefill?.branch) setBranch(prefill.branch);
      if (prefill?.age) setAge(prefill.age);
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open, prefill]);

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

  if (!open) return null;

  const selectedBranch = BRANCHES.find(b => b.id === branch) || BRANCHES[0];
  const waLink = `https://wa.me/971502138502?text=Hi%20Redwood%2C%20I%27d%20like%20to%20book%20a%20tour%20at%20${selectedBranch.waText}%20for%20my%20child%20(${encodeURIComponent(age)})`;

  const next = () => setStep(s => Math.min(s + 1, 3));
  const back = () => setStep(s => Math.max(s - 1, 0));
  const submit = (e) => { e?.preventDefault?.(); setStep(3); };

  return (
    <div className="modal-veil" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Book a tour">

        <aside className="modal-side">
          <div className="modal-side-eb">Book a tour · ~45 min</div>
          <h2>See the classroom <em>in motion.</em></h2>
          <p>Observe a real Montessori work cycle, meet the guides, and walk every space your child would use. We'll confirm your slot within one working day.</p>
          <div className="modal-trust">
            <span>KHDA-registered</span>
            <span>MEAB · Garhoud</span>
            <span>Authentic Montessori</span>
          </div>
        </aside>

        <div className="modal-form">
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>

          <div className="modal-steps">
            <span>Step {step === 3 ? 3 : step + 1} of 3</span>
            <div className={`modal-step-bar ${step >= 1 ? "is-on" : ""}`}></div>
            <div className={`modal-step-dot ${step >= 0 ? "is-on" : ""}`}></div>
            <div className={`modal-step-bar ${step >= 2 ? "is-on" : ""}`}></div>
          </div>

          {step === 0 && (
            <>
              <h3>Choose a branch.</h3>
              <p className="modal-sub">Tours happen at the branch — pick the one closest to home.</p>
              <div className="modal-branches">
                {BRANCHES.map(b => (
                  <button key={b.id} type="button"
                    className={`mb-opt ${branch === b.id ? "is-on" : ""}`}
                    onClick={() => setBranch(b.id)}>
                    <span className="mb-opt-name">{b.name}</span>
                    <span className="mb-opt-area">{b.area}</span>
                  </button>
                ))}
              </div>
              <div className="modal-actions">
                <button className="cta cta-primary" onClick={next}>Continue →</button>
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h3>About your child.</h3>
              <p className="modal-sub">So we can show you the right classroom.</p>
              <div className="modal-fields">
                <label className="ff-row">
                  <span>Child's age group</span>
                  <select value={age} onChange={e => setAge(e.target.value)}>
                    {AGE_GROUPS.map(a => <option key={a}>{a}</option>)}
                  </select>
                </label>
                <label className="ff-row">
                  <span>Child's first name <em style={{opacity:.5, fontStyle:'normal'}}>· optional</em></span>
                  <input value={child} onChange={e => setChild(e.target.value)} placeholder="So our guides can greet them" />
                </label>
                <label className="ff-row">
                  <span>Preferred tour date</span>
                  <input type="date" value={date} onChange={e => setDate(e.target.value)} />
                </label>
              </div>
              <div className="modal-actions">
                <button className="ghost-back" onClick={back}>← Back</button>
                <button className="cta cta-primary" onClick={next}>Continue →</button>
              </div>
            </>
          )}

          {step === 2 && (
            <form onSubmit={submit}>
              <h3>Where do we reach you?</h3>
              <p className="modal-sub">A guide from {selectedBranch.name} will confirm within one working day.</p>

              <div className="modal-wa-handoff">
                <span>Prefer WhatsApp?</span>
                <a href={waLink} target="_blank" rel="noopener">Send via WhatsApp →</a>
              </div>

              <div className="modal-fields two-col">
                <label className="ff-row">
                  <span>Your name</span>
                  <input required value={name} onChange={e => setName(e.target.value)} />
                </label>
                <label className="ff-row">
                  <span>Mobile (UAE)</span>
                  <input required type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+971" />
                </label>
              </div>
              <div className="modal-fields">
                <label className="ff-row">
                  <span>Email</span>
                  <input required type="email" value={email} onChange={e => setEmail(e.target.value)} />
                </label>
              </div>
              <div className="modal-actions">
                <button type="button" className="ghost-back" onClick={back}>← Back</button>
                <button type="submit" className="cta cta-primary">Request my tour →</button>
              </div>
            </form>
          )}

          {step === 3 && (
            <div className="modal-done">
              <div className="modal-done-mark">✓</div>
              <h3>Your tour is requested.</h3>
              <p>A guide from <strong>{selectedBranch.name}</strong> will confirm your slot within one working day. Keep an eye on email or WhatsApp.</p>
              <div className="modal-done-actions">
                <a className="cta cta-primary" href={waLink} target="_blank" rel="noopener">Open WhatsApp</a>
                <button className="ghost-back" onClick={onClose}>Done</button>
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// TWEAKS APP
// ────────────────────────────────────────────────────────────────────────────
function TweaksApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks to <html> root
  useEffect(() => {
    document.documentElement.setAttribute("data-palette", t.palette);
    document.documentElement.setAttribute("data-density", t.density);
    document.documentElement.setAttribute("dir", t.rtl ? "rtl" : "ltr");
    const hero = document.querySelector(".hero");
    if (hero) hero.setAttribute("data-layout", t.heroLayout);
    const fab = document.getElementById("wafab");
    if (fab) fab.style.display = t.showFab ? "" : "none";
  }, [t]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Palette" />
      <TweakColor
        label="Brand palette"
        value={PALETTE_OPTS[PALETTE_NAMES.indexOf(t.palette)] || PALETTE_OPTS[0]}
        options={PALETTE_OPTS}
        onChange={(arr) => {
          const idx = PALETTE_OPTS.findIndex(p => p[0] === arr[0]);
          if (idx >= 0) setTweak("palette", PALETTE_NAMES[idx]);
        }}
      />

      <TweakSection label="Layout" />
      <TweakRadio
        label="Density"
        value={t.density}
        options={["airy", "standard", "compact"]}
        onChange={(v) => setTweak("density", v)}
      />
      <TweakSelect
        label="Hero layout"
        value={t.heroLayout}
        options={[
          { value: "split",  label: "Split — image + copy" },
          { value: "bleed",  label: "Quiet — center, no image" },
          { value: "asym",   label: "Asymmetric — taller image" },
        ]}
        onChange={(v) => setTweak("heroLayout", v)}
      />

      <TweakSection label="Localisation" />
      <TweakToggle
        label="RTL (Arabic direction)"
        value={t.rtl}
        onChange={(v) => setTweak("rtl", v)}
      />

      <TweakSection label="Floating" />
      <TweakToggle
        label="WhatsApp button"
        value={t.showFab}
        onChange={(v) => setTweak("showFab", v)}
      />
    </TweaksPanel>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// ROOT — wires modal triggers + mounts apps
// ────────────────────────────────────────────────────────────────────────────
function ModalRoot() {
  const [open, setOpen] = useState(false);
  const [prefill, setPrefill] = useState({});

  const openModal = useCallback((data = {}) => {
    setPrefill(data);
    setOpen(true);
  }, []);

  useEffect(() => {
    const onClick = (e) => {
      const t = e.target.closest('[data-action="open-tour"]');
      if (t) {
        e.preventDefault();
        const branch = t.dataset.branch;
        openModal(branch ? { branch } : {});
        return;
      }
      const bp = e.target.closest('[data-action="open-branch-placeholder"]');
      if (bp) {
        e.preventDefault();
        const branch = bp.dataset.branch;
        openModal({ branch });
      }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, [openModal]);

  // Quick-tour form on home page
  useEffect(() => {
    const f = document.querySelector('[data-form="quick-tour"]');
    if (!f) return;
    const onSub = (e) => {
      e.preventDefault();
      const branch = f.querySelector('[name="branch"]').value;
      const age = f.querySelector('[name="age"]').value;
      openModal({ branch, age });
    };
    f.addEventListener("submit", onSub);
    return () => f.removeEventListener("submit", onSub);
  }, [openModal]);

  // Locale buttons (visual only; persist via tweak when RTL pressed)
  useEffect(() => {
    const onClick = (e) => {
      const btn = e.target.closest('.loc-btn');
      if (!btn) return;
      document.querySelectorAll('.loc-btn').forEach(b => b.classList.remove('is-on'));
      btn.classList.add('is-on');
      const lang = btn.dataset.lang;
      document.documentElement.lang = lang;
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  return <TourModal open={open} prefill={prefill} onClose={() => setOpen(false)} />;
}

// Mount
ReactDOM.createRoot(document.getElementById("tour-root")).render(<ModalRoot />);
ReactDOM.createRoot(document.getElementById("tweaks-root")).render(<TweaksApp />);
