/* =========================================================================
   app.jsx — main app: hash routing, language switching, page composition
   ========================================================================= */
const { useState, useEffect, useMemo, useRef } = React;

/* -------- Hash routing helpers -------- */
const ROUTES = {
  "":                    "home",
  "/":                   "home",
  "/cash":               "cash",
  "/waqf-services":      "waqf",
  "/government-employee":"gov",
  "/real-estate-liquidity": "liq"
};
const useHashRoute = () => {
  const [route, setRoute] = useState(() => {
    const h = window.location.hash.replace(/^#/, "");
    return ROUTES[h] || "home";
  });
  useEffect(() => {
    const onChange = () => {
      const h = window.location.hash.replace(/^#/, "");
      setRoute(ROUTES[h] || "home");
      window.scrollTo({ top: 0, behavior: "instant" });
      track("page_view", { route: h || "/" });
    };
    window.addEventListener("hashchange", onChange);
    track("page_view", { route: window.location.hash.replace(/^#/, "") || "/" });
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return route;
};

/* -------- Tracking placeholders (Meta / Snapchat / GA) --------
   In production these IDs are filled and the SDKs are loaded in <head>.
   Here we log to console so the wiring is visible.
*/
function track(event, payload = {}) {
  const tagged = { event, ...payload, _ts: Date.now() };
  // Meta Pixel
  if (window.fbq) window.fbq("trackCustom", event, payload);
  // Snapchat Pixel
  if (window.snaptr) window.snaptr("track", event, payload);
  // GA4
  if (window.gtag) window.gtag("event", event, payload);
  // visible log for the mockup
  console.log("[track]", tagged);
}
window.track = track;

/* -------- Language hook -------- */
const useLang = () => {
  const [lang, setLang] = useState(() => localStorage.getItem("sn_lang") || "ar");
  useEffect(() => {
    localStorage.setItem("sn_lang", lang);
    document.body.dir = window.I18N[lang].dir;
    document.body.dataset.lang = lang;
    document.documentElement.lang = lang;
  }, [lang]);
  return [lang, setLang];
};

/* -------- UI atoms -------- */
const Logo = ({ size = 36 }) => (
  <img src="assets/logo-ohg.png" alt="Sama Najd" style={{ width: size, height: size, objectFit: "contain" }}/>
);

const TopBar = ({ lang, setLang, t }) => (
  <header className="topbar">
    <a href="#/" className="topbar__brand" onClick={() => track("nav_logo_click")}>
      <Logo size={40}/>
      <div className="name">
        <b>{t.common.brand}</b>
        <span>{t.common.brandSub}</span>
      </div>
    </a>
    <div className="lang-toggle" role="tablist" aria-label="Language">
      <button
        className={lang === "ar" ? "active" : ""}
        onClick={() => { setLang("ar"); track("lang_switch", { to: "ar" }); }}
        aria-pressed={lang === "ar"}
      >العربية</button>
      <button
        className={lang === "en" ? "active" : ""}
        onClick={() => { setLang("en"); track("lang_switch", { to: "en" }); }}
        aria-pressed={lang === "en"}
      >EN</button>
    </div>
  </header>
);

/* -------- Hero -------- */
const Hero = ({ route, t, page }) => {
  const onWhatsApp = (e) => {
    track("whatsapp_click", { from: "hero", route });
    e.preventDefault();
    window.location.hash = window.location.hash; // no-op nav; in real site → wa.me link
    window.open("https://wa.me/966550650034", "_blank", "noopener");
  };
  const onApply = () => {
    track("cta_apply_click", { from: "hero", route });
    const el = document.getElementById("lead-form");
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };
  return (
    <section className="hero fade-in" key={route}>
      {route !== "home" && (
        <div className="ad-tag">
          <span className="dot"></span>{t.common.adTag} · {route.toUpperCase()}
        </div>
      )}
      <div className="hero__route">{page.eyebrow}</div>
      <h1>
        {page.h1_pre}{" "}
        <span className="pop">{page.h1_pop}</span>
        {page.h1_post ? <><br/><span className="accent">{page.h1_post}</span></> : null}
      </h1>
      <p className="hero__sub">{page.sub}</p>
      <div className="hero__ctas">
        <button className="btn btn--primary" onClick={onApply}>
          <Icon name="arrow" size={18}/>
          {t.common.applyNow}
        </button>
        <a className="btn btn--whatsapp" href="https://wa.me/966550650034" onClick={onWhatsApp}>
          <Icon name="whatsapp" size={18}/>
          {t.common.whatsappCta}
        </a>
      </div>
      <div className="hero__art">
        {page.artImg ? (
          <img
            className="hero__img"
            src={page.artImg}
            alt={page.artLabel}
            loading="eager"
          />
        ) : (
          <div className="placeholder" style={{ position: "absolute", inset: 0 }}>
            <span className="placeholder__tag">{page.artTag}</span>
            <div className="placeholder__inner">
              <Icon name="image" size={36}/>
              <span>{page.artLabel}</span>
            </div>
          </div>
        )}
        <div className="hero__amount">
          <span className="gold-dot"></span>
          <div>
            <div className="num">{page.amount}</div>
            <div className="lbl">{page.amountLbl}</div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* -------- Services -------- */
const Services = ({ t, route }) => {
  const activeId = route === "home" ? null : route;
  return (
    <section className="section">
      <div className="section__head">
        <div className="eyebrow">{t.sections.servicesEyebrow}</div>
        <h2>{t.sections.servicesTitle}</h2>
        <p className="section__lede">{t.sections.servicesLede}</p>
      </div>
      <div className="service-grid">
        {t.services.map(s => {
          const targetHash = s.id === "cash" ? "#/cash"
            : s.id === "waqf" ? "#/waqf-services"
            : s.id === "gov"  ? "#/government-employee"
            : s.id === "liq" || s.id === "surplus" ? "#/real-estate-liquidity"
            : "#/";
          const isActive = s.id === activeId || (s.id === "surplus" && route === "liq");
          return (
            <a
              key={s.id}
              href={targetHash}
              className={"service" + (isActive ? " service--active" : "")}
              onClick={() => track("service_card_click", { id: s.id })}
            >
              <div className="service__icon"><Icon name={s.icon}/></div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
              <span className="service__cta">{t.common.orderNow}</span>
            </a>
          );
        })}
      </div>
    </section>
  );
};

/* -------- Steps -------- */
const Steps = ({ t }) => (
  <section className="section section--paper">
    <div className="section__head">
      <div className="eyebrow">{t.sections.stepsEyebrow}</div>
      <h2>{t.sections.stepsTitle}</h2>
      <p className="section__lede">{t.sections.stepsLede}</p>
    </div>
    <div className="steps">
      {t.steps.map((s, i) => (
        <div className="step" key={i}>
          <span className="step__num">{i + 1}</span>
          <div className="step__icon"><Icon name={s.icon}/></div>
          <div className="step__title">{s.title}</div>
          <div className="step__sub">{s.sub}</div>
        </div>
      ))}
    </div>
  </section>
);

/* -------- Lead form -------- */
const LeadForm = ({ t, route }) => {
  const [name, setName]       = useState("");
  const [mobile, setMobile]   = useState("");
  const [hasMortgage, setHM]  = useState(null);
  const [employer, setEmp]    = useState(null);
  const [errors, setErrors]   = useState({});
  const [sending, setSending] = useState(false);
  const [sent, setSent]       = useState(false);

  // Pre-select gov for the government-employee landing
  useEffect(() => {
    if (route === "gov") setEmp("gov");
    if (route === "cash" || route === "liq") setHM(true);
  }, [route]);

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!name.trim()) errs.name = t.common.required;
    if (!/^05\d{8}$/.test(mobile.trim().replace(/\s|-/g, "")))
      errs.mobile = t.common.invalidMobile;
    setErrors(errs);
    if (Object.keys(errs).length) {
      track("form_error", { errors: Object.keys(errs), route });
      return;
    }
    setSending(true);
    track("form_submit", {
      route,
      hasMortgage: hasMortgage === null ? "unset" : hasMortgage,
      employer: employer || "unset",
      name_provided: !!name,
      mobile_provided: !!mobile
    });
    // simulated network — real backend would replace this
    setTimeout(() => {
      setSending(false);
      setSent(true);
      track("form_submit_success", { route });
    }, 900);
  };

  if (sent) {
    return (
      <section className="lead" id="lead-form">
        <div className="lead__inner lead__success fade-in">
          <div className="ok"><Icon name="check" size={20}/></div>
          <div>
            <h3>{t.common.submitted}</h3>
            <p>{t.common.submittedSub}</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="lead" id="lead-form">
      <div className="lead__inner">
        <div className="eyebrow">{t.sections.formEyebrow}</div>
        <h2>{t.sections.formTitle}</h2>
        <p className="lead__lede">{t.sections.formLede}</p>

        <form className="form" onSubmit={submit} noValidate>
          <div className="field">
            <label className="field__label" htmlFor="name">
              {t.common.name}<span className="req">*</span>
            </label>
            <input
              id="name" type="text" value={name}
              onChange={e => setName(e.target.value)}
              placeholder={t.common.namePh}
              className={errors.name ? "err" : ""}
              autoComplete="name"
            />
            {errors.name && <span className="field__err">{errors.name}</span>}
          </div>

          <div className="field">
            <label className="field__label" htmlFor="mobile">
              {t.common.mobile}<span className="req">*</span>
            </label>
            <input
              id="mobile" type="tel" value={mobile}
              onChange={e => setMobile(e.target.value)}
              placeholder={t.common.mobilePh}
              className={errors.mobile ? "err" : ""}
              dir="ltr"
              autoComplete="tel"
              inputMode="numeric"
            />
            {errors.mobile && <span className="field__err">{errors.mobile}</span>}
          </div>

          <div className="field">
            <label className="field__label">{t.common.hasMortgage}</label>
            <div className="choice">
              <button type="button"
                className={hasMortgage === true ? "on" : ""}
                onClick={() => setHM(true)}>
                <span className="check">{hasMortgage === true && "✓"}</span>
                {t.common.yes}
              </button>
              <button type="button"
                className={hasMortgage === false ? "on" : ""}
                onClick={() => setHM(false)}>
                <span className="check">{hasMortgage === false && "✓"}</span>
                {t.common.no}
              </button>
            </div>
          </div>

          <div className="field">
            <label className="field__label">{t.common.employer}</label>
            <div className="choice">
              <button type="button"
                className={employer === "gov" ? "on" : ""}
                onClick={() => setEmp("gov")}>
                <span className="check">{employer === "gov" && "✓"}</span>
                {t.common.govEmp}
              </button>
              <button type="button"
                className={employer === "priv" ? "on" : ""}
                onClick={() => setEmp("priv")}>
                <span className="check">{employer === "priv" && "✓"}</span>
                {t.common.privEmp}
              </button>
            </div>
          </div>

          <button type="submit" className="btn btn--gold btn--block lead__submit" disabled={sending}>
            {sending ? t.common.sending : t.common.sendBtn}
            {!sending && <Icon name="arrow" size={18}/>}
          </button>
        </form>
      </div>
    </section>
  );
};

/* -------- Trust + Contact -------- */
const Trust = ({ t }) => {
  const onPhone = () => track("phone_click", { from: "trust" });
  const onWA    = () => track("whatsapp_click", { from: "trust" });
  return (
    <section className="section section--paper">
      <div className="section__head">
        <div className="eyebrow">{t.sections.trustEyebrow}</div>
        <h2>{t.sections.trustTitle}</h2>
        <p className="section__lede">{t.sections.trustLede}</p>
      </div>
      <div className="trust-grid">
        {t.trust.map((x, i) => (
          <div className="trust" key={i}>
            <div className="trust__icon"><Icon name={x.icon}/></div>
            <div className="trust__title">{x.title}</div>
          </div>
        ))}
      </div>
      <div className="contact-row">
        <a className="contact-card contact-card--phone" href={`tel:${t.common.phone}`} onClick={onPhone}>
          <div className="contact-card__icon"><Icon name="phone" size={18}/></div>
          <div className="contact-card__body">
            <div className="contact-card__lbl">{t.common.free}</div>
            <div className="contact-card__val">{t.common.phone}</div>
          </div>
        </a>
        <a className="contact-card contact-card--wa" href="https://wa.me/966550650034" target="_blank" rel="noopener" onClick={onWA}>
          <div className="contact-card__icon"><Icon name="whatsapp" size={18}/></div>
          <div className="contact-card__body">
            <div className="contact-card__lbl">WhatsApp</div>
            <div className="contact-card__val">{t.common.whatsapp}</div>
          </div>
        </a>
      </div>
      <div className="socials">
        <a href="#" aria-label="Instagram" onClick={(e)=>{e.preventDefault(); track("social_click",{net:"ig"});}}>
          <Icon name="instagram"/>
        </a>
        <a href="#" aria-label="Snapchat" onClick={(e)=>{e.preventDefault(); track("social_click",{net:"snap"});}}>
          <Icon name="snapchat"/>
        </a>
        <a href="#" aria-label="TikTok" onClick={(e)=>{e.preventDefault(); track("social_click",{net:"tt"});}}>
          <Icon name="tiktok"/>
        </a>
        <a href="https://wa.me/966550650034" target="_blank" rel="noopener" aria-label="WhatsApp" onClick={()=>track("social_click",{net:"wa"})}>
          <Icon name="whatsapp"/>
        </a>
      </div>
    </section>
  );
};

/* -------- Bottom nav rail (mockup-only — lets reviewers click between ad pages) -------- */
const NavRail = ({ route, t }) => {
  const items = [
    { key: "home", hash: "#/",                       label: t.nav.home, icon: "house" },
    { key: "cash", hash: "#/cash",                   label: t.nav.cash, icon: "cash" },
    { key: "waqf", hash: "#/waqf-services",          label: t.nav.waqf, icon: "unlock" },
    { key: "gov",  hash: "#/government-employee",    label: t.nav.gov,  icon: "badge" },
    { key: "liq",  hash: "#/real-estate-liquidity",  label: t.nav.liq,  icon: "trending" },
  ];
  return (
    <nav className="nav-rail" aria-label="Prototype pages">
      {items.map(i => (
        <a key={i.key} href={i.hash} className={route === i.key ? "active" : ""}
           onClick={() => track("nav_rail_click", { to: i.key })}>
          <Icon name={i.icon} size={18}/>
          {i.label}
        </a>
      ))}
    </nav>
  );
};

/* -------- Footer -------- */
const Foot = ({ t }) => (
  <footer className="foot">
    <div className="foot__brand">
      <Logo size={26}/>
      {t.common.brand}
    </div>
    <div>{t.common.tagline}</div>
    <div className="foot__nav">
      <a href="#/">{t.nav.home}</a>
      <a href="#/cash">{t.nav.cash}</a>
      <a href="#/waqf-services">{t.nav.waqf}</a>
      <a href="#/government-employee">{t.nav.gov}</a>
      <a href="#/real-estate-liquidity">{t.nav.liq}</a>
    </div>
    <div className="foot__credits" dir="ltr">
      made with ❤️ by
      <a href="https://nest.aschuweiter.de" target="_blank" rel="noopener" onClick={() => track("foot_nest_click")}>
        <img src="assets/nest.svg" alt="Aschunest" />
      </a>
    </div>
    <div style={{ opacity: .6, marginTop: 8 }}>
      © {new Date().getFullYear()} Sama Najd · Mockup — design only
    </div>
  </footer>
);

/* -------- App root -------- */
const App = () => {
  const route = useHashRoute();
  const [lang, setLang] = useLang();
  const t = window.I18N[lang];
  const page = t.pages[route] || t.pages.home;

  return (
    <div className="shell">
      <TopBar lang={lang} setLang={setLang} t={t}/>
      <main key={route + lang} className="fade-in">
        <Hero route={route} t={t} page={page}/>
        <Services t={t} route={route}/>
        <Steps t={t}/>
        <LeadForm t={t} route={route}/>
        <Trust t={t}/>
        <Foot t={t}/>
      </main>
      <NavRail route={route} t={t}/>
    </div>
  );
};

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