/* global React */
const { useState, useEffect, useRef } = React;
// Live, language-aware data view. Always reflects the active language set by i18n.jsx.
const D = new Proxy({}, {
  get(_t, k) {return (window.__Z21_DATA || window.SITE_DATA)[k];},
  has(_t, k) {return k in (window.__Z21_DATA || window.SITE_DATA);}
});

// Standalone-export resolver: returns the inlined blob URL when bundled
// (window.__resources keyed by original path/URL), else the original path.
if (typeof window !== 'undefined' && !window.asset) {
  window.asset = function (p) { return (window.__resources && p && window.__resources[p]) || p; };
}

// ─── Deterministic responsive columns ───────────────────────────────────────
// Replaces CSS `column-count` masonry, which (a) gave no control over which
// column an item lands in and (b) dropped/flickered transformed cards on real
// GPUs. Here every item is explicitly placed in a flex column, so rendering is
// stable and column placement is predictable across all viewports.
function useColumnCount(breakpoints) {
  // breakpoints: [[minWidthExclusive, cols], ...] in order; last [0, n] always matches.
  const compute = () => {
    const w = (typeof window !== 'undefined') ? window.innerWidth : 1280;
    for (const [min, cols] of breakpoints) { if (w > min) return cols; }
    return breakpoints[breakpoints.length - 1][1];
  };
  const [n, setN] = useState(compute);
  useEffect(() => {
    let raf = 0;
    const onResize = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => setN(compute())); };
    window.addEventListener('resize', onResize);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', onResize); };
  }, []);
  return n;
}
// Sequential chunks: keeps item order down each column, so a given item lands
// in a predictable column (used to pin specific gallery photos to a column).
function columnsChunked(items, n) {
  const per = Math.ceil(items.length / n);
  const cols = Array.from({ length: n }, () => []);
  items.forEach((it, i) => cols[Math.min(n - 1, Math.floor(i / per))].push({ it, i }));
  return cols;
}

// ─── Routing ───────────────────────────────────────────────────────────────
function useHashRoute() {
  const [route, setRoute] = useState(() => (location.hash || '#home').replace('#', ''));
  useEffect(() => {
    const onHash = () => setRoute((location.hash || '#home').replace('#', ''));
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  useEffect(() => {window.scrollTo({ top: 0, behavior: 'instant' });}, [route]);
  return route;
}

// StatCell kept as stub for legacy imports
function StatCell() {return null;}

// ─── Nav ───────────────────────────────────────────────────────────────────
const HEADSHOT_URL = "https://media.beehiiv.com/cdn-cgi/image/format=auto,fit=scale-down,onerror=redirect/uploads/user/profile_picture/afcb2df6-9025-4bbe-adce-daf180b55ffa/FullSizeRender.jpeg";

// NavMe removed per user request

// ─── Language dropdown (nav + mobile) ───────────────────────────────────────
const LANGS = [
['en', 'English', '🇬🇧'],
['tr', 'Türkçe', '🇹🇷'],
['ar', 'العربية', '🇸🇦']];


function LangDropdown({ compact }) {
  const [open, setOpen] = useState(false);
  const [lang, setLang] = useState(() => window.__Z21_LANG || 'en');
  const ref = useRef(null);
  useEffect(() => {
    const onDoc = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, []);
  const pick = (code) => {setLang(code);setOpen(false);window.setZ21Lang(code);};
  const cur = LANGS.find((l) => l[0] === lang) || LANGS[0];
  const rtl = (code) => code === 'ar';
  return (
    <div className={'lang-dd' + (compact ? ' lang-dd-compact' : '')} ref={ref}>
      <button type="button" className="lang-btn" aria-haspopup="listbox" aria-expanded={open}
      onClick={(e) => {e.stopPropagation();setOpen((o) => !o);}}>
        <span className="lang-flag" aria-hidden="true">{cur[2]}</span>
        <span className="lang-cur" dir={rtl(lang) ? 'rtl' : 'ltr'}>{cur[1]}</span>
        <span className="lang-caret" aria-hidden="true">▾</span>
      </button>
      {open &&
      <div className="lang-menu" role="listbox">
          {LANGS.map(([code, label, flag]) =>
        <button key={code} type="button" role="option" aria-selected={code === lang}
        dir={rtl(code) ? 'rtl' : 'ltr'}
        className={'lang-opt' + (code === lang ? ' is-sel' : '')}
        onClick={() => pick(code)}><span className="lang-flag" aria-hidden="true">{flag}</span><span className="lang-opt-label">{label}</span></button>
        )}
        </div>
      }
    </div>);

}

// Smooth-scroll to a Home section id, hopping back to Home first if needed.
function goToSection(id, e, after) {
  if (e) e.preventDefault();
  const doScroll = () => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: 'smooth' });
  };
  if ((location.hash || '#home') !== '#home') {location.hash = '#home';setTimeout(doScroll, 90);} else
  doScroll();
  if (after) after();
}

function Top({ route }) {
  const [mOpen, setMOpen] = useState(false);
  const U = D.ui;
  // Single-page: every nav item scrolls to a section on the home page.
  const navItems = [
  ['ai', U.nav.ai],
  ['room', U.nav.room],
  ['founders', U.nav.founders],
  ['about-sec', U.nav.about]];

  const close = () => setMOpen(false);

  useEffect(() => {
    document.body.style.overflow = mOpen ? 'hidden' : '';
    return () => {document.body.style.overflow = '';};
  }, [mOpen]);

  return (
    <>
      <div className="top" data-comment-anchor="366c421cca-div-60-7">
        <div className="container top-inner">
          <a href="#home" className="logo" onClick={close}><img src={window.asset("site/logos/zero21-logo.svg")} alt="zero21" className="logo-img" /></a>
          <div className="top-right">
            {navItems.map(([k, l]) =>
            <a key={k} href={'#home'} className="nav-link" onClick={(e) => goToSection(k, e)}>{l}</a>
            )}
            <a href="#about" className="nav-link" onClick={close}>{U.nav.aboutPage}</a>
            <a href="https://scalable.news" target="_blank" rel="noopener" className="nav-link">{U.nav.newsletter}</a>
            <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="start" onClick={close}>{U.bookCall}</a>
            <LangDropdown />
            <button className="burger" onClick={() => setMOpen((o) => !o)} aria-label={mOpen ? 'Close menu' : 'Open menu'} aria-expanded={mOpen}>
              <span className={'burger-icon' + (mOpen ? ' is-open' : '')}>
                <span></span><span></span><span></span>
              </span>
            </button>
          </div>
        </div>
      </div>
      {mOpen &&
      <div className="mobile-menu" onClick={close}>
          <div className="mobile-menu-inner" onClick={(e) => e.stopPropagation()}>
            <div className="mobile-menu-links">
              {navItems.map(([k, l]) =>
            <a key={k} href={'#home'} className="mm-link" onClick={(e) => goToSection(k, e, close)}>{l}</a>
            )}
              <a href="#about" className="mm-link" onClick={close}>{U.nav.aboutPage}</a>
              <a href="https://scalable.news" target="_blank" rel="noopener" className="mm-link" onClick={close}>{U.nav.newsletter}</a>
            </div>
            <LangDropdown compact />
            <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary mm-cta" onClick={close}>{U.bookCall}</a>
          </div>
        </div>
      }
    </>);

}

// ─── Trust / logo marquee ──────────────────────────────────────────────────
// Real brand logos, normalized to a single ink tone + per-logo optical height so
// transparent, colored, badge, and wordmark logos all read at the same visual level.
function MarqueeItem({ item }) {
  const inner =
  <img
    className={'trust-logo' + (item.darken ? ' trust-logo-darken' : '')}
    src={window.asset(item.src)}
    alt={item.name}
    loading="lazy"
    style={item.h ? { height: item.h + 'px' } : null} />;


  if (item.link) {
    return (
      <a className="marquee-item" href={item.link} target="_blank" rel="noopener" aria-label={item.name}>{inner}</a>);

  }
  return <div className="marquee-item">{inner}</div>;
}

function Trust() {
  const logos = D.trustLogos || [];
  // Duplicate list for seamless loop
  const doubled = [...logos, ...logos];
  return (
    <div className="trust-marquee" data-comment-anchor="6480f91ff2-div-138-5">
      <div className="container">
        <div className="trust-head">
          <span className="lab">{D.ui.trustHead}</span>
        </div>
      </div>
      <div className="marquee-wrap">
        <div className="marquee-track">
          {doubled.map((it, i) => <MarqueeItem key={it.name + '-' + i} item={it} />)}
        </div>
      </div>
    </div>);

}

// ─── Reusable section CTA, single consistent action ──────────────────────
function SectionCTA({ anchor }) {
  const bookCall = D.ui.bookCall;
  if (anchor) {
    // The closing CTA before the footer: holds the contact-anchor + real action.
    return (
      <div className="section-cta" id="contact-anchor">
        <div className="section-cta-btns">
          <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary">{bookCall}</a>
        </div>
      </div>);

  }
  return (
    <div className="section-cta">
      <div className="section-cta-btns">
        <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary">{bookCall}</a>
      </div>
    </div>);

}

// ─── Building with AI ──────────────────────────────────────────────────────
function BuildingAISection() {
  const B = D.buildingAI;
  return (
    <section className="s buildai-section dark-section" id="ai">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <span className="s-ix-plain"><span className="lab">{B.eyebrow}</span></span>
            <h2>{D.ui.buildAiPre}<span className="it">{D.ui.buildAiKey}</span>{D.ui.buildAiPost}</h2>
          </div>
          <div className="lede">{B.sub}</div>
        </div>
        <div className="buildai-wrap">
          <div className="buildai-shot buildai-stack-wrap" data-comment-anchor="597c91d67d-div-186-11">
            {(() => {const AIStack = window.AIStack;return AIStack ? <AIStack /> : null;})()}
          </div>
          <div className="buildai-caps">
            {B.caps.map((c, i) =>
            <div key={i} className="buildai-card">
                <span className="buildai-k">{c.k}</span>
                <p>{c.d}</p>
              </div>
            )}
          </div>
        </div>
        <p className="buildai-note">{B.note}</p>
        <SectionCTA />
      </div>
    </section>);

}

// ─── Out in the ecosystem · full-bleed horizontal photo strip ──────────────
// A single edge-to-edge, auto-scrolling repetition of the event photos. Saves
// the vertical space the old masonry columns ate, and reads the same on web and
// mobile. The list is duplicated once so translateX(-50%) loops seamlessly.
function InTheRoomSection() {
  const G = D.gallery;
  const strip = [...G.items, ...G.items];
  return (
    <section className="s room-section" id="room">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <span className="s-ix-plain"><span className="lab">{G.eyebrow}</span></span>
            <h2 data-comment-anchor="7808611edb-h2-206-13">{G.title}</h2>
          </div>
          <div className="lede">{G.sub}</div>
        </div>
      </div>
      <div className="room-marquee">
        <div className="room-marquee-track">
          {strip.map((it, i) =>
          <figure
            key={it.id + '-' + i}
            className={'room-strip-cell room-' + it.id}
            aria-hidden={i >= G.items.length ? 'true' : undefined}>
              <img src={window.asset(it.src)} alt={it.label || ''} loading="lazy" style={it.pos ? { objectPosition: it.pos } : null} />
              {it.label ? <figcaption>{it.label}</figcaption> : null}
            </figure>
          )}
        </div>
      </div>
    </section>);

}

// ─── Problem section, dark bg ─────────────────────────────────────────────
function ProblemSection() {
  const P = D.problem;
  return (
    <section className="s problem-s dark-section">
      <div className="container">
        <div className="problem-grid">
          <div className="problem-left">
            <span className="s-ix-plain"><span className="lab">{P.eyebrow}</span></span>
            <h2 dangerouslySetInnerHTML={{ __html: P.title.replace('stuck.', '<span class="it">stuck.</span>') }} />
            <p className="problem-close">{P.close}</p>
            <a href="#contact" className="btn primary">Book a call →</a>
          </div>
          <ul className="problem-list">
            {P.points.map((pt) =>
            <li key={pt.n} className="problem-item">
                <span className="problem-n">{pt.n}</span>
                <span className="problem-text">{pt.text}</span>
              </li>
            )}
          </ul>
        </div>
      </div>
    </section>);

}

// ─── Services · horizontal flow (shared by closing section + Services page) ──
function ServicesFlow() {
  const [active, setActive] = useState(0);
  const S = D.services;
  return (
    <div className="flow">
      <div className="flow-rail" aria-hidden="true"><span className="flow-pulse"></span></div>
      <div className="flow-nodes">
        {S.map((s, i) =>
        <button
          key={s.n}
          type="button"
          className={'flow-node' + (active === i ? ' is-active' : '')}
          onMouseEnter={() => setActive(i)}
          onFocus={() => setActive(i)}
          onClick={() => setActive(i)}
          aria-pressed={active === i}>

            <span className="flow-dot" aria-hidden="true"></span>
            <span className="flow-num">{s.n}</span>
            <span className="flow-node-sub">{s.sub}</span>
            <span className="flow-node-title">{s.title}</span>
          </button>
        )}
      </div>
      <div className="flow-detail" key={active}>
        <p className="flow-detail-text">{S[active].blurb}</p>
        <div className="flow-detail-foot">
          <span className="flow-gain">{S[active].gain}</span>
          <div className="flow-tags">{S[active].tags.map((t) => <span key={t} className="flow-tag">{t}</span>)}</div>
        </div>
      </div>
    </div>);

}

// ─── Services · standalone section (used on the Services subpage) ───────────
function ServicesSection({ isSubpage }) {
  return (
    <section className="s flow-section dark-section" id="services-anchor">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <h2>{D.ui.servicesHead}<span className="it">{D.ui.servicesHeadIt}</span></h2>
          </div>
          <div className="lede">{D.ui.servicesLede}</div>
        </div>
        <ServicesFlow />
        {!isSubpage && <SectionCTA anchor />}
      </div>
    </section>);

}

// ─── Testimonials · scattered wall, every card a link ──────────────────────
function TestimonialsSection() {
  const T = D.testimonials;
  // Mobile keeps two columns (never collapses to one) per request.
  const nCols = useColumnCount([[1100, 3], [0, 2]]);
  // Sequential layout: list order maps directly to on-screen position (items 1-4 -> col 1,
  // 5-8 -> col 2, 9-12 -> col 3 at three columns). The order in data-clean.jsx is hand-tuned
  // for balanced column heights + one female founder per row + the Rewa/Thunder/Sylus trio.
  const cols = columnsChunked(T, nCols);
  const renderCard = (t, i) => {
    const previewSrc = t.preview || null;
    const Tag = t.site ? 'a' : 'figure';
    const linkProps = t.site ? { href: t.site, target: '_blank', rel: 'noopener' } : {};
    return (
      <Tag key={t.name} {...linkProps} className={'twall-card twc-' + (i % 6) + (t.site ? ' is-link' : '')}>
        {previewSrc &&
        <div className="twall-prev">
            <img className="twall-prev-img" src={window.asset(previewSrc)} alt={t.company} loading="lazy" onError={(e) => {e.target.parentNode.style.display = 'none';}} />
          </div>
        }
        <blockquote className="twall-quote">{t.quote}</blockquote>
        <figcaption className="twall-who">
          {t.headshot ?
          <img className="twall-av" src={window.asset(t.headshot)} alt={t.name} loading="lazy" onError={(e) => {e.target.style.display = 'none';}} /> :
          <span className="twall-av-init">{t.initial}</span>}
          <span className="twall-nm">
            <span className="twall-name">{t.name}</span>
            <span className="twall-role">{t.role}{t.company ? ' · ' + t.company : ''}{t.site ? ' ↗' : ''}</span>
          </span>
        </figcaption>
      </Tag>);

  };
  return (
    <section className="twall" id="founders" data-screen-label="Testimonials">
      <div className="container">
        <div className="twall-head">
          <span className="lab">{D.ui.foundersLab}</span>
          <h2>{D.ui.foundersHead}<span className="it">{D.ui.foundersHeadIt}</span></h2>
        </div>
        <div className="twall-grid">
          {cols.map((col, ci) =>
          <div className="twall-col" key={ci}>
              {col.map(({ it, i }) => renderCard(it, i))}
            </div>
          )}
        </div>
        <SectionCTA />
      </div>
    </section>);

}

// ─── Scalable newsletter · transplanted from scalable.news ──────────────────
function ScalableSection() {
  const S = D.scalable;
  const handleSubmit = (e) => {
    e.preventDefault();
    const email = e.target.querySelector('input[type="email"]').value;
    const dest = email ?
    `${S.url}?email=${encodeURIComponent(email)}` :
    S.url;
    window.open(dest, '_blank', 'noopener');
  };
  return (
    <section className="s scalable-feature" id="scalable">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <span className="s-ix-plain"><span className="lab">Also from Egemen</span></span>
            <h2>The newsletter behind <span className="it">the work.</span></h2>
          </div>
          <div className="lede">Scalable is a weekly read on AI, product, and building from zero. The same thinking behind the work, delivered to your inbox.</div>
        </div>

        {/* Black, Inter-themed card lifted straight from scalable.news */}
        <div className="sn-card" data-comment-anchor="1aec4b110f-div-357-7">
          <div className="sn-card-left">
            <a className="sn-brand" href={S.url} target="_blank" rel="noopener" aria-label="SCALABLE">
              <span className="sn-logo-wrap"><img src={S.logo} alt="" /></span>
              <span className="sn-brand-text">
                <span className="sn-word">SCALABLE</span>
                <span className="sn-freq">Free weekly newsletter</span>
              </span>
            </a>
            <h3 className="sn-title">{S.title}</h3>
            <div className="sn-proof">
              <span className="sn-stars" aria-label="5 stars">★★★★★</span>
              <span className="sn-proof-sep"></span>
              <span className="sn-proof-text">Practical. Founder-first. No fluff.</span>
            </div>
          </div>

          <div className="sn-card-right">
            <form className="sn-form" onSubmit={handleSubmit}>
              <input
                className="sn-input"
                type="email"
                placeholder="your@email.com"
                aria-label="Email address"
                required />
              <button className="sn-submit" type="submit">
                <span>Subscribe</span>
                <span className="sn-arrow" aria-hidden="true">→</span>
              </button>
            </form>
            <p className="sn-disclaimer">Free. No spam. Unsubscribe any time.</p>
            <div className="sn-trusted">
              <p className="sn-trusted-label">{S.trustedLabel}</p>
              <div className="sn-logos">
                {S.trustedLogos.map((src, i) =>
                <img
                  key={i}
                  className="sn-trust-logo"
                  src={src}
                  alt=""
                  loading="lazy"
                  onError={(e) => {e.target.style.display = 'none';}} />
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

// PullQuote kept for any legacy imports
function PullQuote() {return null;}

// ─── Work ──────────────────────────────────────────────────────────────────

// Per-card config: accent color scheme + external link for social proof
const WORK_META = {
  a: {
    scheme: 'dark', // dark moss bg
    link: 'https://www.linkedin.com/company/sallis-io/',
    linkLabel: 'sallis.io on LinkedIn',
    metricBig: '$200K+',
    metricSub: 'revenue · 6 months · then acquired',
    tag: 'Venture Studio'
  },
  b: {
    scheme: 'light',
    link: 'https://watermelonecosystem.com',
    linkLabel: 'Watermelon Ecosystem',
    metricBig: '$50K/yr',
    metricSub: 'saved · invoice financing · live',
    tag: 'F&B Marketplace'
  },
  c: {
    scheme: 'dark',
    link: 'https://www.linkedin.com/company/spring-studios-bahrain/',
    linkLabel: 'Spring Studios on LinkedIn',
    metricBig: '60+',
    metricSub: 'founders · 3 startups · 2 cohorts',
    tag: 'Fintech Studio'
  },
  d: {
    scheme: 'accent', // gold-tinted panel for contrast
    link: 'https://papara.com',
    linkLabel: 'papara.com',
    metricBig: '30+',
    metricSub: 'enterprise clients · new B2B line',
    tag: 'B2B Payments'
  }
};

function WorkCard({ w, index }) {
  const [flipped, setFlipped] = useState(false);
  const meta = WORK_META[w.id] || {};

  return (
    <div
      className={'wc2-card wc2-' + (meta.scheme || 'light') + (flipped ? ' flipped' : '')}
      onClick={() => setFlipped((f) => !f)}>
      
      <div className="wc2-flipper">
        {/* Front face */}
        <div className="wc2-face wc2-face-front">
          <div className="wc2-top-row">
            <span className="wc2-tag">{meta.tag || w.kind.split('·')[0].trim()}</span>
            <span className="wc2-num">0{index + 1}</span>
          </div>
          <div className="wc2-client">{w.client.split('·')[0].trim()}</div>
          <div className="wc2-metric-big">{meta.metricBig}</div>
          <div className="wc2-metric-sub">{meta.metricSub}</div>
          <h3 className="wc2-title">{w.title}</h3>
          <div className="wc2-footer">
            <span className="wc2-kind">{w.kind}</span>
            <span className="wc2-flip-hint">{D.ui.flipFor}</span>
          </div>
        </div>

        {/* Back face */}
        <div className="wc2-face wc2-face-back">
          <div className="wc2-top-row">
            <span className="wc2-tag">{meta.tag || w.kind.split('·')[0].trim()}</span>
            <span className="wc2-flip-hint" style={{ fontSize: '11px' }}>{D.ui.flipBack}</span>
          </div>
          <div className="wc2-back-body">
            <div className="wc2-back-block">
              <span className="wc2-back-label">{D.ui.situation}</span>
              <p>{w.situation}</p>
            </div>
            <div className="wc2-back-block">
              <span className="wc2-back-label">{D.ui.whatChanged}</span>
              <p>{w.did}</p>
            </div>
          </div>
          {meta.link &&
          <a
            href={meta.link}
            target="_blank"
            rel="noopener noreferrer"
            className="wc2-ext-link"
            onClick={(e) => e.stopPropagation()}>
            
              {meta.linkLabel} ↗
            </a>
          }
        </div>
      </div>
    </div>);

}

function WorkSection({ isSubpage }) {
  return (
    <section className="s wc2-section" id="work-anchor">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <h2>{D.ui.workHead}<span className="it">{D.ui.workHeadIt}</span></h2>
          </div>
          <div className="lede">{D.ui.workLede}</div>
        </div>
        <div className="wc2-grid">
          {D.work.map((w, i) => <WorkCard key={w.id} w={w} index={i} />)}
        </div>
        {!isSubpage && <SectionCTA />}
      </div>
    </section>);

}

// ─── Process ───────────────────────────────────────────────────────────────
function ProcessSection({ isSubpage }) {
  const P = D.process;
  return (
    <section className="s how-band dark-section" id="how">
      <div className="container">
        <div className="s-head">
          <div className="h-left">
            <h2 style={{ width: "640px" }}>Real progress from <span className="it">the first call.</span></h2>
          </div>
          <div className="lede">From the first call to real progress is short. </div>
        </div>
        <div className="how-row">
          {P.map((p, i) =>
          <div key={p.n} className="how-step">
              <span className="how-ix">{p.n}</span>
              <h4>{p.title}</h4>
              <p>{p.desc}</p>
              {i < P.length - 1 && <span className="how-arrow" aria-hidden="true">→</span>}
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ─── Region Map, Leaflet ─────────────────────────────────────────────────
function RegionMap() {
  const mapRef = useRef(null);
  const instanceRef = useRef(null);

  useEffect(() => {
    if (!mapRef.current || instanceRef.current) return;

    // Leaflet loaded from CDN in index.html
    const L = window.L;
    if (!L) return;

    const map = L.map(mapRef.current, {
      center: [30.5, 44],
      zoom: 5,
      zoomControl: false,
      scrollWheelZoom: false,
      attributionControl: false,
      dragging: false,
      doubleClickZoom: false,
      boxZoom: false,
      keyboard: false
    });
    instanceRef.current = map;

    // Monochrome tile layer, CartoDB Positron (light, clean)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
      maxZoom: 19
    }).addTo(map);

    // Engagement cities
    const cities = [
    { name: 'Dubai', lat: 25.2048, lng: 55.2708, note: 'HQ · Watermelon · sallis.io', hq: true },
    { name: 'Abu Dhabi', lat: 24.4539, lng: 54.3773, note: 'Advisory · UAE' },
    { name: 'Istanbul', lat: 41.0082, lng: 28.9784, note: 'Papara · B2B payments' },
    { name: 'Ankara', lat: 39.9334, lng: 32.8597, note: 'Fintech · product' },
    { name: 'Jeddah', lat: 21.4858, lng: 39.1925, note: 'KAUST TAQADAM' },
    { name: 'Riyadh', lat: 24.7136, lng: 46.6753, note: 'Advisory · KSA' },
    { name: 'Doha', lat: 25.2854, lng: 51.5310, note: 'Advisory · Qatar' },
    { name: 'Muscat', lat: 23.5880, lng: 58.3829, note: 'Advisory · Oman' },
    { name: 'Manama', lat: 26.2285, lng: 50.5860, note: 'Spring Studios · fintech launches' }];


    // Animated flight-path arcs from the Dubai HQ to every other city.
    const hqCity = cities.find((c) => c.hq) || cities[0];
    cities.forEach((city) => {
      if (city === hqCity) return;
      L.polyline([[hqCity.lat, hqCity.lng], [city.lat, city.lng]], {
        color: '#C8862A', weight: 1.4, opacity: 0.45,
        dashArray: '2 7', lineCap: 'round', className: 'rmap-arc', interactive: false
      }).addTo(map);
    });

    cities.forEach((city) => {
      const size = city.hq ? 22 : 16;
      const icon = L.divIcon({
        className: '',
        html: `<div class="rmap-pin ${city.hq ? 'is-hq' : ''}"><span class="rmap-ring"></span><span class="rmap-ring rmap-ring-2"></span><span class="rmap-core"></span></div>`,
        iconSize: [size, size],
        iconAnchor: [size / 2, size / 2]
      });

      L.marker([city.lat, city.lng], { icon }).
      addTo(map).
      bindTooltip(`<strong style="color:#C8862A;font-family:monospace;font-size:10px;letter-spacing:0.12em;text-transform:uppercase">${city.name}</strong><br><span style="font-size:10px;color:#6E6753">${city.note}</span>`, {
        permanent: false,
        direction: 'top',
        offset: [0, -8],
        className: 'rmap-tooltip'
      });
    });

    // Frame tightly on GCC + Türkiye (markers define the bounds, nothing extra)
    const bounds = L.latLngBounds(cities.map((c) => [c.lat, c.lng]));
    const fit = () => map.fitBounds(bounds, { padding: [26, 26], maxZoom: 7 });
    fit();

    // The map cell now stretches to match the content column, so its final
    // height is only known after layout settles. Re-measure and re-frame.
    const ro = new ResizeObserver(() => {map.invalidateSize();fit();});
    ro.observe(mapRef.current);
    setTimeout(() => {map.invalidateSize();fit();}, 300);

    return () => {
      ro.disconnect();
      map.remove();
      instanceRef.current = null;
    };
  }, []);

  return (
    <div className="rmap-wrap">
      <div ref={mapRef} className="rmap-leaflet" data-comment-anchor="568dae725d-div-649-7"></div>
    </div>);

}

// ─── Shared contact / message form ─────────────────────────────────────────
function ContactForm() {
  const C = D.contact;
  const U = D.ui;
  const handleSend = (e) => {
    e.preventDefault();
    const f = e.target;
    const name = f.elements.name.value.trim();
    const email = f.elements.email.value.trim();
    const msg = f.elements.message.value.trim();
    const subject = encodeURIComponent(name ? `Hello from ${name}` : 'Hello');
    const body = encodeURIComponent(msg + (name ? `\n\n${name}` : '') + (email ? `\n${email}` : ''));
    window.location.href = `mailto:${D.brand.email}?subject=${subject}&body=${body}`;
  };
  return (
    <div className="about-form" id="contact-anchor">
      <form className="contact-box about-contact-box" onSubmit={handleSend}>
        <input className="contact-field" name="name" type="text" placeholder={U.formName} aria-label={U.formName} required />
        <input className="contact-field" name="email" type="email" placeholder={U.formEmail} aria-label={U.formEmail} required />
        <textarea className="contact-field contact-area" name="message" rows="4" placeholder={U.formMsg} aria-label={U.formMsg} required></textarea>
        <button className="contact-send" type="submit">{U.formSend}</button>
      </form>
      <p className="about-form-note">{C.note}</p>
    </div>);

}

// ─── Closing · success-stories map (the 4-step flow follows in ServicesSection) ─
function AboutSection({ isSubpage }) {
  const A = D.about;
  return (
    <section className="s about-stories-section" id="about-sec">
      <div className="container">
        <div className="s-head" data-comment-anchor="deab7901df-div-670-9">
          <div className="h-left">
            <h2 style={{ padding: "0px 0px 16px" }}>{A.h2a} <span className="it">{A.h2b}</span></h2>
          </div>
        </div>
        <RegionMap />
        <ServicesFlow />
        <SectionCTA anchor />
      </div>
    </section>);

}


// ─── Contact ───────────────────────────────────────────────────────────────
function Contact() {
  const C = D.contact;
  return (
    <section className="contact" id="lets-talk">
      <div className="container">
        <span className="cap lab">{C.eyebrow}</span>
        <h2>{C.title.split('.')[0]}. <span className="it">{C.title.split('.')[1]?.trim() || ''}</span></h2>
        <p>{C.sub}</p>
        <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary contact-cta">{D.ui.bookCall}</a>
        <div className="contact-note">{C.note}</div>
      </div>
    </section>);

}

// ─── Footer ────────────────────────────────────────────────────────────────
function FooterBar() {
  const F = D.footer;
  return (
    <footer>
      <div className="container">
        <div className="foot-row foot-row-lean" data-comment-anchor="99f9e3aca5-div-722-9">
          <div className="foot-brand">
            <div className="footer-logo-wrap"><img src={window.asset("site/logos/zero21-logo.svg")} alt="zero21" className="footer-logo-img" /></div>
            <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary foot-cta">{D.ui.bookCall}</a>
          </div>
          <nav className="foot-links" aria-label="Footer">
            <a href="#home" onClick={(e) => goToSection('ai', e)}>{D.ui.nav.ai}</a>
            <a href="#home" onClick={(e) => goToSection('room', e)}>{D.ui.nav.room}</a>
            <a href="#home" onClick={(e) => goToSection('founders', e)}>{D.ui.nav.founders}</a>
            <a href="/blog/">Blog</a>
            <a href="https://scalable.news" target="_blank" rel="noopener">{D.ui.nav.newsletter}</a>
            <a href="#home" onClick={(e) => goToSection('about-sec', e)}>{D.ui.nav.about}</a>
          </nav>
        </div>
        <div className="foot-bot">
          <span>© zero21 · {D.brand.location}</span>
        </div>
      </div>
    </footer>);

}

// ─── Service Detail Pages ──────────────────────────────────────────────────
function ServiceDetailPage({ serviceIndex }) {
  const s = D.services[serviceIndex];
  return (
    <div className="page active">
      <div className="service-hero">
        <div className="container">
          <a href="#services" className="back-link">← Back to services</a>
          <h1>{s.title}</h1>
          <p className="service-hero-sub">{s.blurb}</p>
          <div className="service-hero-tags">
            {s.tags.map((t) => <span key={t} className="tag">{t}</span>)}
          </div>
        </div>
      </div>
      <div className="container" style={{ padding: '96px 40px', maxWidth: '1280px', margin: '0 auto' }}>
        <div className="service-detail">
          <h2 className="section-title">{s.gain}</h2>
          <p className="service-detail-text">This is where we'd expand on the specific approach, outcomes, and timeline for {s.sub.toLowerCase()}. Each service has its own deep-dive story here.</p>
          <a href="#contact" className="btn primary" style={{ marginTop: '40px' }}>Book a call →</a>
        </div>
      </div>
      <Contact />
    </div>);

}

function ServiceAIPage() {return <ServiceDetailPage serviceIndex={0} />;}
function ServiceLaunchPage() {return <ServiceDetailPage serviceIndex={1} />;}
function ServiceLeadershipPage() {return <ServiceDetailPage serviceIndex={2} />;}
function ServiceFundraisePage() {return <ServiceDetailPage serviceIndex={3} />;}

// ─── Case Studies Page ─────────────────────────────────────────────────────
function CaseStudiesPage() {
  return (
    <div className="page active">
      <div className="case-studies-hero">
        <div className="container">
          <a href="#home" className="back-link">← Back to home</a>
          <h1>Case Studies</h1>
          <p>Four engagements from the last three years. Full details.</p>
        </div>
      </div>
      <section className="s wc2-section">
        <div className="container">
          <div className="wc2-grid">
            {D.work.map((w, i) => <WorkCard key={w.id} w={w} index={i} />)}
          </div>
          <div style={{ textAlign: 'center', marginTop: '60px' }}>
            <a href="#contact" className="btn primary">Book a call →</a>
          </div>
        </div>
      </section>
      <Contact />
    </div>);

}

// ─── Page shells ───────────────────────────────────────────────────────────
function ServicesPage() {
  return (
    <div className="page active">
      <div className="services-page-hero">
        <div className="container">
          <a href="#home" className="back-link">← Back to home</a>
          <h1>How we work together</h1>
          <p>Each engagement is scoped tightly: a 90-day embed, a focused sprint, or an ongoing embedded role. Pick the approach that fits your timeline and budget.</p>
        </div>
      </div>
      <ServicesSection isSubpage={true} />
      <Contact />
    </div>);

}

function WorkPage() {
  return (
    <div className="page active">
      <div className="work-page-hero">
        <div className="container">
          <a href="#home" className="back-link">← Back to home</a>
          <h1>Selected work</h1>
          <p>Four engagements from the last three years. Names are real, numbers are accurate.</p>
        </div>
      </div>
      <WorkSection isSubpage={true} />
      <Contact />
    </div>);

}

function AboutPage() {
  const A = D.about;
  const U = D.ui;
  return (
    <div className="page active">
      <div className="about-page-hero">
        <div className="container">
          <a href="#home" className="back-link">← {U.backHome}</a>
        </div>
      </div>
      <section className="s about-page-section">
        <div className="container">
          <div className="about-page-grid">
            <div className="about-page-portrait">
              <div className="about-portrait">
                <img src={window.asset(HEADSHOT_URL)} alt="Egemen Eres" loading="lazy" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 20%' }} />
              </div>
            </div>
            <div className="about-page-content">
              {A.pageEyebrow && <span className="s-ix-plain"><span className="lab">{A.pageEyebrow}</span></span>}
              <h1>{A.pageTitle || A.title}</h1>
              {A.bio && <p className="about-page-bio">{A.bio}</p>}
              {A.bio2 && <p className="about-page-bio">{A.bio2}</p>}
              <div className="about-page-facts">
                {A.facts.map((f, i) =>
                <div key={i} className="fact-row">
                    <span className="fact-num">0{i + 1}</span>
                    <span className="fact-text">{f}</span>
                  </div>
                )}
              </div>
              <a href={D.brand.bookingUrl} target="_blank" rel="noopener" className="btn primary" style={{ marginTop: '40px' }}>{U.bookCall}</a>
            </div>
          </div>
        </div>
      </section>
      <Contact />
    </div>);

}

// ─── 404 ─────────────────────────────────────────────────────────────────────
function NotFound() {
  const U = D.ui;
  return (
    <div className="page active nf-page">
      <div className="container nf-wrap">
        <span className="nf-code">404</span>
        <h1 className="nf-title">{U.notFoundTitle}</h1>
        <p className="nf-sub">{U.notFoundSub}</p>
        <a href="#home" className="btn primary nf-btn">{U.backHome}</a>
      </div>
    </div>);

}

window.zero21blend = {
  useHashRoute, Top, StatCell, PullQuote, Trust, FooterBar,
  ProblemSection, ServicesSection, WorkSection, ProcessSection, AboutSection, Contact, ContactForm,
  TestimonialsSection, SectionCTA, BuildingAISection, InTheRoomSection, ScalableSection, NotFound,
  ServicesPage, WorkPage, AboutPage, CaseStudiesPage,
  ServiceAIPage, ServiceLaunchPage, ServiceLeadershipPage, ServiceFundraisePage
};