// Shared components — Nav, Footer, Buttons, Icons, FAB, Modal
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Icons ----------
const Icon = ({ name, size = 20 }) => {
  const s = size;
  const paths = {
    arrow: <path d="M5 12h14M13 6l6 6-6 6" />,
    phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72a2 2 0 0 1 1.72 2.03Z" />,
    wa: <><path d="M16.6 14a4.2 4.2 0 0 1-1.9 1.5 4.5 4.5 0 0 1-2 .5 6 6 0 0 1-2.4-.5 8 8 0 0 1-3.2-2.4 8 8 0 0 1-2.4-3.2 6 6 0 0 1-.5-2.4c0-.7.2-1.4.5-2A4.2 4.2 0 0 1 6.2 3.6c.5-.5 1.1-.7 1.7-.7.2 0 .4 0 .6.1.2 0 .4.2.5.5l1 2.3c.1.3.2.5.1.7-.1.2-.2.5-.4.7l-.5.5c-.2.2-.3.4-.2.6a8 8 0 0 0 4.5 4.5c.2.1.4 0 .6-.2l.5-.5c.2-.2.5-.3.7-.4.2-.1.4 0 .7.1l2.3 1c.3.1.4.3.5.5 0 .2.1.4.1.6 0 .6-.2 1.2-.7 1.7Z" /><circle cx="12" cy="12" r="10" /></>,
    mail: <><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-10 7L2 7" /></>,
    pin: <><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></>,
    calendar: <><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></>,
    play: <polygon points="5 3 19 12 5 21 5 3" />,
    check: <path d="M20 6 9 17l-5-5" />,
    classroom: <><rect x="3" y="4" width="18" height="14" rx="2" /><path d="M3 9h18M8 13h2M14 13h2M12 18v3M8 21h8" /></>,
    art: <><circle cx="13.5" cy="6.5" r="2.5" /><circle cx="17.5" cy="11.5" r="2.5" /><circle cx="6.5" cy="13.5" r="2.5" /><circle cx="9.5" cy="18.5" r="2.5" /><path d="M12 2a10 10 0 1 0 0 20c2 0 2-2 1-3-1-1-1-2 0-3 1-1 4-1 5-3 1-2-2-11-6-11Z" /></>,
    music: <><circle cx="6" cy="18" r="3" /><circle cx="18" cy="16" r="3" /><path d="M9 18V5l12-2v13" /></>,
    book: <><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" /><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" /></>,
    media: <><rect x="2" y="3" width="20" height="14" rx="2" /><path d="M8 21h8M12 17v4" /></>,
    field: <><circle cx="12" cy="12" r="10" /><path d="M12 2a14 14 0 0 0 0 20M12 2a14 14 0 0 1 0 20M2 12h20" /></>,
    tree: <><path d="M12 22V12" /><path d="M5 12a3 3 0 0 1-3-3 3 3 0 0 1 3-3c0-2 2-4 4-4s4 2 4 4c0 2-2 3-2 3M19 12a3 3 0 0 0 3-3 3 3 0 0 0-3-3c0-2-2-4-4-4" /><path d="M5 12c0 3 3 5 7 5s7-2 7-5" /></>,
    gym: <><path d="M6.5 6.5 17.5 17.5M21 21l-1-1M3 3l1 1M18 22l4-4M2 6l4-4M3 10l7-7M14 21l7-7" /><rect x="7" y="9.5" width="10" height="5" rx="1" transform="rotate(45 12 12)" /></>,
    star: <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />,
    globe: <><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20" /></>,
    leaf: <><path d="M11 20A7 7 0 0 1 4 13c0-4 3-9 9-11 1 7 0 13-2 18" /><path d="M2 22 11 13" /></>,
    shield: <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />,
    sparkle: <><path d="m12 3-2 5-5 2 5 2 2 5 2-5 5-2-5-2z" /><path d="M19 3v4M5 17v4M17 19h4M3 5h4" /></>,
    sun: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" /></>,
    heart: <path d="M19 14c1.5-1.5 3-3.3 3-5.5A5.5 5.5 0 0 0 16.5 3 5.5 5.5 0 0 0 12 5.5 5.5 5.5 0 0 0 7.5 3 5.5 5.5 0 0 0 2 8.5c0 2.2 1.5 4 3 5.5l7 7Z" />,
    close: <><path d="M18 6 6 18M6 6l12 12" /></>,
    menu: <><path d="M3 12h18M3 6h18M3 18h18" /></>,
    chev: <path d="m9 18 6-6-6-6" />,
    chevDown: <path d="m6 9 6 6 6-6" />,
    instagram: <><rect x="2" y="2" width="20" height="20" rx="5" /><path d="M16 11.37a4 4 0 1 1-4.74-4.74 4 4 0 0 1 4.74 4.74Z M17.5 6.5h.01" /></>,
    facebook: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />,
  };
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      {paths[name] || null}
    </svg>
  );
};

// ---------- Brand mark (mini-crest as SVG fallback so it always renders) ----------
const BrandMark = ({ size = 44 }) => (
  <img src="assets/logo.svg" width={size} height={size * 1.155} alt="Odyssey Nursery"
    style={{ display: 'block', borderRadius: 6, background: 'var(--cream)' }} />
);

// ---------- Locale switch ----------
const LocaleSwitch = ({ locale, onChange }) => (
  <div className="locale-switch" role="tablist" aria-label="Language">
    {["EN", "AR", "RU", "ZH"].map(l => (
      <button key={l} className={locale === l ? "active" : ""} onClick={() => onChange(l)}>{l}</button>
    ))}
  </div>
);

// ---------- Nav ----------
const Nav = ({ route, navigate, locale, setLocale, onBookTour }) => {
  const items = [
    ["home", "Home"],
    ["curriculum", "Curriculum"],
    ["programmes", "Programmes"],
    ["facilities", "Facilities"],
    ["branches", "Branches"],
    ["admissions", "Admissions"],
    ["about", "About"]
  ];
  return (
    <header className="nav">
      <div className="nav-inner">
        <a href="#" className="nav-logo" onClick={(e) => { e.preventDefault(); navigate("home"); }}>
          <BrandMark size={42} />
          <div className="wordmark">Odyssey<small>Nursery · Dubai</small></div>
        </a>
        <nav className="nav-menu">
          {items.map(([k, label]) => (
            <a key={k} href={"#" + k} className={"nav-link " + (route === k ? "active" : "")}
              onClick={(e) => { e.preventDefault(); navigate(k); }}>{label}</a>
          ))}
        </nav>
        <div className="nav-cta">
          <LocaleSwitch locale={locale} onChange={setLocale} />
          <a href="tel:800-REGGIO" className="btn btn-ghost btn-sm" title="Call 800-REGGIO">
            <Icon name="phone" size={14} /> 800-REGGIO
          </a>
          <button className="btn btn-primary btn-sm" onClick={onBookTour}>
            Book a Tour <Icon name="arrow" size={14} />
          </button>
        </div>
      </div>
    </header>
  );
};

// ---------- WhatsApp FAB ----------
const Fab = () => (
  <a href={window.OdysseyData.contact.waLink} target="_blank" rel="noopener" className="fab" aria-label="WhatsApp Odyssey Nursery">
    <span className="fab-label">Chat on WhatsApp</span>
    <Icon name="wa" size={28} />
  </a>
);

// ---------- Mobile sticky CTA ----------
const MobileCta = ({ onBookTour }) => (
  <div className="mob-cta">
    <a href="tel:800-REGGIO" className="btn btn-ghost btn-sm"><Icon name="phone" size={14} /> Call</a>
    <button className="btn btn-primary btn-sm" onClick={onBookTour}>Book a Tour</button>
  </div>
);

// ---------- Modal ----------
const Modal = ({ open, onClose, children }) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
};

// ---------- Footer ----------
const Footer = ({ navigate }) => {
  const D = window.OdysseyData;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 22 }}>
              <BrandMark size={50} />
              <div style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--paper)' }}>
                Odyssey Nursery
                <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,251,245,0.5)', marginTop: 2, fontWeight: 600 }}>
                  Reggio Emilia · Dubai
                </div>
              </div>
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 20, maxWidth: 360 }}>
              A premium, Reggio Emilia–inspired nursery group across six Dubai branches. Part of Kids First Group.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              <a href="#" aria-label="Instagram" style={{ width: 38, height: 38, border: '1px solid rgba(255,251,245,0.18)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="instagram" size={16} /></a>
              <a href="#" aria-label="Facebook" style={{ width: 38, height: 38, border: '1px solid rgba(255,251,245,0.18)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="facebook" size={16} /></a>
              <a href={D.contact.waLink} aria-label="WhatsApp" style={{ width: 38, height: 38, border: '1px solid rgba(255,251,245,0.18)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="wa" size={16} /></a>
            </div>
          </div>
          <div>
            <h4>Visit</h4>
            <ul>
              {D.branches.map(b => (
                <li key={b.id}><a href={"#branch-" + b.id} onClick={(e) => { e.preventDefault(); navigate("branch", b.id); }}>{b.name}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>Learn</h4>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("curriculum"); }}>Curriculum & Approach</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("programmes"); }}>Programmes & Ages</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("facilities"); }}>Facilities</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("admissions"); }}>Admissions & Fees</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("about"); }}>About Odyssey</a></li>
            </ul>
          </div>
          <div>
            <h4>Contact</h4>
            <ul>
              <li><a href="tel:800-REGGIO"><strong style={{ color: 'var(--paper)' }}>800-REGGIO</strong> · toll-free</a></li>
              <li><a href={"tel:" + D.contact.mobile.replace(/\s/g, "")}>{D.contact.mobile}</a></li>
              <li><a href={"mailto:" + D.contact.emailGeneral}>{D.contact.emailGeneral}</a></li>
              <li><a href="https://kidsfirstgroup.com" target="_blank" rel="noopener">Kids First Group ↗</a></li>
              <li><a href="https://pea.kidsfirstgroup.com" target="_blank" rel="noopener">Parent Education Academy ↗</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Odyssey Nursery. A Kids First Group company.</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="#">Privacy</a>
            <a href="#">Safeguarding</a>
            <a href="#">KHDA</a>
          </div>
        </div>
      </div>
    </footer>
  );
};

// ---------- Tour booking form (multi-step) ----------
const TourForm = ({ onClose, presetBranch }) => {
  const D = window.OdysseyData;
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [data, setData] = useState({
    branch: presetBranch || "",
    age: "",
    name: "",
    phone: "",
    email: "",
    childAge: "",
    when: "",
    msg: ""
  });
  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const steps = [
    { title: "Which branch?", help: "Pick the campus that's most convenient." },
    { title: "About your child", help: "We'll match the right age group and key person." },
    { title: "Your contact", help: "We reply within one working day." }
  ];

  const next = () => setStep(s => Math.min(s + 1, 2));
  const back = () => setStep(s => Math.max(s - 1, 0));
  const submit = () => setDone(true);

  if (done) {
    return (
      <div style={{ textAlign: 'center', padding: '12px 4px' }}>
        <div className="success-icon"><Icon name="check" size={28} /></div>
        <h3 style={{ fontSize: 26 }}>Tour request received</h3>
        <p style={{ color: 'var(--ink-soft)', margin: '12px auto 24px', maxWidth: 340 }}>
          Thank you, {data.name || "friend"}. A member of the Odyssey admissions team will reply within one working day.
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <a href={D.contact.waLink} target="_blank" rel="noopener" className="btn btn-leaf">
            <Icon name="wa" size={16} /> WhatsApp us now
          </a>
          <button className="btn btn-ghost" onClick={onClose}>Close</button>
        </div>
      </div>
    );
  }

  const canNext =
    (step === 0 && data.branch) ||
    (step === 1 && data.age) ||
    (step === 2 && data.name && data.phone);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <span className="eyebrow">Book a Tour · Step {step + 1} of 3</span>
        <button onClick={onClose} aria-label="Close" style={{ width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-soft)' }}>
          <Icon name="close" size={18} />
        </button>
      </div>

      <div className="steps">
        {[0, 1, 2].map(i => (
          <div key={i} className={"step-dot " + (i < step ? "done" : i === step ? "active" : "")} style={{ background: i < step ? 'var(--leaf)' : i === step ? 'var(--brand-brown)' : 'var(--line)' }} />
        ))}
      </div>

      <h3 style={{ fontSize: 28, marginBottom: 6 }}>{steps[step].title}</h3>
      <p style={{ color: 'var(--ink-soft)', fontSize: 14, marginBottom: 22 }}>{steps[step].help}</p>

      {step === 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {D.branches.map(b => (
            <button key={b.id} onClick={() => update("branch", b.id)}
              style={{
                padding: 14, borderRadius: 12, textAlign: 'left',
                border: '1.5px solid ' + (data.branch === b.id ? 'var(--brand-brown)' : 'var(--line)'),
                background: data.branch === b.id ? 'var(--paper-soft)' : 'var(--paper)',
                transition: 'all .15s'
              }}>
              <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--brand-brown)', marginBottom: 2 }}>{b.name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{b.area}</div>
            </button>
          ))}
        </div>
      )}

      {step === 1 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
            {D.ageGroups.map(a => (
              <button key={a.id} onClick={() => update("age", a.id)}
                style={{
                  padding: 12, borderRadius: 10, textAlign: 'center',
                  border: '1.5px solid ' + (data.age === a.id ? 'var(--brand-brown)' : 'var(--line)'),
                  background: data.age === a.id ? 'var(--paper-soft)' : 'var(--paper)',
                  fontSize: 12, fontWeight: 600, color: 'var(--brand-brown)'
                }}>
                {a.title}
                <div style={{ fontSize: 10, color: 'var(--ink-soft)', marginTop: 4, fontWeight: 500 }}>{a.range}</div>
              </button>
            ))}
          </div>
          <div className="field">
            <label>Child's date of birth (optional)</label>
            <input type="text" placeholder="DD / MM / YYYY" value={data.childAge} onChange={e => update("childAge", e.target.value)} />
          </div>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="field">
            <label>Parent name *</label>
            <input value={data.name} onChange={e => update("name", e.target.value)} placeholder="Full name" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div className="field">
              <label>Phone *</label>
              <input value={data.phone} onChange={e => update("phone", e.target.value)} placeholder="+971 ..." />
            </div>
            <div className="field">
              <label>Email</label>
              <input value={data.email} onChange={e => update("email", e.target.value)} placeholder="you@example.com" />
            </div>
          </div>
          <div className="field">
            <label>Preferred visit time</label>
            <input value={data.when} onChange={e => update("when", e.target.value)} placeholder="Weekday morning, this Thursday, etc." />
          </div>
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 28 }}>
        <button className="btn btn-ghost btn-sm" onClick={step === 0 ? onClose : back}>
          {step === 0 ? "Cancel" : "Back"}
        </button>
        {step < 2 ? (
          <button className="btn btn-primary" onClick={next} disabled={!canNext}
            style={{ opacity: canNext ? 1 : 0.5, pointerEvents: canNext ? 'auto' : 'none' }}>
            Continue <Icon name="arrow" size={14} />
          </button>
        ) : (
          <button className="btn btn-sun" onClick={submit} disabled={!canNext}
            style={{ opacity: canNext ? 1 : 0.5, pointerEvents: canNext ? 'auto' : 'none' }}>
            <Icon name="calendar" size={14} /> Request my tour
          </button>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { Icon, BrandMark, Nav, Footer, Fab, MobileCta, Modal, TourForm });
