// App shell: Nav, locale switcher, consultation modal, mobile menu, sticky CTAs, and composition.

const LOCALES = [
  { id: "en", label: "EN" },
  { id: "ar", label: "AR" },
  { id: "ru", label: "RU" },
  { id: "zh", label: "ZH" },
];

function useLocale() {
  const [locale, setLocale] = useState(() => {
    try { return localStorage.getItem("cb_locale") || "en"; } catch { return "en"; }
  });
  useEffect(() => {
    window.__cbLocale = locale;
    try { localStorage.setItem("cb_locale", locale); } catch {}
    const dir = window.CBI18N[locale].dir;
    document.documentElement.setAttribute("dir", dir);
    document.documentElement.setAttribute("lang", locale);
  }, [locale]);
  return [locale, setLocale];
}

function Nav({ locale, setLocale, onBook, openMenu }) {
  const [scrolled, setScrolled] = useState(false);
  const t = window.CBI18N[locale];
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className={`cb-nav ${scrolled ? "is-scrolled" : ""}`}>
      <div className="cb-wrap cb-nav__inner">
        <a className="cb-nav__brand" href="#top"><CBLogo /></a>
        <nav className="cb-nav__links">
          <a href="#services">{t.nav.services}</a>
          <a href="#jurisdictions">{t.nav.jurisdictions}</a>
          <a href="#estimator">{t.nav.estimator}</a>
          <a href="#guides">{t.nav.guides}</a>
          <a href="#offices">{t.nav.offices}</a>
          <a href="#about">{t.nav.about}</a>
        </nav>
        <div className="cb-nav__right">
          <LocaleSwitcher locale={locale} setLocale={setLocale} />
          <CBButton kind="accent" onClick={onBook} className="cb-nav__cta">{t.nav.consult}</CBButton>
          <button className="cb-nav__burger" aria-label="Menu" onClick={openMenu}>{IconSet.menu}</button>
        </div>
      </div>
    </header>
  );
}

function LocaleSwitcher({ locale, setLocale }) {
  return (
    <div className="cb-loc" role="tablist" aria-label="Language">
      <span className="cb-loc__icon">{IconSet.globe}</span>
      {LOCALES.map(l => (
        <button
          key={l.id}
          role="tab"
          aria-selected={l.id === locale}
          className={`cb-loc__btn ${l.id === locale ? "is-on" : ""}`}
          onClick={() => setLocale(l.id)}
        >{l.label}</button>
      ))}
    </div>
  );
}

// ─── Consultation modal ───────────────────────────────────────────────
function ConsultationModal({ open, onClose }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({ service: "", jurisdiction: "", name: "", contact: "", message: "" });
  useEffect(() => {
    if (open) { setStep(0); setForm({ service: "", jurisdiction: "", name: "", contact: "", message: "" }); }
  }, [open]);
  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 services = window.CBDATA.services;
  const jurs = window.CBDATA.jurisdictions;

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

  return (
    <div className="cb-modal" role="dialog" aria-modal="true" aria-label="Book a consultation" onClick={(e) => { if (e.target.classList.contains("cb-modal")) onClose(); }}>
      <div className="cb-modal__panel">
        <button className="cb-modal__close" onClick={onClose} aria-label="Close">{IconSet.close}</button>
        <div className="cb-modal__head">
          <span className="cb-eyebrow">Book a free consultation</span>
          <div className="cb-modal__steps">
            {[0, 1, 2].map(i => <span key={i} className={`cb-modal__step ${i <= step ? "is-on" : ""} ${i === step ? "is-cur" : ""}`} />)}
          </div>
        </div>

        {step === 0 && (
          <div className="cb-modal__body">
            <h3 className="cb-h3">What's the focus?</h3>
            <p className="cb-modal__hint">Pick the closest fit — your consultant will refine.</p>
            <div className="cb-modal__grid">
              {services.map(s => (
                <button key={s.id} onClick={() => { setForm(f => ({ ...f, service: s.id })); next(); }} className={`cb-modal__choice ${form.service === s.id ? "is-on" : ""}`}>
                  <span className="cb-modal__choice-icon">{IconSet[SERVICE_ICON[s.id]]}</span>
                  <span className="cb-modal__choice-label">{s.name}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="cb-modal__body">
            <h3 className="cb-h3">Where are you setting up?</h3>
            <p className="cb-modal__hint">If you're not sure yet, pick "Not sure" — that's what we're here for.</p>
            <div className="cb-modal__grid cb-modal__grid--3">
              {[...jurs, { id: "not-sure", name: "Not sure yet" }].map(j => (
                <button key={j.id} onClick={() => { setForm(f => ({ ...f, jurisdiction: j.id })); next(); }} className={`cb-modal__choice cb-modal__choice--text ${form.jurisdiction === j.id ? "is-on" : ""}`}>
                  {j.name}
                </button>
              ))}
            </div>
            <div className="cb-modal__nav">
              <button className="cb-modal__back" onClick={back}>{IconSet.arrowL} Back</button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="cb-modal__body">
            <h3 className="cb-h3">How should we reach you?</h3>
            <p className="cb-modal__hint">Same consultant will reply on the channel you prefer.</p>
            <div className="cb-modal__form">
              <label><span>Name</span><input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} /></label>
              <label><span>Email or WhatsApp</span><input value={form.contact} onChange={e => setForm(f => ({ ...f, contact: e.target.value }))} /></label>
              <label className="cb-modal__form-wide"><span>Anything to add? (optional)</span><textarea rows="3" value={form.message} onChange={e => setForm(f => ({ ...f, message: e.target.value }))} /></label>
            </div>
            <div className="cb-modal__nav cb-modal__nav--end">
              <button className="cb-modal__back" onClick={back}>{IconSet.arrowL} Back</button>
              <CBButton kind="accent" icon="arrow" onClick={submit}>Send to a consultant</CBButton>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="cb-modal__body cb-modal__body--done">
            <div className="cb-modal__done-mark">{IconSet.check}</div>
            <h3 className="cb-h3">You're booked.</h3>
            <p className="cb-modal__hint">A Commitbiz advisor will WhatsApp you within one business day to confirm a 30-minute consultation. No fixed fees promised — we'll size the engagement together.</p>
            <div className="cb-modal__done-summary">
              <div><span>Focus</span>{services.find(s => s.id === form.service)?.name || "—"}</div>
              <div><span>Where</span>{form.jurisdiction === "not-sure" ? "Not sure yet" : (window.CBDATA.jurisdictions.find(j => j.id === form.jurisdiction)?.name || "—")}</div>
              <div><span>Reaching you on</span>{form.contact || "—"}</div>
            </div>
            <CBButton kind="primary" onClick={onClose}>Close</CBButton>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Mobile menu ───────────────────────────────────────────────────────
function MobileMenu({ open, onClose, locale, setLocale, onBook }) {
  if (!open) return null;
  const t = window.CBI18N[locale];
  const links = [
    ["#services", t.nav.services],
    ["#jurisdictions", t.nav.jurisdictions],
    ["#estimator", t.nav.estimator],
    ["#guides", t.nav.guides],
    ["#offices", t.nav.offices],
    ["#about", t.nav.about],
    ["#contact", t.nav.contact],
  ];
  return (
    <div className="cb-mm" role="dialog">
      <div className="cb-mm__head">
        <CBLogo />
        <button className="cb-mm__close" onClick={onClose} aria-label="Close menu">{IconSet.close}</button>
      </div>
      <nav className="cb-mm__links">
        {links.map(([h, l]) => <a key={h} href={h} onClick={onClose}>{l}{IconSet.arrowUpRight}</a>)}
      </nav>
      <div className="cb-mm__loc"><LocaleSwitcher locale={locale} setLocale={setLocale} /></div>
      <CBButton kind="accent" icon="arrow" onClick={() => { onClose(); onBook(); }} className="cb-mm__cta">{t.nav.consult}</CBButton>
    </div>
  );
}

// ─── Sticky CTAs ────────────────────────────────────────────────────────
function StickyCTAs({ onBook }) {
  const c = window.CBDATA.contact;
  return (
    <div className="cb-sticky" aria-hidden="false">
      <a className="cb-sticky__wa" href={`https://wa.me/${c.whatsapp}?text=Hi%20Commitbiz%2C%20I%27d%20like%20to%20enquire%20about%20...`} aria-label="WhatsApp">
        <span className="cb-sticky__wa-icon">{IconSet.whatsapp}</span>
        <span className="cb-sticky__wa-label">WhatsApp</span>
      </a>
    </div>
  );
}

// ─── App ────────────────────────────────────────────────────────────────
function App() {
  const [locale, setLocale] = useLocale();
  const [modal, setModal] = useState(false);
  const [menu, setMenu] = useState(false);
  const openBook = useCallback(() => setModal(true), []);
  const openEstimate = useCallback(() => {
    const el = document.getElementById("estimator");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  }, []);

  return (
    <div className="cb-app" id="top">
      <Nav locale={locale} setLocale={setLocale} onBook={openBook} openMenu={() => setMenu(true)} />
      <main>
        <Hero onBook={openBook} onEstimate={openEstimate} locale={locale} />
        <TrustStrip />
        <ServicesSection onEstimate={openEstimate} onBook={openBook} />
        <JurisdictionsSection />
        <EstimatorSection />
        <AboutSection />
        <OfficesSection />
        <GuidesSection />
        <ContactSection onBook={openBook} />
      </main>
      <Footer />
      <StickyCTAs onBook={openBook} />
      <ConsultationModal open={modal} onClose={() => setModal(false)} />
      <MobileMenu open={menu} onClose={() => setMenu(false)} locale={locale} setLocale={setLocale} onBook={openBook} />
    </div>
  );
}

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