// Dahab v2 — main app
const { useState, useEffect, useMemo, useRef, useCallback } = React;
const { T, CCY, KARAT, SPOT_USD_OZ, OZ_G, fmt } = window;

// ========== Hooks ==========
const useGold = () => {
  const [px, setPx] = useState(SPOT_USD_OZ);
  const ref = useRef(SPOT_USD_OZ);
  useEffect(() => {
    const id = setInterval(() => {
      setPx(c => c + (ref.current - c) * 0.04 + (Math.random() - 0.5) * 2.4);
    }, 1800);
    return () => clearInterval(id);
  }, []);
  const open = ref.current - 5.8;
  return { px, chg: px - open, chgPct: ((px - open) / open) * 100 };
};

const useFx = () => {
  const [rates, setRates] = useState(() => Object.fromEntries(CCY.map(c => [c.code, c.rate])));
  const ref = useRef(rates);
  useEffect(() => {
    const id = setInterval(() => {
      setRates(curr => {
        const next = { ...curr };
        Object.keys(next).forEach(k => {
          if (k === "USD" || k === "JOD") return;
          const base = ref.current[k];
          next[k] = next[k] + (base - next[k]) * 0.05 + (Math.random() - 0.5) * base * 0.0008;
        });
        return next;
      });
    }, 2200);
    return () => clearInterval(id);
  }, []);
  return rates;
};

// Rate from code to JOD: how many JOD for 1 unit of code
const toJOD = (fx, code) => code === "JOD" ? 1 : fx[code] / fx.JOD;

const AnimNum = ({ value, decimals = 2, duration = 600 }) => {
  const [d, setD] = useState(value);
  const from = useRef(value);
  const start = useRef(performance.now());
  useEffect(() => {
    from.current = d;
    start.current = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start.current) / duration);
      const e = 1 - Math.pow(1 - p, 3);
      setD(from.current + (value - from.current) * e);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <span>{fmt(d, decimals)}</span>;
};

// ========== Brand logo ==========
const Logo = ({ className = "brand-mark", variant = "color" }) => (
  <img
    src={variant === "white" ? "assets/dahab-logo-white.png" : "assets/dahab-logo-transparent.png"}
    alt="Dahab Lilsarafah"
    className={className}
  />
);

// ========== Top bar + Ticker ==========
const TopBar = ({ lang, setLang }) => (
  <div className="topbar">
    <div className="wrap topbar-inner">
      <div className="topbar-left">
        <span className="topbar-license" aria-label="Licensed by the Central Bank of Jordan">
          {lang === "ar" ? "مرخّصة من البنك المركزي الأردني" : "Licensed by the Central Bank of Jordan"}
        </span>
      </div>
      <div className="lang-pill" role="tablist" aria-label={lang === "ar" ? "اختيار اللغة" : "Language"}>
        <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
        <button className={lang === "ar" ? "on" : ""} onClick={() => setLang("ar")}>عربي</button>
      </div>
    </div>
  </div>
);

const Ticker = () => {
  const { px } = useGold();
  const fx = useFx();
  const items = useMemo(() => {
    return [
      { sym: "USD/JOD", v: toJOD(fx, "USD").toFixed(4), c: "+0.00%", up: true },
      { sym: "EUR/JOD", v: toJOD(fx, "EUR").toFixed(4), c: "−0.14%", up: false },
      { sym: "GBP/JOD", v: toJOD(fx, "GBP").toFixed(4), c: "+0.22%", up: true },
      { sym: "CHF/JOD", v: toJOD(fx, "CHF").toFixed(4), c: "+0.18%", up: true },
      { sym: "AED/JOD", v: toJOD(fx, "AED").toFixed(4), c: "+0.02%", up: true },
      { sym: "SAR/JOD", v: toJOD(fx, "SAR").toFixed(4), c: "−0.05%", up: false },
      { sym: "KWD/JOD", v: toJOD(fx, "KWD").toFixed(4), c: "+0.09%", up: true },
      { sym: "EGP/JOD", v: toJOD(fx, "EGP").toFixed(5), c: "−0.31%", up: false },
      { sym: "TRY/JOD", v: toJOD(fx, "TRY").toFixed(5), c: "−0.42%", up: false },
    ];
  }, [fx]);
  const doubled = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {doubled.map((it, i) => (
          <div className="ticker-item" key={i}>
            <span className="sym">{it.sym}</span>
            <span className="px">{it.v}</span>
            <span className={"chg " + (it.up ? "up" : "down")}>{it.c}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ========== Nav ==========
const SuperAgentBadge = ({ lang, variant = "light" }) => (
  <span
    className={`partner-mark partner-mark--${variant}`}
    aria-label={lang === "ar" ? "وكيل MoneyGram رئيسي معتمد" : "Authorized MoneyGram Super Agent"}
    title={lang === "ar" ? "وكيل MoneyGram® رئيسي" : "MoneyGram® Super Agent"}
  >
    <img
      src={variant === "dark" ? "assets/moneygram-logo-white.svg" : "assets/moneygram-logo-black.svg"}
      alt="MoneyGram"
      className="partner-mark-img"
      draggable="false"
    />
    <span className="partner-mark-tier">{lang === "ar" ? "وكيل رئيسي" : "Super Agent"}</span>
  </span>
);

// Services dropdown — opens a panel with the full services list.
const ServicesMenu = ({ t, lang }) => {
  const [open, setOpen] = useState(false);
  const closeTimer = useRef(null);
  const ICONS = {
    exchange: (<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7h13l-3-3"/><path d="M21 17H8l3 3"/></svg>),
    transfer: (<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>),
    gold: (<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 9h14l-2 9H7L5 9z"/><path d="M5 9l1.7-4h10.6L19 9"/></svg>),
    bills: (<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 3h11l3 3v15l-3-2-2 2-2-2-2 2-2-2-3 2V3z"/><path d="M9 8h7M9 12h7M9 16h4"/></svg>),
    wallet: (<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><circle cx="16.5" cy="14.5" r="1.2" fill="currentColor"/></svg>),
  };
  const TARGETS = {
    exchange: "#converter",
    transfer: "#mustaqbalcom",
    gold: "#contact",
    bills: "#contact",
    wallet: "#contact",
  };
  const onEnter = () => { clearTimeout(closeTimer.current); setOpen(true); };
  const onLeave = () => { closeTimer.current = setTimeout(() => setOpen(false), 180); };

  return (
    <div className={"services-menu " + (open ? "is-open" : "")} onMouseEnter={onEnter} onMouseLeave={onLeave}>
      <button
        type="button"
        className="services-trigger"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen(o => !o)}
      >
        {t.nav.services}
        <span className="services-caret" aria-hidden="true">▾</span>
      </button>
      <div className="services-panel" role="menu" aria-label={t.nav.services}>
        <div className="services-panel-grid">
          {t.nav.services_menu.map(s => (
            <a
              key={s.k}
              href={TARGETS[s.k] || "#contact"}
              className="services-item"
              role="menuitem"
              onClick={() => setOpen(false)}
            >
              <span className="services-icon">{ICONS[s.k]}</span>
              <span className="services-text">
                <span className="services-t">{s.t}</span>
                <span className="services-d">{s.d}</span>
              </span>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
};

const Nav = ({ t, lang, menuOpen, setMenuOpen }) => {
  return (
  <>
    <div className="nav">
      <div className="wrap nav-inner">
        <div className="brand-group">
          <a href="#" aria-label="Dahab home" className="brand-link"><Logo /></a>
        </div>
        <nav className="nav-links" aria-label="Main">
          <ServicesMenu t={t} lang={lang} />
          <a href="#newsroom">{t.nav.newsroom}</a>
          <a href="#faq">{t.nav.faq}</a>
          <a href="#contact">{t.nav.contact}</a>
        </nav>
        <div className="nav-cta-group">
          <img src="assets/mustaqbalcom-logo-color.png" alt="Mustaqbalcom" className="nav-cta-mark-side" />
          <a href="#find-partner" className="nav-cta" aria-label={lang === "ar" ? "حوّل عبر مستقبل كوم" : "Transfer with Mustaqbalcom"}>
            <span>{t.cta_send}</span>
            <span className="nav-cta-arrow">→</span>
          </a>
        </div>
        <button className="menu-btn" onClick={() => setMenuOpen(o => !o)} aria-label="Menu" aria-expanded={menuOpen}>
          <span></span>
        </button>
      </div>
    </div>
    <div className="mobile-menu">
      <div className="mobile-menu-group">
        <div className="mobile-menu-lbl">{t.nav.services}</div>
        {t.nav.services_menu.map(s => (
          <a key={s.k} href="#contact" className="mobile-menu-sub" onClick={() => setMenuOpen(false)}>
            {s.t}
          </a>
        ))}
      </div>
      <a href="#newsroom" onClick={() => setMenuOpen(false)}>{t.nav.newsroom}</a>
      <a href="#faq" onClick={() => setMenuOpen(false)}>{t.nav.faq}</a>
      <a href="#contact" onClick={() => setMenuOpen(false)}>{t.nav.contact}</a>
      <div className="menu-cta-spacer"></div>
      <a href="#find-partner" className="menu-cta" onClick={() => setMenuOpen(false)}>
        <img src="assets/mustaqbalcom-logo-color.png" alt="" aria-hidden="true" className="nav-cta-mark-side" />
        <span className="menu-cta-divider" aria-hidden="true"></span>
        <span>{t.cta_send}</span>
        <span className="menu-cta-arrow" aria-hidden="true">→</span>
      </a>
    </div>
  </>
  );
};

// ========== Currency sheet (picker) ==========
const Sheet = ({ open, onClose, title, children }) => {
  useEffect(() => {
    document.body.classList.toggle("sheet-open", open);
    return () => document.body.classList.remove("sheet-open");
  }, [open]);
  return (
    <>
      <div className="sheet-backdrop" onClick={onClose}></div>
      <div className="sheet" role="dialog" aria-modal="true">
        <div className="sheet-handle"></div>
        {title && <div className="sheet-title">{title}</div>}
        <div className="sheet-list">{children}</div>
      </div>
    </>
  );
};

const CcyButton = ({ code, onClick }) => {
  const c = CCY.find(x => x.code === code);
  return (
    <button className="ccy-btn" onClick={onClick} type="button">
      <span className="ccy-flag">{c.flag}</span>
      <span>{c.code}</span>
      <span className="chev">▾</span>
    </button>
  );
};

// Reliable external-link opener: tries window.open (new tab), falls back to
// top-window navigation if the iframe sandbox blocks popups, and finally
// degrades to a same-frame navigation. Use this for tel: and https://wa.me/…
const openExternal = (url) => {
  try {
    const w = window.open(url, "_blank", "noopener,noreferrer");
    if (w) return;
  } catch (e) { /* fall through */ }
  try {
    if (window.top && window.top !== window) {
      window.top.location.href = url;
      return;
    }
  } catch (e) { /* fall through */ }
  window.location.href = url;
};

// ========== Converter (currency only) ==========
const Converter = ({ t, lang }) => {
  const fx = useFx();

  const [amt, setAmt] = useState("1000");
  const [from, setFrom] = useState("USD");
  const [to, setTo] = useState("JOD");
  const [picker, setPicker] = useState(null); // "from" | "to" | null
  const [updatedAgo, setUpdatedAgo] = useState(0);

  useEffect(() => { setUpdatedAgo(0); const id = setInterval(() => setUpdatedAgo(n => n + 1), 1000); return () => clearInterval(id); }, [fx]);

  const a = parseFloat((amt || "0").replace(/,/g, "")) || 0;
  const rate = (fx[from] || 1) / (fx[to] || 1);
  const out = a * rate;

  const swap = () => { setFrom(to); setTo(from); };
  const closePicker = () => setPicker(null);

  return (
    <div className="converter" id="converter">
      <div className="conv-head">
        <span style={{
          fontFamily: "var(--display)",
          fontSize: 20,
          fontWeight: 500,
          color: "var(--ink)",
        }}>
          {lang === "ar" ? "حاسبة العملات" : "Currency converter"}
        </span>
        <span className="conv-live"><span className="dot"></span>{t.conv.live}</span>
      </div>

      <div className="conv-field">
        <div>
          <div className="lbl">{t.conv.send}</div>
          <input
            className="conv-amt"
            value={amt}
            onChange={e => setAmt(e.target.value.replace(/[^0-9.,]/g, ""))}
            inputMode="decimal"
            placeholder="0"
            aria-label={t.conv.amount}
          />
        </div>
        <CcyButton code={from} onClick={() => setPicker("from")} />
      </div>

      <div className="conv-swap">
        <button onClick={swap} aria-label="Swap" type="button">⇅</button>
      </div>

      <div className="conv-field">
        <div>
          <div className="lbl">{t.conv.receive}</div>
          <div className="conv-amt-readonly"><AnimNum value={out} decimals={out < 10 ? 4 : 2} /></div>
        </div>
        <CcyButton code={to} onClick={() => setPicker("to")} />
      </div>

      <div className="conv-meta">
        <span><span className="rate">1 {from} = {rate.toFixed(rate < 1 ? 6 : 4)} {to}</span></span>
        <span>{t.conv.updated} {updatedAgo}{t.conv.sec}</span>
      </div>

      <div className="conv-cta">
        <a
          href={window.BRANCH_MAPS_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="btn primary"
          onClick={(e) => { e.preventDefault(); openExternal(window.BRANCH_MAPS_URL); }}
        >
          {t.conv.cta_primary} <span className="arrow">→</span>
        </a>
      </div>

      <div className="metals-notice">
        <div className="metals-notice-head">
          <span className="metals-icon" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 8h14l-2 8H7L5 8z" />
              <path d="M5 8l1.5-3h11L19 8" />
            </svg>
          </span>
          <span className="metals-pill">{t.conv.metals_pill}</span>
        </div>
        <h4 className="metals-title">{t.conv.metals_title}</h4>
        <p className="metals-body">{t.conv.metals_body}</p>
        <div className="metals-actions">
          <a href="tel:+962775530045" className="btn primary metals-btn"
             onClick={(e) => { e.preventDefault(); openExternal("tel:+962775530045"); }}>
            <span aria-hidden="true">☏</span> {t.conv.metals_call}
          </a>
        </div>
      </div>

      <div style={{ marginTop: 16, fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--muted-2)", lineHeight: 1.6 }}>
        {t.conv.disclaimer}
      </div>

      {picker && (
        <Sheet open={!!picker} onClose={closePicker} title={t.conv.picker_title}>
          {CCY.map(c => (
            <button key={c.code} onClick={() => {
              if (picker === "from") setFrom(c.code);
              else if (picker === "to") setTo(c.code);
              closePicker();
            }}>
              <span className="ccy-flag">{c.flag}</span>
              <span className="code">{c.code}</span>
              <span className="nm">{lang === "ar" ? c.nm_ar : c.nm_en}</span>
              <span className="rate">{c.code === "JOD" ? "1.0000" : toJOD(fx, c.code).toFixed(4)}</span>
            </button>
          ))}
        </Sheet>
      )}
    </div>
  );
};

// ========== Quick Assist (floating call + WhatsApp) ==========
const QuickAssist = ({ t, lang }) => {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const waText = lang === "ar"
    ? "مرحباً ذهب، أود الاستفسار."
    : "Hello Dahab, I'd like to make an inquiry.";

  return (
    <div className={"qa-wrap " + (open ? "qa-open" : "")} ref={wrapRef}>
      <div className="qa-menu" role="menu" aria-hidden={!open}>
        <a
          className="qa-item qa-whatsapp"
          href={`https://wa.me/962775530045?text=${encodeURIComponent(waText)}`}
          target="_blank" rel="noopener noreferrer"
          role="menuitem"
          onClick={(e) => {
            e.preventDefault();
            openExternal(`https://wa.me/962775530045?text=${encodeURIComponent(waText)}`);
            setOpen(false);
          }}
        >
          <span className="qa-item-ic">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-1s-.5-.1-.7.1l-.9 1c-.2.2-.3.2-.6.1-1-.5-1.8-1.1-2.6-2-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.1-.3 0-.5l-.7-1.6c-.2-.4-.4-.4-.6-.4h-.5c-.2 0-.4.1-.6.3-.7.6-1 1.5-1 2.4 0 .3.1.6.2 1 .6 1.7 1.6 3.1 3 4.3 1 1 2.3 1.7 3.6 1.8 1 .1 1.8-.2 2.5-.7.4-.3.7-.8.7-1.3 0-.2-.1-.5-.3-.4zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5-1.3c1.5.8 3.2 1.2 5 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
          </span>
          <span className="qa-item-txt">
            <span className="qa-item-k">{lang === "ar" ? "واتساب" : "WhatsApp"}</span>
            <span className="qa-item-v">{lang === "ar" ? "ردّ خلال دقائق" : "Reply in minutes"}</span>
          </span>
        </a>
        <a
          className="qa-item qa-call"
          href="tel:+962775530045"
          role="menuitem"
          onClick={(e) => {
            e.preventDefault();
            openExternal("tel:+962775530045");
            setOpen(false);
          }}
        >
          <span className="qa-item-ic">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><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-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 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-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
          </span>
          <span className="qa-item-txt">
            <span className="qa-item-k">{lang === "ar" ? "اتصل بالفرع" : "Call the branch"}</span>
            <span className="qa-item-v" style={{ direction: "ltr", display: "inline-block" }}>+962 7 755 300 45</span>
          </span>
        </a>
      </div>
      <button
        className="qa-fab"
        onClick={() => setOpen(o => !o)}
        aria-label={lang === "ar" ? "مساعدة سريعة" : "Quick assist"}
        aria-expanded={open}
        type="button"
      >
        <span className="qa-fab-pulse" aria-hidden="true"></span>
        {open ? (
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        ) : (
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
        )}
      </button>
    </div>
  );
};

// ========== Hero partner-rails strip ==========
// ========== Authorized partners strip (below header) ==========
// Quiet authorization shelf that sits between the nav and the hero. It states
// the four global rails Dahab is licensed on — separate purpose from the two
// dedicated "Our partners" marquees deeper down the page (which are full
// sections with their own headlines). This is a credentials line, not a
// presentation.
const HeroRails = ({ lang }) => (
  <div className="hero-rails">
    <div className="wrap">
      <div className="hero-rails-inner">
        <span className="hero-rails-lbl">
          {lang === "ar" ? "معتمدون على أبرز شبكات التحويل في العالم" : "Authorized on the world's transfer rails"}
        </span>
        <div className="hero-rails-row" role="list">
          <span className="rail" role="listitem" title="MoneyGram">
            <img src="assets/moneygram-logo-black.svg" alt="MoneyGram" className="rail-img rail-img--mg" />
          </span>
          <span className="rail-sep" aria-hidden="true"></span>
          <span className="rail" role="listitem" title="Ria Money Transfer">
            <img src="assets/ria-logo.png" alt="Ria Money Transfer" className="rail-img rail-img--ria" />
          </span>
          <span className="rail-sep" aria-hidden="true"></span>
          <span className="rail" role="listitem" title="TerraPay">
            <img src="assets/terrapay-logo.svg" alt="TerraPay" className="rail-img rail-img--tp" />
          </span>
          <span className="rail-sep" aria-hidden="true"></span>
          <span className="rail rail--mc" role="listitem" title="Mastercard · network powered by TransFast">
            <img src="assets/mastercard-symbol.svg" alt="Mastercard" className="rail-img rail-img--mc" />
            <img src="assets/transfast-lockup.svg" alt="network powered by TransFast" className="rail-img rail-img--tf" />
          </span>
          <span className="rail-sep" aria-hidden="true"></span>
          <span className="rail" role="listitem" title="UPT — Money Transfer">
            <img src="assets/upt-logo.png" alt="UPT" className="rail-img rail-img--upt" />
          </span>
        </div>
      </div>
    </div>
  </div>
);

// ========== Hero ==========
const Hero = ({ t, lang }) => (
  <section className="hero">
    <div className="wrap hero-grid">
      <div>
        <h1 className="display">
          {t.hero.h_a} <em>{t.hero.h_em}</em><br />
          <span style={{ color: "var(--ink-2)" }}>{t.hero.h_b}</span>
        </h1>
        <p className="hero-sub">{t.hero.sub}</p>
        <div className="hero-actions">
          <a href="#find-partner" className="btn primary">{t.hero.cta_primary} <span className="arrow">→</span></a>
        </div>
        <div className="hero-trust">
          {t.hero.trust.map((tr, i) => (
            <div key={i}>
              <div className="k">{tr.k}</div>
              <div className="v">{tr.v}</div>
            </div>
          ))}
        </div>
      </div>
      <Converter t={t} lang={lang} />
    </div>
  </section>
);

// ========== Partner marquee ==========
// Horizontal infinite-loop logo strip. Direction reverses in RTL so motion
// reads naturally with the page's text direction. Pauses on hover. Cloned
// markup keeps the loop seamless without measuring widths.
const PartnerMarquee = ({ items, lang, reverse = false, height = 56 }) => {
  // In RTL we want logos to travel right-to-left visually with the reading
  // direction — but the CSS animation runs in the document direction, so we
  // pass through `reverse` to flip it explicitly.
  const dirClass = (lang === "ar") !== reverse ? "marq-rtl" : "marq-ltr";
  const renderRow = (key) => (
    <div className={"marq-row " + dirClass} key={key} aria-hidden={key === "b"}>
      {items.map((it, i) => (
        <span className="marq-cell" key={key + i} title={it.title}>
          {it.placeholder ? (
            <span className="marq-placeholder" style={{ height }}>{it.placeholder}</span>
          ) : (
            <img
              src={it.src}
              alt={it.alt || it.title || ""}
              className={"marq-logo " + (it.cls || "")}
              style={{ height: it.h || height }}
              draggable="false"
            />
          )}
          {it.note && <span className="marq-note">{it.note}</span>}
        </span>
      ))}
    </div>
  );
  return (
    <div className="marquee" role="region" aria-roledescription="logo carousel">
      <div className="marq-track">
        {renderRow("a")}
        {renderRow("b")}
      </div>
    </div>
  );
};

// ========== Partners — In Jordan ==========
const PartnersJordan = ({ t, lang }) => {
  // Real Jordanian exchange-house partners. Heights are tuned per-logo so each
  // brand reads at a similar visual weight in the marquee row: landscape
  // wordmarks stay shorter, stacked / portrait lockups get more height.
  // The array is rendered TWICE inside <PartnerMarquee> so the loop stays
  // seamless — only edit this single list to add/remove a partner.
  const items = [
    { title: "Jordan Post (JO Post)",  src: "assets/jordan-partners/jopost.png",     alt: "Jordan Post",           h: 50 },
    { title: "Abu Sheikha Exchange",  src: "assets/jordan-partners/abusheikha.png",  alt: "Abu Sheikha Exchange",  h: 48 },
    { title: "Alawneh Exchange",      src: "assets/jordan-partners/alawneh.png",     alt: "Alawneh Exchange",      h: 38 },
    { title: "Swiss Exchange",        src: "assets/jordan-partners/swissex.png",     alt: "Swiss Exchange",        h: 44 },
    { title: "Al-Sadat & Hindi Exchange", src: "assets/jordan-partners/sadat-hindi.png", alt: "Al-Sadat & Hindi Exchange", h: 64 },
    { title: "Zamzam Exchange",       src: "assets/jordan-partners/zamzam.png",      alt: "Zamzam Exchange",       h: 38 },
    { title: "Musharbash Exchange",   src: "assets/jordan-partners/musharbash.png",  alt: "Musharbash Exchange",   h: 60 },
  ];
  return (
    <section id="partners" className="section section--marquee">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">{t.partners.jordan_eyebrow}</span>
          <h2 className="display">{t.partners.jordan_h}</h2>
          <p className="lede">{t.partners.jordan_sub}</p>
        </div>
      </div>
      <PartnerMarquee items={items} lang={lang} height={56} />
    </section>
  );
};

// ========== Partners — Worldwide ==========
const PartnersWorldwide = ({ t, lang }) => {
  const items = [
    { title: "MoneyGram", src: "assets/moneygram-logo-black.svg", alt: "MoneyGram", cls: "marq-mg", h: 38 },
    { title: "Ria Money Transfer", src: "assets/ria-logo.png", alt: "Ria Money Transfer", cls: "marq-ria", h: 44 },
    { title: "TerraPay", src: "assets/terrapay-logo.svg", alt: "TerraPay", cls: "marq-tp", h: 34 },
    { title: "Mastercard · TransFast", src: "assets/mastercard-symbol.svg", alt: "Mastercard", cls: "marq-mc", h: 42, note: "TransFast" },
    { title: "UPT", src: "assets/upt-logo.png", alt: "UPT", cls: "marq-upt", h: 34 },
    { title: "MoneyGram", src: "assets/moneygram-logo-black.svg", alt: "MoneyGram", cls: "marq-mg", h: 38 },
    { title: "Ria Money Transfer", src: "assets/ria-logo.png", alt: "Ria Money Transfer", cls: "marq-ria", h: 44 },
    { title: "TerraPay", src: "assets/terrapay-logo.svg", alt: "TerraPay", cls: "marq-tp", h: 34 },
    { title: "Mastercard · TransFast", src: "assets/mastercard-symbol.svg", alt: "Mastercard", cls: "marq-mc", h: 42, note: "TransFast" },
    { title: "UPT", src: "assets/upt-logo.png", alt: "UPT", cls: "marq-upt", h: 34 },
  ];
  return (
    <section id="partners-worldwide" className="section section--marquee">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">{t.partners.worldwide_eyebrow}</span>
          <h2 className="display">{t.partners.worldwide_h}</h2>
          <p className="lede">{t.partners.worldwide_sub}</p>
        </div>
      </div>
      <PartnerMarquee items={items} lang={lang} reverse={true} height={42} />
    </section>
  );
};

// ========== Mustaqbalcom (B2B · for partner institutions) ==========
const Mustaqbalcom = ({ t, lang }) => (
  <section id="mustaqbalcom" className="section">
    <div className="wrap">
      <div className="must-card">
        <div style={{ position: "relative" }}>
          <div className="must-card-head">
            <span className="must-mark" aria-label="Mustaqbalcom">
              <img src="assets/mustaqbalcom-logo-color.png" alt="Mustaqbalcom — money transfer" />
            </span>
          </div>
          <span className="eyebrow">{t.must.eyebrow}</span>
          <div className="must-audience-pill">
            <span className="dot" aria-hidden="true"></span>
            {t.must.audience_pill}
          </div>
          <h2 className="display">{t.must.h_a} <em>{t.must.h_em}</em></h2>
          <p className="lede">{t.must.sub}</p>
          <div className="must-stats">
            {t.must.stats.map((s, i) => (
              <div className="must-stat" key={i}>
                <div className="k">{s.k}</div>
                <div className="v">{s.v}</div>
                {s.x && <div className="x">{s.x}</div>}
              </div>
            ))}
          </div>
          {t.must.features.length > 0 && (
            <div className="must-features">
              {t.must.features.map((f, i) => (
                <div className="must-feat" key={i}>
                  <div className="icon" aria-hidden="true">{String(i + 1).padStart(2, "0")}</div>
                  <h4>{f.h}</h4>
                  <p>{f.p}</p>
                </div>
              ))}
            </div>
          )}
          <div className="must-actions">
            <a href={`mailto:partners@dahabx.jo?subject=${encodeURIComponent(lang === "ar" ? "طلب شراكة — مستقبل كوم" : "Mustaqbalcom — partnership inquiry")}`} className="must-cta">
              {t.must.cta} <span>→</span>
            </a>
            <a
              href="assets/mustaqbalcom-onboarding.pdf"
              target="_blank"
              rel="noopener noreferrer"
              download
              className="must-cta-ghost"
              aria-label={lang === "ar" ? "تحميل معايير الانضمام (PDF)" : "Download onboarding criteria (PDF)"}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/>
                <path d="M14 3v5h5"/>
                <path d="M12 12v6m-3-3 3 3 3-3"/>
              </svg>
              <span>{t.must.cta_secondary}</span>
              <span className="must-cta-ghost-tag" aria-hidden="true">PDF</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ========== Why ==========
const Why = ({ t }) => (
  <section id="why" className="section">
    <div className="wrap">
      <div className="section-head">
        <span className="eyebrow">{t.why.eyebrow}</span>
        <h2 className="display">{t.why.h_a} <em>{t.why.h_em}</em></h2>
        <p className="lede">{t.why.sub}</p>
      </div>
      <div className="pillars">
        {t.why.pillars.map((p, i) => (
          <div className="pillar" key={i}>
            <div className="num">{String(i + 1).padStart(2, "0")} / 03</div>
            <h4>{p.h}</h4>
            {p.p && <p>{p.p}</p>}
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ========== Newsroom ==========
// Service launches, partner onboardings, customer advisories, and regulatory
// updates. Replaces the previous "Blog" treatment — institutional voice fits a
// CBJ-licensed exchange better than personal/editorial framing. Posts carry a
// `cat` so the filter chips can narrow the list without route changes.
const Newsroom = ({ t, lang }) => {
  const [active, setActive] = useState("all");
  const items = active === "all"
    ? t.newsroom.items
    : t.newsroom.items.filter(a => a.cat === active);
  return (
    <section id="newsroom" className="section" style={{ background: "var(--bg-2)" }}>
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">{t.newsroom.eyebrow}</span>
          <h2 className="display">{t.newsroom.h}</h2>
          <p className="lede">{t.newsroom.sub}</p>
        </div>
        <div className="nr-filters" role="tablist"
             aria-label={lang === "ar" ? "تصفية حسب الفئة" : "Filter by category"}>
          {t.newsroom.filters.map(f => (
            <button
              key={f.id}
              type="button"
              role="tab"
              aria-selected={active === f.id}
              className={"nr-chip" + (active === f.id ? " on" : "")}
              onClick={() => setActive(f.id)}
            >
              {f.label}
            </button>
          ))}
        </div>
        {items.length > 0 ? (
          <div className="articles">
            {items.map((a, i) => (
              <article className={"article article--" + a.cat} key={a.title}>
                <div className={"article-cover article-cover--" + a.cat}>
                  {/* Category-level cover art. Same mark/background for every
                      article in a category — Newsroom is not photographic. */}
                  <div className="cover-mark" aria-hidden="true">
                    {a.cat === "ann" && <div className="mark-rings"></div>}
                    {a.cat === "ptr" && <div className="mark-linked"></div>}
                    {a.cat === "adv" && <div className="mark-triangle"></div>}
                    {a.cat === "reg" && (
                      <div className="mark-bars">
                        <div className="mark-bars-mid"></div>
                      </div>
                    )}
                  </div>
                  <span className={"nr-pill nr-pill--" + a.cat}>{a.catLabel}</span>
                </div>
                <div className="article-body">
                  <span className="nr-date">{a.date}</span>
                  <h3>{a.title}</h3>
                  <p>{a.excerpt}</p>
                  <div className="article-foot article-foot--single">
                    <a href="#">{t.newsroom.read_more} <span className="arrow">→</span></a>
                  </div>
                </div>
              </article>
            ))}
          </div>
        ) : (
          <div className="nr-empty">{t.newsroom.empty}</div>
        )}
        <div style={{ marginTop: 32, textAlign: "center" }}>
          <a href="#" className="btn ghost">{t.newsroom.more} <span className="arrow">→</span></a>
        </div>
      </div>
    </section>
  );
};

// ========== Worldwide transfer rails ==========
// Below the "Find a partner" list we surface the global rails Dahab is
// authorized on. For each rail we show its logo, a one-line coverage stat,
// and a deep link to that rail's own consumer locator (or, for B2B rails
// like TerraPay and Mastercard Move, a "Learn more" link to their corporate
// page). We do NOT try to list rail-side branches ourselves — MoneyGram has
// 350k+ outlets, that's a job for their locator, not ours.
const WorldwideRails = ({ t, lang }) => (
  <section id="worldwide-rails" className="section section--ww">
    <div className="wrap">
      <div className="section-head">
        {t.wwrails.eyebrow && <span className="eyebrow">{t.wwrails.eyebrow}</span>}
        <h2 className="display">{t.wwrails.h}</h2>
        <p className="lede">{t.wwrails.sub}</p>
      </div>
      <div className="wwrails-grid">
        {t.wwrails.items.map(item => (
          <a key={item.id} href={item.url} target="_blank" rel="noopener noreferrer"
             className={"wwrail-card wwrail-card--" + item.id}>
            <div className="wwrail-mark">
              <img src={item.logo} alt={item.name} />
              {/* Optional second-logo lockup (used for Mastercard + TransFast,
                  mirroring the lockup shown in the top rails ticker). */}
              {item.logo2 && (
                <React.Fragment>
                  <span className="wwrail-mark-sep" aria-hidden="true"></span>
                  <img src={item.logo2} alt="" className="wwrail-mark-logo2" />
                </React.Fragment>
              )}
            </div>
            <div className="wwrail-body">
              <h3 className="wwrail-name">{item.name}</h3>
              <p className="wwrail-desc">{item.desc}</p>
            </div>
            <span className="wwrail-cta">
              <span>{item.action === "find" ? t.wwrails.action : t.wwrails.learn}</span>
              <span className="wwrail-arrow" aria-hidden="true">↗</span>
            </span>
          </a>
        ))}
      </div>
    </div>
  </section>
);

const PartnerFinder = ({ t, lang }) => {
  // Default country = Jordan (JO). On first visit, visitors see local partners
  // first; selecting a different country swaps the list to that country's
  // partners only — there is no "all countries" mega-list anymore.
  const [query, setQuery] = useState("");
  const [country, setCountry] = useState("JO");
  const [limit, setLimit] = useState(8);
  const [activeIdx, setActiveIdx] = useState(null);
  const rowsRef = useRef([]);

  const allAgents = window.AGENTS;
  const allCountries = window.COUNTRIES;

  // ---------- Branch grouping ----------
  // Partners with multiple branches collapse into a single expandable row.
  // The user-typed `query` auto-expands any group whose brand matches, so
  // searching e.g. "Alawneh" reveals all its branches without an extra click.
  // The map (and `activeIdx`) still operates on the flat filtered list so
  // every branch keeps its own marker.
  const [expanded, setExpanded] = useState(() => new Set());
  const toggleExpand = (brand) => {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(brand)) next.delete(brand);
      else next.add(brand);
      return next;
    });
  };

  // Counts per country (used to badge the country chips). The previous
  // global `all` count was dropped along with the all-countries button.
  const counts = useMemo(() => {
    const c = {};
    allCountries.forEach(co => { c[co.code] = 0; });
    allAgents.forEach(a => { c[a.country] = (c[a.country] || 0) + 1; });
    return c;
  }, []);

  // Filter — always scoped to the currently selected country.
  // Then sorted by the per-country `order` column (lower numbers first);
  // brand name is the tiebreaker. Placeholder rows without an explicit
  // `order` fall back to their position in the source array.
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    const withIdx = allAgents.map((a, i) => ({ ...a, _origIdx: i }));
    const matches = withIdx.filter(a => {
      if (a.country !== country) return false;
      if (!q) return true;
      const co = allCountries.find(c => c.code === a.country);
      const hay = [
        a.brand,
        a.city_en, a.city_ar,
        a.addr_en, a.addr_ar,
        co.nm_en, co.nm_ar,
        a.country,
        a.phone,
      ].join(" ").toLowerCase();
      return hay.includes(q);
    });
    matches.sort((a, b) => {
      const oa = (a.order ?? (1000 + a._origIdx));
      const ob = (b.order ?? (1000 + b._origIdx));
      if (oa !== ob) return oa - ob;
      return a.brand.localeCompare(b.brand);
    });
    return matches;
  }, [query, country]);

  const shown = filtered.slice(0, limit);
  const canLoadMore = filtered.length > limit;

  // Group filtered branches by brand (preserve filter order). Single-branch
  // partners render as flat cards; multi-branch render as expandable parents.
  // Each branch keeps its index `_idx` into `filtered` so `activeIdx` and the
  // map markers stay in sync.
  const groups = useMemo(() => {
    const m = new Map();
    filtered.forEach((a, idx) => {
      if (!m.has(a.brand)) m.set(a.brand, { brand: a.brand, country: a.country, branches: [] });
      m.get(a.brand).branches.push({ ...a, _idx: idx });
    });
    return [...m.values()];
  }, [filtered]);

  // The "Load more" button reveals additional partners, not branches.
  const shownGroups = groups.slice(0, limit);
  const canLoadMoreGroups = groups.length > limit;

  // Auto-expand any group whose brand matches the live query (so search
  // surfaces sub-branches without an extra click). User-toggled state still
  // wins for non-matching groups.
  const effectiveExpanded = useMemo(() => {
    if (!query.trim()) return expanded;
    const q = query.toLowerCase().trim();
    const auto = new Set(expanded);
    groups.forEach(g => { if (g.brand.toLowerCase().includes(q)) auto.add(g.brand); });
    return auto;
  }, [expanded, query, groups]);

  // For a multi-branch partner the "Headquarters" city = the FIRST branch in
  // the list (which reflects the CSV's `order` column). The team can put
  // their HQ on the lowest order number to control this label.
  const hqCity = (g, lang) => lang === "ar" ? g.branches[0].city_ar : g.branches[0].city_en;

  // Derive a short label for each branch. Prefer the explicit `branch_label`
  // field (with optional `_ar` variant); fall back to the first segment of
  // the address.
  const branchLabel = (b, lang) => {
    if (lang === "ar" && b.branch_label_ar) return b.branch_label_ar;
    if (b.branch_label) return b.branch_label;
    const addr = lang === "ar" ? b.addr_ar : b.addr_en;
    return addr.split(/[,،]/)[0].trim();
  };

  // Reset active selection when filter changes
  useEffect(() => { setActiveIdx(null); }, [query, country]);

  // Reset clears the query but keeps the country (default JO). The user
  // chose a country deliberately — don't pull the rug.
  const reset = () => { setQuery(""); setCountry("JO"); setLimit(8); setActiveIdx(null); };

  // Build a Google Maps "Get directions" URL for any agent record.
  // If the partner provided a specific share link (Dahab Lilsarafah, e.g.),
  // use it verbatim. Otherwise build a search URL from the address + city +
  // country — Maps geocodes the address string, no lat/lng needed.
  const directionsUrl = (a) => {
    if (a.maps_url) return a.maps_url;
    const co = allCountries.find(c => c.code === a.country);
    const parts = [
      lang === "ar" ? a.addr_ar : a.addr_en,
      lang === "ar" ? a.city_ar : a.city_en,
      lang === "ar" ? (co && co.nm_ar) : (co && co.nm_en),
    ].filter(Boolean);
    return "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(parts.join(", "));
  };

  const scrollToCard = (idx) => {
    // Ensure the card is in the rendered slice
    if (idx >= limit) setLimit(Math.ceil((idx + 1) / 8) * 8);
    // Defer scroll until after render
    requestAnimationFrame(() => {
      const el = rowsRef.current[idx];
      if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
    });
  };

  // Sort country chips: ones with results first, then alpha.
  // Countries with zero partners are filtered out — visitors only see chips
  // for countries we actually serve (no empty buttons).
  const orderedCountries = useMemo(() => {
    return [...allCountries]
      .filter(c => (counts[c.code] || 0) > 0)
      .sort((a, b) => {
        const ca = counts[a.code] || 0;
        const cb = counts[b.code] || 0;
        if (ca === cb) return (lang === "ar" ? a.nm_ar : a.nm_en).localeCompare(lang === "ar" ? b.nm_ar : b.nm_en);
        return cb - ca;
      });
  }, [lang, counts]);

  return (
    <section id="find-partner" className="section">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">{t.finder.eyebrow}</span>
          <h2 className="display">{t.finder.h_a} <em>{t.finder.h_em}</em></h2>
          <p className="lede">{t.finder.sub}</p>
        </div>

        <div className="finder">
          <div className="finder-head">
            <div className="finder-search">
              <span className="icon">⌕</span>
              <input
                value={query}
                onChange={e => { setQuery(e.target.value); setLimit(8); }}
                placeholder={t.finder.search_ph}
                aria-label={t.finder.search_ph}
                type="text"
              />
              {query && (
                <button className="clear-btn" onClick={() => setQuery("")} aria-label={t.finder.clear} type="button">×</button>
              )}
            </div>

            <div className="country-chips" role="tablist">
              {orderedCountries.map(co => (
                <button
                  key={co.code}
                  className={"country-chip " + (country === co.code ? "on" : "")}
                  onClick={() => { setCountry(co.code); setLimit(8); }}
                  type="button"
                >
                  <span className="flag">{co.code}</span>
                  <span>{lang === "ar" ? co.nm_ar : co.nm_en}</span>
                  <span className="count">{counts[co.code] || 0}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="finder-meta">
            <span className="count-pill">
              {groups.length} {groups.length === 1 ? t.finder.result_one_partner : t.finder.results_partners}
            </span>
            <span className="count-locations">
              {filtered.length} {filtered.length === 1 ? t.finder.result_one : t.finder.results}
            </span>
            <span>
              {lang === "ar"
                ? allCountries.find(c => c.code === country).nm_ar
                : allCountries.find(c => c.code === country).nm_en}
              {query && ` · "${query}"`}
            </span>
          </div>

          {filtered.length === 0 ? (
            <div className="finder-empty">
              <h4>{t.finder.no_results}</h4>
              <button className="svc-action" onClick={reset} type="button">{t.finder.clear}</button>
            </div>
          ) : (
            <div className="agent-grid">
              {shownGroups.map((g) => {
                const co = allCountries.find(c => c.code === g.country);
                const isMulti = g.branches.length > 1;
                const isExpanded = effectiveExpanded.has(g.brand);

                if (!isMulti) {
                  // ----- Single-branch partner: render as flat card -----
                  const a = g.branches[0];
                  const i = a._idx;
                  const isActive = activeIdx === i;
                  return (
                    <div
                      className={"agent-row " + (isActive ? "is-active" : "")}
                      key={g.brand}
                      ref={el => { rowsRef.current[i] = el; }}
                      onClick={() => { setActiveIdx(i); }}
                    >
                      <div className="agent-head">
                        <div style={{ minWidth: 0 }}>
                          <div className="agent-brand">{(lang === "ar" && a.brand_ar) ? a.brand_ar : a.brand}</div>
                          <div className="agent-loc">
                            <span className="flag">{a.country}</span>
                            <span className="agent-city">{lang === "ar" ? a.city_ar : a.city_en}</span>
                            <span style={{ color: "var(--muted-2)" }}>·</span>
                            <span>{lang === "ar" ? co.nm_ar : co.nm_en}</span>
                          </div>
                        </div>
                        {a.hq && <span className="agent-hq">{t.finder.hq}</span>}
                      </div>
                      <div className="agent-addr">{lang === "ar" ? a.addr_ar : a.addr_en}</div>
                      <div className="agent-meta">
                        <span><span className="ph">{a.phone}</span></span>
                        <span>{lang === "ar" ? a.hours_ar : a.hours_en}</span>
                      </div>
                      <div className="agent-svc">
                        {a.svc.map(s => (
                          <span key={s} className={"svc-badge svc-" + s}>{t.finder.services[s]}</span>
                        ))}
                      </div>
                      <div className="svc-actions">
                        <a href={"tel:" + a.phone.replace(/\s/g, "")} className="svc-action gold" onClick={(e) => e.stopPropagation()}>
                          <span>☏</span> {t.finder.call}
                        </a>
                        <a
                          href={directionsUrl(a)}
                          target="_blank" rel="noopener noreferrer"
                          className="svc-action"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <span>⟐</span> {t.finder.directions}
                        </a>
                      </div>
                    </div>
                  );
                }

                // ----- Multi-branch partner: HQ details + collapsible "other branches" -----
                // The parent row renders the HQ branch (first sorted branch) as a full
                // single-branch card so visitors see the same details (address, phone,
                // hours, service badges, Call/Directions) without having to expand.
                // A small chevron pill toggles a sublist of the OTHER branches.
                const hq = g.branches[0];
                const others = g.branches.slice(1);
                const hqIdx = hq._idx;
                const isHQActive = activeIdx === hqIdx;
                return (
                  <div
                    className={"agent-row agent-row--group " + (isExpanded ? "is-expanded" : "") + (isHQActive ? " is-active" : "")}
                    key={g.brand}
                    ref={el => { rowsRef.current[hqIdx] = el; }}
                    onClick={() => { setActiveIdx(hqIdx); }}
                  >
                    <div className="agent-head">
                      <div style={{ minWidth: 0 }}>
                        <div className="agent-brand">{(lang === "ar" && hq.brand_ar) ? hq.brand_ar : hq.brand}</div>
                        <div className="agent-loc">
                          <span className="flag">{hq.country}</span>
                          <span className="agent-city">{lang === "ar" ? hq.city_ar : hq.city_en}</span>
                          <span style={{ color: "var(--muted-2)" }}>·</span>
                          <span>{lang === "ar" ? co.nm_ar : co.nm_en}</span>
                        </div>
                      </div>
                      <span className="agent-locations-tag">
                        {g.branches.length} {t.finder.locations}
                      </span>
                    </div>

                    <div className="agent-addr">{lang === "ar" ? hq.addr_ar : hq.addr_en}</div>

                    <div className="agent-meta">
                      <span><span className="ph">{hq.phone}</span></span>
                      <span>{lang === "ar" ? hq.hours_ar : hq.hours_en}</span>
                    </div>

                    <div className="agent-svc">
                      {hq.svc.map(s => (
                        <span key={s} className={"svc-badge svc-" + s}>{t.finder.services[s]}</span>
                      ))}
                    </div>

                    <div className="svc-actions">
                      <a
                        href={"tel:" + hq.phone.replace(/\s/g, "")}
                        className="svc-action gold"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <span>☏</span> {t.finder.call}
                      </a>
                      <a
                        href={directionsUrl(hq)}
                        target="_blank" rel="noopener noreferrer"
                        className="svc-action"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <span>⟐</span> {t.finder.directions}
                      </a>
                      <button
                        type="button"
                        className={"svc-action svc-action--expand " + (isExpanded ? "is-on" : "")}
                        onClick={(e) => { e.stopPropagation(); toggleExpand(g.brand); }}
                        aria-expanded={isExpanded}
                      >
                        <span>{others.length}</span>
                        {isExpanded ? t.finder.hide_branches : t.finder.more_branches}
                        <span className="agent-chevron" aria-hidden="true">
                          <svg viewBox="0 0 16 16" width="12" height="12"><path d="M3 6l5 5 5-5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </span>
                      </button>
                    </div>

                    {isExpanded && others.length > 0 && (
                      <ul className="agent-sublist" role="list">
                        <li className="agent-sublist-head" aria-hidden="true">
                          {t.finder.other_branches}
                        </li>
                        {others.map((b) => {
                          const j = b._idx;
                          const isSubActive = activeIdx === j;
                          return (
                            <li
                              key={j}
                              className={"agent-sub " + (isSubActive ? "is-active" : "")}
                              ref={el => { rowsRef.current[j] = el; }}
                              onClick={(e) => { e.stopPropagation(); setActiveIdx(j); }}
                            >
                              <div className="agent-sub-main">
                                <div className="agent-sub-label">{branchLabel(b, lang)}</div>
                                <div className="agent-sub-addr">{lang === "ar" ? b.addr_ar : b.addr_en}</div>
                                <div className="agent-sub-meta">
                                  <span>{b.phone}</span>
                                  <span style={{ color: "var(--muted-2)" }}>·</span>
                                  <span>{lang === "ar" ? b.hours_ar : b.hours_en}</span>
                                </div>
                              </div>
                              <div className="agent-sub-actions" onClick={(e) => e.stopPropagation()}>
                                <a
                                  href={"tel:" + b.phone.replace(/\s/g, "")}
                                  className="agent-sub-act"
                                  title={t.finder.call}
                                  aria-label={t.finder.call}
                                >☏</a>
                                <a
                                  href={directionsUrl(b)}
                                  target="_blank" rel="noopener noreferrer"
                                  className="agent-sub-act"
                                  title={t.finder.directions}
                                  aria-label={t.finder.directions}
                                >⟐</a>
                              </div>
                            </li>
                          );
                        })}
                      </ul>
                    )}
                  </div>
                );
              })}
            </div>
          )}

          <div className="finder-foot">
            <span className="note">{t.finder.missing_note}</span>
            {canLoadMoreGroups && (
              <button
                className="svc-action load-more"
                onClick={() => setLimit(l => l + 8)}
                type="button"
              >
                {t.finder.load_more} <span>→</span>
              </button>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

// ========== FAQ ==========
const Faq = ({ t }) => {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq" className="section" style={{ background: "var(--bg-2)" }}>
      <div className="wrap faq-wrap">
        <div className="faq-aside">
          <span className="eyebrow">{t.faq.eyebrow}</span>
          <h3 style={{ marginTop: 16 }}>{t.faq.h}</h3>
          <p style={{ color: "var(--muted)" }}>{t.faq.sub}</p>
          <div className="faq-contact">
            <div className="v">{t.faq.desk}</div>
            <div className="k">{t.faq.hours}</div>
            <div className="ph" style={{ marginTop: 8, direction: "ltr" }}>+962 7 755 300 45</div>
          </div>
        </div>
        <div className="faq-list">
          {t.faq.items.map((it, i) => (
            <div className={"faq-item " + (open === i ? "open" : "")} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{it.q}</span>
                <span className="plus">+</span>
              </button>
              <div className="faq-a"><div className="faq-a-inner">{it.a}</div></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ========== Support (unified) ==========
// Replaces the prior dual-CTA + "Three ways to reach us" sections — they
// repeated the same address/phone twice within ~600px of each other. One
// section covers both audiences: a customer cluster (Visit / Call / WhatsApp
// / Email) stacked above a partner cluster (Inquiry / Call / Onboarding PDF).
// Stacked, not tabbed — both audiences should *see* both paths exist on a
// regulated financial site.
const SupportCard = ({ ch, lang }) => {
  const waText = lang === "ar"
    ? "مرحباً، أود الاستفسار عن خدمات ذهب للصرافة."
    : "Hello, I'd like to ask about Dahab Lilsarafah's services.";
  const partnerSubject = lang === "ar"
    ? "طلب شراكة — مستقبل كوم"
    : "Mustaqbalcom — partnership inquiry";

  let href = "#";
  let onClick;
  const extras = {};
  switch (ch.action) {
    case "maps":
      href = window.BRANCH_MAPS_URL || "#";
      extras.target = "_blank"; extras.rel = "noopener noreferrer";
      onClick = (e) => { e.preventDefault(); openExternal(window.BRANCH_MAPS_URL); };
      break;
    case "tel":
      href = "tel:+962775530045";
      break;
    case "wa": {
      const waHref = `https://wa.me/962775530045?text=${encodeURIComponent(waText)}`;
      href = waHref;
      extras.target = "_blank"; extras.rel = "noopener noreferrer";
      onClick = (e) => { e.preventDefault(); openExternal(waHref); };
      break;
    }
    case "mailto":
      href = "mailto:info@dahabx.jo";
      break;
    case "mailto_partner":
      href = `mailto:info@dahabx.jo?subject=${encodeURIComponent(partnerSubject)}`;
      break;
    case "pdf":
      href = "assets/mustaqbalcom-onboarding.pdf";
      extras.target = "_blank"; extras.rel = "noopener noreferrer";
      break;
    default: break;
  }

  return (
    <a className={"sup-card sup-card--" + ch.k} href={href} onClick={onClick} {...extras}>
      <span className="sup-card-lbl">{ch.lbl}</span>
      <span
        className={"sup-card-v" + (ch.mono ? " mono" : "")}
        style={ch.mono ? { direction: "ltr", textAlign: lang === "ar" ? "right" : "left" } : undefined}
      >
        {ch.v}
      </span>
      <span className="sup-card-x">
        {ch.file && <span className="sup-card-pdf" aria-hidden="true">PDF</span>}
        <span>{ch.x}</span>
      </span>
      <span className="sup-card-arrow" aria-hidden="true">→</span>
    </a>
  );
};

const Support = ({ t, lang }) => (
  <section id="contact" className="section sup-section">
    <div className="wrap">
      <div className="section-head">
        <span className="eyebrow">{t.support.eyebrow}</span>
        <h2 className="display">{t.support.h}</h2>
        <p className="lede">{t.support.sub}</p>
      </div>

      <div className="sup-cluster">
        <header className="sup-cluster-head">
          <span className="sup-pill">{t.support.cust.pill}</span>
          {t.support.cust.h && <h3 className="sup-cluster-h">{t.support.cust.h}</h3>}
        </header>
        <div className="sup-grid sup-grid--4">
          {t.support.cust.channels.map(ch => (
            <SupportCard key={ch.k} ch={ch} lang={lang} />
          ))}
        </div>
      </div>

      <div className="sup-cluster sup-cluster--partner">
        <header className="sup-cluster-head">
          <span className="sup-pill sup-pill--gold">{t.support.part.pill}</span>
          <h3 className="sup-cluster-h">{t.support.part.h}</h3>
          <p className="sup-cluster-sub">{t.support.part.sub}</p>
        </header>
        <div className="sup-grid sup-grid--3">
          {t.support.part.channels.map(ch => (
            <SupportCard key={ch.k} ch={ch} lang={lang} />
          ))}
        </div>
      </div>
    </div>
  </section>
);

// ========== Footer ==========
const Footer = ({ t, lang }) => (
  <footer>
    <div className="wrap">
      <div className="foot-top foot-top--slim">
        {/* Brand cluster. The original treatment \u2014 logo + divider + Super Agent
            badge together on one row \u2014 reads better than a stranded logo, so
            we keep it. The previous EN-mobile collision (badge wrapping onto
            the y-position of \"Privacy\") is solved by the footer's single-col
            layout at \u2264900px, which gives the brand row the full container
            width, so it never gets squeezed by the nav column. */}
        <div className="foot-brand">
          <div className="foot-brand-row">
            <Logo variant="white" />
          </div>
          <p className="tag">{t.footer.tagline}</p>
          {/* Social row — sits under the tagline in the brand cluster so the
              "who we are" column carries everything (mark, regulatory badge,
              positioning line, social presence) in one place. Quiet styling
              — outlined circles, gold on hover — so social doesn't compete
              with the regulatory mark. */}
          <div className="foot-socials" aria-label={lang === "ar" ? "تواصل اجتماعي" : "Social"}>
            <a
              href="https://www.instagram.com/dahabxjo?igsh=MWZxcmp0aGNwb2lieA=="
              target="_blank" rel="noopener noreferrer"
              aria-label="Instagram" title="Instagram"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="18" height="18" rx="5" ry="5"/>
                <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
                <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>
              </svg>
            </a>
            <a
              href="https://www.facebook.com/share/1R2teubQoN/?mibextid=wwXIfr"
              target="_blank" rel="noopener noreferrer"
              aria-label="Facebook" title="Facebook"
            >
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M22 12c0-5.52-4.48-10-10-10S2 6.48 2 12c0 4.84 3.44 8.87 8 9.8V15H8v-3h2V9.5C10 7.57 11.57 6 13.5 6H16v3h-2c-.55 0-1 .45-1 1v2h3v3h-3v6.95c5.05-.5 9-4.76 9-9.95z"/>
              </svg>
            </a>
          </div>
        </div>
        <nav className="foot-links" aria-label={lang === "ar" ? "الروابط القانونية" : "Legal & regulatory"}>
          {t.footer.links.map((l, i) => (
            <a key={i} href={l.url} target={l.external ? "_blank" : undefined} rel={l.external ? "noopener noreferrer" : undefined}>
              {l.label}
              {l.external && <span className="foot-link-ext" aria-hidden="true">↗</span>}
            </a>
          ))}
        </nav>
      </div>
      <div className="reg-note">{t.footer.reg_note}</div>
      <div className="foot-bottom">
        <span>{t.footer.copy}</span>
        <span className="cbj">{t.footer.cbj}</span>
      </div>
    </div>
  </footer>
);

// ========== App ==========
const App = () => {
  const [lang, setLang] = useState(() => localStorage.getItem("dahab.v2.lang") || "en");
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";
    // Keep the browser tab in sync with the active language. Source of truth
    // for the EN copy is the static <title> in HTML; we mirror it here for
    // AR. If you change the EN tagline, update both places.
    document.title = lang === "ar"
      ? "ذهب للصرافة — بوابتكم المالية إلى العالم"
      : "Dahab Lilsarafah — Your financial gate to the world";
    localStorage.setItem("dahab.v2.lang", lang);
  }, [lang]);

  useEffect(() => {
    document.body.classList.toggle("menu-open", menuOpen);
    return () => document.body.classList.remove("menu-open");
  }, [menuOpen]);

  const t = T[lang];

  return (
    <>
      <TopBar lang={lang} setLang={setLang} />
      <Ticker />
      <Nav t={t} lang={lang} menuOpen={menuOpen} setMenuOpen={setMenuOpen} />
      <HeroRails lang={lang} />
      <Hero t={t} lang={lang} />
      <PartnersJordan t={t} lang={lang} />
      <PartnersWorldwide t={t} lang={lang} />
      <Mustaqbalcom t={t} lang={lang} />
      <PartnerFinder t={t} lang={lang} />
      <WorldwideRails t={t} lang={lang} />
      <Why t={t} />
      <Newsroom t={t} lang={lang} />
      <Faq t={t} />
      <Support t={t} lang={lang} />
      <Footer t={t} lang={lang} />
      <QuickAssist t={t} lang={lang} />
    </>
  );
};

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