/* LuxuryProperty.com — investor microsite (Palm Jumeirah + brand shell).
   Cinematic dark hero · warm editorial body · feed-driven listing UX.
   Reads i18n.js (LP_LOCALES) and data.js (LP_DATA).                    */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "locale": "en",
  "palette": "warm-stone",
  "showSampleBadges": true,
  "density": "luxe",
  "heroVariant": "palm"
}/*EDITMODE-END*/;

/* ────────────────── icons (hand-rolled minimal set) ─────────────────── */
const Icon = {
  arrow: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><path d="M5 12h14M13 6l6 6-6 6" /></svg>,
  arrowSm: (p) => <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M5 12h14M13 6l6 6-6 6" /></svg>,
  whatsapp: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" {...p}><path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 2.1.67 4.06 1.81 5.66L2 22l4.55-1.91a9.86 9.86 0 0 0 5.49 1.66h.01c5.46 0 9.91-4.45 9.91-9.92C21.96 6.45 17.5 2 12.04 2zm5.79 14.06c-.25.7-1.45 1.34-1.99 1.42-.54.08-1.13.12-1.78-.11-.41-.13-.94-.31-1.62-.6-2.85-1.23-4.71-4.1-4.85-4.29-.14-.19-1.16-1.54-1.16-2.95s.74-2.1.99-2.39c.25-.29.55-.36.74-.36h.55c.18 0 .42-.07.66.5.25.6.83 2.07.91 2.22.07.15.12.32.02.51-.1.19-.15.31-.3.48-.15.17-.31.38-.45.51-.15.15-.3.31-.13.6.18.29.78 1.29 1.68 2.08 1.16 1.04 2.13 1.36 2.42 1.51.29.15.46.13.63-.07.18-.2.74-.85.94-1.14.19-.29.4-.25.66-.15.27.1 1.73.81 2.02.96.29.15.48.22.55.34.07.13.07.7-.18 1.4z"/></svg>,
  phone: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><path d="M6.6 10.8a14 14 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25c1.1.36 2.3.55 3.5.55a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A18 18 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.2.2 2.4.55 3.5a1 1 0 0 1-.25 1z" /></svg>,
  pin: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><path d="M12 22s7-7.6 7-13a7 7 0 0 0-14 0c0 5.4 7 13 7 13z" /><circle cx="12" cy="9" r="2.5" /></svg>,
  close: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><path d="M6 6l12 12M18 6L6 18" /></svg>,
  globe: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 3 2.5 15 0 18M12 3c-2.5 3-2.5 15 0 18" /></svg>,
  bed: (p) => <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M3 18v-7a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v7M3 14h18M3 18v2M21 18v2" /><circle cx="7.5" cy="11" r="1.5" /></svg>,
  bath: (p) => <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M4 12h16v3a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4v-3zM6 12V6a2 2 0 0 1 2-2h2v3" /></svg>,
  area: (p) => <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M4 4h16v16H4zM4 9h16M9 4v16" /></svg>,
  check: (p) => <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M4 12l5 5L20 6" /></svg>,
};

/* ───────────────────────── tweaks integration ───────────────────────── */
const PALETTES = {
  'warm-stone':   { name: 'Warm stone',     swatch: ['#0E1114','#B8995E','#F7F5F1'] },
  'graphite':     { name: 'Graphite',       swatch: ['#0B0D10','#8FA8B2','#EFEEEA'] },
  'desert-bronze':{ name: 'Desert bronze',  swatch: ['#1A130C','#C8843A','#F4ECDF'] },
  'midnight-teal':{ name: 'Midnight teal',  swatch: ['#0A1A22','#C9A24B','#EFEFE9'] },
};

function applyPalette(name) {
  const p = name;
  const r = document.documentElement;
  if (p === 'graphite') {
    r.style.setProperty('--bg', '#0B0D10');
    r.style.setProperty('--surface', '#EFEEEA');
    r.style.setProperty('--primary', '#8FA8B2');
    r.style.setProperty('--secondary', '#13202A');
    r.style.setProperty('--accent', '#D8D5CE');
    r.style.setProperty('--focus', '#A6BFC9');
  } else if (p === 'desert-bronze') {
    r.style.setProperty('--bg', '#1A130C');
    r.style.setProperty('--surface', '#F4ECDF');
    r.style.setProperty('--primary', '#C8843A');
    r.style.setProperty('--secondary', '#2A1E12');
    r.style.setProperty('--accent', '#E8D5B8');
    r.style.setProperty('--focus', '#E4A968');
  } else if (p === 'midnight-teal') {
    r.style.setProperty('--bg', '#0A1A22');
    r.style.setProperty('--surface', '#EFEFE9');
    r.style.setProperty('--primary', '#C9A24B');
    r.style.setProperty('--secondary', '#0F2A36');
    r.style.setProperty('--accent', '#E0DAC8');
    r.style.setProperty('--focus', '#E8C25C');
  } else {
    // warm-stone (default per brief)
    r.style.setProperty('--bg', '#0E1114');
    r.style.setProperty('--surface', '#F7F5F1');
    r.style.setProperty('--primary', '#B8995E');
    r.style.setProperty('--secondary', '#16313F');
    r.style.setProperty('--accent', '#DED1BD');
    r.style.setProperty('--focus', '#D2AD68');
  }
}

/* ─────────────────────────── building blocks ────────────────────────── */
function Logo({ light }) {
  // Wordmark — original SVG; on dark surfaces use the white SVG asset,
  // on light use a typeset placeholder until the dark SVG is traced.
  if (light) {
    return <img src="media/logo-luxuryproperty-white.svg" alt="LuxuryProperty.com" className="lp-logo-img" />;
  }
  return (
    <span className="lp-logo-text">
      <span style={{fontWeight: 600}}>Luxury</span>Property<span className="lp-logo-tld">.com</span><span className="lp-logo-r">®</span>
    </span>
  );
}

function Eyebrow({ children, light, className }) {
  return <div className={`lp-eyebrow ${light ? 'on-dark' : ''} ${className || ''}`}>{children}</div>;
}

function Pill({ children, light, accent, className, onClick, active }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`lp-pill ${light ? 'on-dark' : ''} ${accent ? 'accent' : ''} ${active ? 'active' : ''} ${className || ''}`}
    >{children}</button>
  );
}

function Btn({ kind = 'primary', light, onClick, type = 'button', children, full, sm, as: As = 'button', href, target }) {
  const cls = `lp-btn lp-btn-${kind} ${light ? 'on-dark' : ''} ${full ? 'full' : ''} ${sm ? 'sm' : ''}`;
  if (As === 'a') {
    return <a href={href} target={target} className={cls} onClick={onClick}>{children}</a>;
  }
  return <button type={type} className={cls} onClick={onClick}>{children}</button>;
}

function SectionHead({ eyebrow, title, sub, light, align = 'start' }) {
  return (
    <div className={`lp-sechead ${light ? 'on-dark' : ''} align-${align}`}>
      {eyebrow ? <Eyebrow light={light}>{eyebrow}</Eyebrow> : null}
      <h2 className="lp-h2">{title}</h2>
      {sub ? <p className="lp-sub">{sub}</p> : null}
    </div>
  );
}

/* ─────────────────────────────── NAV ────────────────────────────────── */
function Nav({ t, locale, onLocale, onOpenViewing }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`lp-nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="lp-nav-inner">
        <a href="#top" className="lp-nav-logo"><Logo light={!scrolled} /></a>
        <nav className="lp-nav-links">
          <a href="#communities">{t.nav.communities}</a>
          <a href="#listings">{t.nav.buy}</a>
          <a href="#listings">{t.nav.rent}</a>
          <a href="#offplan">{t.nav.offplan}</a>
          <a href="#sell">{t.nav.sell}</a>
          <a href="#team">{t.nav.team}</a>
          <a href="#contact">{t.nav.contact}</a>
        </nav>
        <div className="lp-nav-actions">
          <LocaleSwitcher locale={locale} onLocale={onLocale} />
          <Btn kind="ghost" light={!scrolled} sm as="a" href="https://wa.me/971585097626" target="_blank">
            <Icon.whatsapp /> <span>{t.nav.whatsapp}</span>
          </Btn>
          <Btn kind="primary" sm onClick={onOpenViewing}>{t.nav.bookViewing}</Btn>
        </div>
      </div>
    </header>
  );
}

function LocaleSwitcher({ locale, onLocale }) {
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  return (
    <div className="lp-locale" ref={ref}>
      <button className="lp-locale-btn" onClick={() => setOpen(o => !o)}>
        <Icon.globe /> <span>{window.LP_LOCALES[locale].short}</span>
      </button>
      {open ? (
        <div className="lp-locale-menu">
          {Object.entries(window.LP_LOCALES).map(([code, l]) => (
            <button key={code} className={`lp-locale-opt ${code === locale ? 'active' : ''}`} onClick={() => { onLocale(code); setOpen(false); }}>
              <span className="code">{l.short}</span> <span className="name">{l.label}</span>
              {code === locale ? <Icon.check /> : null}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}

/* ─────────────────────────────── HERO ───────────────────────────────── */
const HERO_IMAGES = {
  palm: 'media/editorial-palm-district-one.webp',
  skyline: 'media/editorial-dubai-skyline.webp',
  villa: 'media/listing-sample-villa.webp',
  about: 'media/brand-about-us-hero.webp',
};

function Hero({ t, onOpenViewing, onOpenValuation, heroVariant }) {
  const img = HERO_IMAGES[heroVariant] || HERO_IMAGES.palm;
  return (
    <section className="lp-hero" id="top">
      <div className="lp-hero-media" key={img}>
        <img src={img} alt="" className="lp-hero-img" />
        <div className="lp-hero-shade" />
        <div className="lp-hero-grain" />
      </div>
      <div className="lp-hero-content">
        <Eyebrow light>{t.hero.eyebrow}</Eyebrow>
        <h1 className="lp-h1">{t.hero.title}</h1>
        <p className="lp-hero-sub">{t.hero.sub}</p>
        <div className="lp-hero-ctas">
          <Btn kind="primary" onClick={onOpenViewing}>{t.hero.ctaPrimary} <Icon.arrowSm /></Btn>
          <Btn kind="ghost" light onClick={onOpenValuation}>{t.hero.ctaSecondary}</Btn>
        </div>
      </div>
      <div className="lp-hero-meta">
        <div className="lp-hero-meta-item">
          <span className="k">Microsite</span>
          <span className="v">Palm Jumeirah</span>
        </div>
        <div className="lp-hero-meta-item">
          <span className="k">Brokerage</span>
          <span className="v">LuxuryProperty.com</span>
        </div>
        <div className="lp-hero-meta-item">
          <span className="k">Status</span>
          <span className="v"><span className="lp-dot" /> Demo build · feed-ready</span>
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────── SEARCH BAR (under hero) ────────────────────── */
function SearchBar({ t }) {
  const [tab, setTab] = useState('buy');
  return (
    <section className="lp-search-wrap">
      <div className="lp-search">
        <div className="lp-search-tabs">
          {['buy','rent','offplan'].map(k => (
            <button key={k} className={`lp-search-tab ${tab === k ? 'active' : ''}`} onClick={() => setTab(k)}>
              {t.search[k]}
            </button>
          ))}
        </div>
        <div className="lp-search-fields">
          <SearchField label={t.search.community} options={['Palm Jumeirah','Emirates Hills','Dubai Hills','Business Bay','Dubai Creek Harbour']} t={t} />
          <SearchField label={t.search.type} options={['Villa','Mansion','Penthouse','Apartment','Land']} t={t} />
          <SearchField label={t.search.beds} options={['1','2','3','4','5','6+']} t={t} />
          <SearchField label={t.search.price} options={['AED 5–15M','AED 15–30M','AED 30–60M','AED 60M+','POA']} t={t} />
          <button className="lp-search-go" aria-label={t.search.search}>
            <span className="lp-search-go-lbl">{t.search.search}</span>
            <Icon.arrowSm />
          </button>
        </div>
        <div className="lp-search-hint"><span className="lp-dot live" /> {t.search.hint}</div>
      </div>
    </section>
  );
}
function SearchField({ label, options, t }) {
  return (
    <label className="lp-field">
      <span className="lp-field-lbl">{label}</span>
      <select className="lp-field-sel">
        <option>{t.search.any}</option>
        {options.map(o => <option key={o}>{o}</option>)}
      </select>
    </label>
  );
}

/* ─────────────────────────── STATS STRIP ─────────────────────────────── */
function Stats({ t }) {
  return (
    <section className="lp-stats" id="about">
      <div className="lp-container">
        <div className="lp-stats-head">
          <Eyebrow>The brokerage</Eyebrow>
          <h2 className="lp-h2">{t.stats.title}</h2>
          <p className="lp-sub">{t.stats.sub}</p>
        </div>
        <div className="lp-stats-grid">
          {t.stats.items.map((s, i) => (
            <div key={i} className="lp-stat">
              <div className="lp-stat-v">{s.v}</div>
              <div className="lp-stat-k">{s.k}</div>
              <div className="lp-stat-note">{s.note}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── COMMUNITIES ─────────────────────────────── */
function Communities({ t }) {
  return (
    <section className="lp-section lp-communities" id="communities">
      <div className="lp-container">
        <SectionHead eyebrow="Prime addresses" title={t.communities.title} sub={t.communities.sub} />
        <div className="lp-communities-grid">
          {t.communities.items.map((c, i) => (
            <a key={c.id} className={`lp-community lp-community-${i}`} href="#community">
              <div className="lp-community-img" style={{ backgroundImage: `url(${window.LP_DATA.communityCovers[c.id]})` }} />
              <div className="lp-community-shade" />
              <div className="lp-community-body">
                <div className="lp-community-kicker">{c.kicker}</div>
                <h3 className="lp-community-name">{c.name}</h3>
                <p className="lp-community-blurb">{c.blurb}</p>
                <div className="lp-community-cta">{t.communities.cta} <Icon.arrowSm /></div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────── COMMUNITY EDITORIAL (Palm) ──────────────────── */
function CommunityStory({ t }) {
  return (
    <section className="lp-section lp-story" id="community">
      <div className="lp-container lp-story-grid">
        <div className="lp-story-img">
          <img src="media/editorial-palm-district-one.webp" alt="Palm Jumeirah" />
          <div className="lp-story-badge">Palm Jumeirah · Crescent</div>
        </div>
        <div className="lp-story-text">
          <Eyebrow>{t.community.eyebrow}</Eyebrow>
          <h2 className="lp-h2 serif">{t.community.title}</h2>
          {t.community.body.map((p, i) => <p key={i} className="lp-body">{p}</p>)}
          <dl className="lp-facts">
            {t.community.facts.map((f, i) => (
              <div key={i} className="lp-fact">
                <dt>{f.k}</dt><dd>{f.v}</dd>
              </div>
            ))}
          </dl>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── LISTINGS GRID ───────────────────────────── */
function Listings({ t, showSampleBadges, onOpenViewing }) {
  const [filter, setFilter] = useState('all');
  const items = useMemo(() => {
    if (filter === 'all') return window.LP_DATA.listings;
    return window.LP_DATA.listings.filter(l => l.type === filter);
  }, [filter]);
  return (
    <section className="lp-section lp-listings" id="listings">
      <div className="lp-container">
        <div className="lp-listings-head">
          <div>
            <Eyebrow>Live inventory</Eyebrow>
            <h2 className="lp-h2 serif">{t.listings.title}</h2>
            <p className="lp-sub">{t.listings.sub}</p>
          </div>
          <div className="lp-feed-pill"><span className="lp-dot live" /> {t.listings.live}</div>
        </div>
        <div className="lp-listings-filters">
          {['all','sale','rent','offplan'].map(k => (
            <Pill key={k} active={filter === k} onClick={() => setFilter(k)}>{t.listings.filters[k]}</Pill>
          ))}
        </div>
        <div className="lp-listings-grid">
          {items.map(l => <ListingCard key={l.id} l={l} t={t} showSampleBadges={showSampleBadges} onOpenViewing={onOpenViewing} />)}
        </div>
        <div className="lp-listings-foot">
          {t.misc.sampleNotice}
        </div>
      </div>
    </section>
  );
}

function ListingCard({ l, t, showSampleBadges, onOpenViewing }) {
  return (
    <article className="lp-card">
      <div className="lp-card-img-wrap">
        <img src={l.img} alt="" className="lp-card-img" />
        <div className="lp-card-tag">{l.tag}</div>
        {showSampleBadges ? <div className="lp-card-sample">{t.listings.sampleBadge}</div> : null}
        <button className="lp-card-fav" aria-label="Save">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 21s-7-4.5-9.3-9.3C1 7.8 4 4 7.5 4c2 0 3.5 1 4.5 2.5C13 5 14.5 4 16.5 4 20 4 23 7.8 21.3 11.7 19 16.5 12 21 12 21z"/></svg>
        </button>
      </div>
      <div className="lp-card-body">
        <div className="lp-card-row top">
          <span className="lp-card-community">{l.communityLabel}</span>
          <span className="lp-card-ref">{l.ref}</span>
        </div>
        <h3 className="lp-card-title">{l.title}</h3>
        <div className="lp-card-meta">
          <span><Icon.bed /> {l.beds}</span>
          <span><Icon.bath /> {l.baths}</span>
          <span><Icon.area /> {l.sqft}</span>
        </div>
        <div className="lp-card-foot">
          <div className="lp-card-price">{l.price}</div>
          <div className="lp-card-actions">
            <button className="lp-card-act" onClick={onOpenViewing}>{t.listings.enquire} <Icon.arrowSm /></button>
            <a className="lp-card-act ghost" href="https://wa.me/971585097626" target="_blank" rel="noreferrer"><Icon.whatsapp /></a>
          </div>
        </div>
      </div>
    </article>
  );
}

/* ───────────────────────────── OFF-PLAN ──────────────────────────────── */
function OffPlan({ t, onBrochure }) {
  const op = window.LP_DATA.offplan;
  return (
    <section className="lp-section lp-offplan" id="offplan">
      <div className="lp-container">
        <div className="lp-offplan-card">
          <div className="lp-offplan-img">
            <img src={op.img} alt={op.name} />
            <div className="lp-offplan-img-shade" />
            <div className="lp-offplan-img-tag">Off-plan microsite preview</div>
          </div>
          <div className="lp-offplan-body">
            <Eyebrow light>{t.offplan.eyebrow}</Eyebrow>
            <h2 className="lp-h2 serif on-dark">{op.name}</h2>
            <p className="lp-offplan-sub">{op.sub}</p>
            <p className="lp-offplan-summary">{op.summary}</p>
            <dl className="lp-facts on-dark">
              {op.facts.map((f, i) => (
                <div key={i} className="lp-fact"><dt>{f.k}</dt><dd>{f.v}</dd></div>
              ))}
            </dl>
            <div className="lp-offplan-ctas">
              <Btn kind="primary" onClick={onBrochure}>{t.offplan.gate}</Btn>
              <Btn kind="ghost" light as="a" href="#listings">{t.offplan.cta} <Icon.arrowSm /></Btn>
            </div>
            <div className="lp-offplan-note">{t.offplan.gateNote}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── TEAM / AGENTS ───────────────────────────── */
function Team({ t }) {
  return (
    <section className="lp-section lp-team" id="team">
      <div className="lp-container">
        <SectionHead eyebrow={t.agents.eyebrow} title={t.agents.title} sub={t.agents.sub} />
        <div className="lp-team-grid">
          {window.LP_DATA.agents.map(a => (
            <article key={a.id} className="lp-agent">
              <div className="lp-agent-img-wrap">
                <img src={a.img} alt={a.name} className="lp-agent-img" />
              </div>
              <div className="lp-agent-body">
                <h3 className="lp-agent-name">{a.name}</h3>
                <div className="lp-agent-title">{a.title}</div>
                <div className="lp-agent-meta">
                  <span>{a.langs}</span>
                  <span className="lp-agent-brn">{a.brn}</span>
                </div>
                <div className="lp-agent-actions">
                  <button className="lp-agent-act">{t.agents.contact}</button>
                  <a className="lp-agent-act ghost" href="https://wa.me/971585097626" target="_blank" rel="noreferrer"><Icon.whatsapp /></a>
                </div>
              </div>
            </article>
          ))}
        </div>
        <div className="lp-team-foot">
          Headshots and titles confirmed against the live <code>/team</code> directory (2026-05). Individual publication remains permissioned.
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── EDITORIAL ───────────────────────────────── */
function Editorial({ t }) {
  return (
    <section className="lp-section lp-editorial">
      <div className="lp-container">
        <SectionHead eyebrow={t.editorial.eyebrow} title={t.editorial.title} sub={t.editorial.sub} />
        <div className="lp-editorial-grid">
          {window.LP_DATA.editorial.map((e, i) => (
            <a key={e.id} href="#" className={`lp-edit-card lp-edit-${i}`}>
              <div className="lp-edit-img" style={{ backgroundImage: `url(${e.img})` }} />
              <div className="lp-edit-body">
                <div className="lp-edit-tag">{e.tag} · {e.minutes} min</div>
                <h3 className="lp-edit-title">{e.title}</h3>
                <div className="lp-edit-read">{t.editorial.read} <Icon.arrowSm /></div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────── SELL / VALUATION ──────────────────────────── */
function Sell({ t, onOpenValuation }) {
  return (
    <section className="lp-section lp-sell" id="sell">
      <div className="lp-container lp-sell-inner">
        <div className="lp-sell-text">
          <Eyebrow light>{t.sell.eyebrow}</Eyebrow>
          <h2 className="lp-h2 serif on-dark">{t.sell.title}</h2>
          <p className="lp-sub on-dark">{t.sell.sub}</p>
        </div>
        <div className="lp-sell-cta">
          <Btn kind="primary" onClick={onOpenValuation}>{t.sell.cta} <Icon.arrowSm /></Btn>
          <a className="lp-sell-wa" href="https://wa.me/971585097626" target="_blank" rel="noreferrer">
            <Icon.whatsapp /> +971 58 509 7626
          </a>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────── CONTACT ─────────────────────────────── */
function Contact({ t }) {
  const [sent, setSent] = useState(false);
  const [interest, setInterest] = useState(t.contact.form.opts[0]);
  return (
    <section className="lp-section lp-contact" id="contact">
      <div className="lp-container lp-contact-grid">
        <div className="lp-contact-info">
          <Eyebrow>{t.contact.eyebrow}</Eyebrow>
          <h2 className="lp-h2 serif">{t.contact.title}</h2>
          <p className="lp-sub">{t.contact.sub}</p>
          <ul className="lp-contact-list">
            <li>
              <span className="k"><Icon.pin /> {t.contact.hq}</span>
              <span className="v">{t.contact.hqAddr}</span>
            </li>
            <li>
              <span className="k"><Icon.phone /> {t.contact.phone}</span>
              <a className="v lp-link" href="tel:+97145635900">{t.contact.phoneNum}</a>
            </li>
            <li>
              <span className="k"><Icon.whatsapp /> {t.contact.whatsapp}</span>
              <a className="v lp-link" href="https://wa.me/971585097626" target="_blank" rel="noreferrer">{t.contact.whatsappNum}</a>
            </li>
            <li>
              <span className="k">@ {t.contact.email}</span>
              <a className="v lp-link" href="mailto:hello@luxuryproperty.com">{t.contact.emailAddr}</a>
            </li>
            <li>
              <span className="k"><Icon.globe /> {t.contact.offices}</span>
              <span className="v">{t.contact.officesList}</span>
            </li>
          </ul>
        </div>

        <form className="lp-contact-form" onSubmit={e => { e.preventDefault(); setSent(true); }}>
          {sent ? (
            <div className="lp-form-success">
              <div className="lp-form-success-icon"><Icon.check /></div>
              <h3>{t.contact.form.sent}</h3>
              <button className="lp-link" onClick={() => setSent(false)}>Send another →</button>
            </div>
          ) : (
            <div className="lp-form-body">
              <div className="lp-field-row">
                <Field label={t.contact.form.name} />
                <Field label={t.contact.form.email} type="email" />
              </div>
              <Field label={t.contact.form.phone} type="tel" />
              <SelectField label={t.contact.form.interest} value={interest} onChange={setInterest} opts={t.contact.form.opts} />
              <Field label={t.contact.form.message} as="textarea" />
              <label className="lp-consent">
                <input type="checkbox" defaultChecked />
                <span>{t.contact.form.consent}</span>
              </label>
              <Btn kind="primary" type="submit" full>{t.contact.form.submit} <Icon.arrowSm /></Btn>
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

function Field({ label, type = 'text', as }) {
  if (as === 'textarea') {
    return (
      <label className="lp-field block">
        <span className="lp-field-lbl">{label}</span>
        <textarea rows="3" className="lp-field-inp" />
      </label>
    );
  }
  return (
    <label className="lp-field block">
      <span className="lp-field-lbl">{label}</span>
      <input type={type} className="lp-field-inp" />
    </label>
  );
}

function SelectField({ label, value, onChange, opts }) {
  return (
    <label className="lp-field block">
      <span className="lp-field-lbl">{label}</span>
      <select className="lp-field-inp" value={value} onChange={e => onChange(e.target.value)}>
        {opts.map(o => <option key={o}>{o}</option>)}
      </select>
    </label>
  );
}

/* ──────────────────────────────── FOOTER ─────────────────────────────── */
function Footer({ t }) {
  return (
    <footer className="lp-footer">
      <div className="lp-container">
        <div className="lp-footer-top">
          <div className="lp-footer-brand">
            <Logo light />
            <p className="lp-footer-tagline">{t.footer.tagline}</p>
            <div className="lp-footer-contact">
              <a className="lp-link on-dark" href="tel:+97145635900">+971 4 563 5900</a>
              <a className="lp-link on-dark" href="https://wa.me/971585097626" target="_blank" rel="noreferrer">+971 58 509 7626</a>
              <a className="lp-link on-dark" href="mailto:hello@luxuryproperty.com">hello@luxuryproperty.com</a>
            </div>
          </div>
          <FooterCol title={t.footer.sections.company} items={t.footer.company} />
          <FooterCol title={t.footer.sections.services} items={t.footer.services} />
          <FooterCol title={t.footer.sections.legal} items={t.footer.legal} />
        </div>
        <div className="lp-footer-bottom">
          <div className="lp-footer-compliance">{t.footer.compliance}</div>
          <div className="lp-footer-copy">{t.footer.copy}</div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div className="lp-footer-col">
      <div className="lp-footer-col-title">{title}</div>
      <ul>{items.map(i => <li key={i}><a href="#">{i}</a></li>)}</ul>
    </div>
  );
}

/* ────────────────────────── STICKY MOBILE BAR ────────────────────────── */
function MobileLeadBar({ t, onOpenViewing }) {
  return (
    <div className="lp-mlb">
      <a className="lp-mlb-btn" href="tel:+97145635900"><Icon.phone /> <span>Call</span></a>
      <a className="lp-mlb-btn" href="https://wa.me/971585097626" target="_blank" rel="noreferrer"><Icon.whatsapp /> <span>WhatsApp</span></a>
      <button className="lp-mlb-btn primary" onClick={onOpenViewing}>{t.nav.bookViewing}</button>
    </div>
  );
}

/* ──────────────────────────────── MODALS ─────────────────────────────── */
function Modal({ open, onClose, title, sub, children, wide }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="lp-modal-scrim" onClick={onClose}>
      <div className={`lp-modal ${wide ? 'wide' : ''}`} onClick={e => e.stopPropagation()}>
        <button className="lp-modal-close" onClick={onClose} aria-label="Close"><Icon.close /></button>
        <div className="lp-modal-head">
          <h3 className="lp-modal-title">{title}</h3>
          {sub ? <p className="lp-modal-sub">{sub}</p> : null}
        </div>
        <div className="lp-modal-body">{children}</div>
      </div>
    </div>
  );
}

function ViewingModal({ open, onClose, t }) {
  const [sent, setSent] = useState(false);
  return (
    <Modal open={open} onClose={() => { onClose(); setTimeout(() => setSent(false), 200); }} title={t.modal.viewing.title} sub={t.modal.viewing.sub}>
      {sent ? (
        <div className="lp-form-success">
          <div className="lp-form-success-icon"><Icon.check /></div>
          <h3>{t.modal.success}</h3>
        </div>
      ) : (
        <form className="lp-form" onSubmit={e => { e.preventDefault(); setSent(true); }}>
          <div className="lp-field-row">
            <Field label={t.contact.form.name} />
            <Field label={t.contact.form.phone} type="tel" />
          </div>
          <Field label={t.contact.form.email} type="email" />
          <Field label={t.modal.viewing.listing} />
          <div className="lp-field-row">
            <Field label={t.modal.viewing.date} type="date" />
            <Field label={t.modal.viewing.time} type="time" />
          </div>
          <Field label={t.modal.viewing.notes} as="textarea" />
          <Btn kind="primary" type="submit" full>{t.modal.viewing.submit}</Btn>
        </form>
      )}
    </Modal>
  );
}

function ValuationModal({ open, onClose, t }) {
  const [sent, setSent] = useState(false);
  const [timeline, setTimeline] = useState(t.modal.valuation.timelineOpts[0]);
  return (
    <Modal open={open} onClose={() => { onClose(); setTimeout(() => setSent(false), 200); }} title={t.modal.valuation.title} sub={t.modal.valuation.sub}>
      {sent ? (
        <div className="lp-form-success">
          <div className="lp-form-success-icon"><Icon.check /></div>
          <h3>{t.modal.success}</h3>
        </div>
      ) : (
        <form className="lp-form" onSubmit={e => { e.preventDefault(); setSent(true); }}>
          <div className="lp-field-row">
            <Field label={t.contact.form.name} />
            <Field label={t.contact.form.phone} type="tel" />
          </div>
          <Field label={t.contact.form.email} type="email" />
          <Field label={t.modal.valuation.address} />
          <div className="lp-field-row">
            <Field label={t.modal.valuation.beds} type="number" />
            <Field label={t.modal.valuation.sqft} type="number" />
          </div>
          <SelectField label={t.modal.valuation.timeline} value={timeline} onChange={setTimeline} opts={t.modal.valuation.timelineOpts} />
          <Btn kind="primary" type="submit" full>{t.modal.valuation.submit}</Btn>
        </form>
      )}
    </Modal>
  );
}

function BrochureModal({ open, onClose, t }) {
  const [sent, setSent] = useState(false);
  return (
    <Modal open={open} onClose={() => { onClose(); setTimeout(() => setSent(false), 200); }} title="Download the brochure" sub={t.offplan.gateNote}>
      {sent ? (
        <div className="lp-form-success">
          <div className="lp-form-success-icon"><Icon.check /></div>
          <h3>Brochure sent to your inbox.</h3>
          <p className="lp-sub">A private-client advisor will follow up within one business day.</p>
        </div>
      ) : (
        <form className="lp-form" onSubmit={e => { e.preventDefault(); setSent(true); }}>
          <div className="lp-field-row">
            <Field label={t.contact.form.name} />
            <Field label={t.contact.form.phone} type="tel" />
          </div>
          <Field label={t.contact.form.email} type="email" />
          <label className="lp-consent">
            <input type="checkbox" defaultChecked />
            <span>{t.contact.form.consent}</span>
          </label>
          <Btn kind="primary" type="submit" full>Email me the brochure</Btn>
        </form>
      )}
    </Modal>
  );
}

/* ────────────────────────────── APP ROOT ─────────────────────────────── */
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const locale = tweaks.locale;
  const t = window.LP_LOCALES[locale];

  useEffect(() => {
    document.documentElement.setAttribute('lang', locale);
    document.documentElement.setAttribute('dir', t.dir);
    document.documentElement.dataset.density = tweaks.density;
  }, [locale, t.dir, tweaks.density]);

  useEffect(() => { applyPalette(tweaks.palette); }, [tweaks.palette]);

  const [viewingOpen, setViewingOpen] = useState(false);
  const [valuationOpen, setValuationOpen] = useState(false);
  const [brochureOpen, setBrochureOpen] = useState(false);

  return (
    <div className="lp-app">
      <Nav t={t} locale={locale} onLocale={l => setTweak('locale', l)} onOpenViewing={() => setViewingOpen(true)} />
      <Hero t={t} onOpenViewing={() => setViewingOpen(true)} onOpenValuation={() => setValuationOpen(true)} heroVariant={tweaks.heroVariant} />
      <SearchBar t={t} />
      <Stats t={t} />
      <Communities t={t} />
      <CommunityStory t={t} />
      <Listings t={t} showSampleBadges={tweaks.showSampleBadges} onOpenViewing={() => setViewingOpen(true)} />
      <OffPlan t={t} onBrochure={() => setBrochureOpen(true)} />
      <Editorial t={t} />
      <Team t={t} />
      <Sell t={t} onOpenValuation={() => setValuationOpen(true)} />
      <Contact t={t} />
      <Footer t={t} />
      <MobileLeadBar t={t} onOpenViewing={() => setViewingOpen(true)} />

      <ViewingModal open={viewingOpen} onClose={() => setViewingOpen(false)} t={t} />
      <ValuationModal open={valuationOpen} onClose={() => setValuationOpen(false)} t={t} />
      <BrochureModal open={brochureOpen} onClose={() => setBrochureOpen(false)} t={t} />

      <TweaksPanel title={t.tweaks.title}>
        <TweakSection label="Locale">
          <TweakSelect tweakKey="locale" value={tweaks.locale} setTweak={setTweak} options={[
            { value: 'en', label: 'English' },
            { value: 'ar', label: 'العربية (RTL)' },
            { value: 'ru', label: 'Русский' },
            { value: 'zh', label: '中文' },
          ]} />
        </TweakSection>
        <TweakSection label="Palette">
          <TweakSelect tweakKey="palette" value={tweaks.palette} setTweak={setTweak} options={[
            { value: 'warm-stone', label: 'Warm stone (default)' },
            { value: 'graphite', label: 'Graphite' },
            { value: 'desert-bronze', label: 'Desert bronze' },
            { value: 'midnight-teal', label: 'Midnight teal' },
          ]} />
        </TweakSection>
        <TweakSection label="Hero image">
          <TweakSelect tweakKey="heroVariant" value={tweaks.heroVariant} setTweak={setTweak} options={[
            { value: 'palm', label: 'Palm Jumeirah (default)' },
            { value: 'skyline', label: 'Downtown skyline' },
            { value: 'villa', label: 'Coastal villa' },
            { value: 'about', label: 'Brand · about' },
          ]} />
        </TweakSection>
        <TweakSection label="Density">
          <TweakRadio tweakKey="density" value={tweaks.density} setTweak={setTweak} options={[
            { value: 'luxe', label: 'Luxe' },
            { value: 'compact', label: 'Compact' },
          ]} />
        </TweakSection>
        <TweakSection label="Sample badges on listings">
          <TweakToggle tweakKey="showSampleBadges" value={tweaks.showSampleBadges} setTweak={setTweak} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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