// Binghatti Flare — Lead-gen landing page (marketed by Treysta Real Estate Broker L.L.C)
// Broker campaign. Components exported to window.

const WA = '971582475234';   // Treysta WhatsApp lead line
const TEL = '+971585336375';  // Treysta call line
const AGENCY = 'Treysta Real Estate Broker L.L.C';
const AGENCY_SHORT = 'Treysta';
const ORN = '46270';         // Treysta RERA ORN

function waLink(msg) {
  return `https://wa.me/${WA}?text=${encodeURIComponent(msg || "Hi, I'd like the Binghatti Flare price list and floor plans please.")}`;
}

/* ============================================================
   LEAD INTEGRATION — Google Sheet + CRM
   ------------------------------------------------------------
   Paste your endpoints below. See INTEGRATION.md for the
   2-minute Apps Script setup (pre-filled to your sheet).
   - googleSheetUrl: the Apps Script Web App /exec URL.
   - crmWebhookUrl : any JSON POST endpoint (Zapier / Make /
     HubSpot / Bitrix24 / Salesforce Web-to-Lead proxy, etc.).
   Leave a value '' to skip it. The form still works if both
   are empty (lead is kept in localStorage as a backup).
   ============================================================ */
const LEAD_CONFIG = {
  sheetId: '11Spa1HyGKpSZYQsZGNuBNOCbep4NavHHAU8QYDz_9NQ',
  googleSheetUrl: 'https://script.google.com/macros/s/AKfycbzk1m4Dk5kOOWoGFk_oIonut0Ttd_VA_hRHqipalZl9ImXSZWJDgUrJeD764elSiFnlWg/exec',  // ← Apps Script Web App (Sheet + email)
  crmWebhookUrl: 'https://services.leadconnectorhq.com/hooks/mQIGQSfkaBURi1jHWkv7/webhook-trigger/092b1c3a-3dd7-4f7e-a35c-8019a2c0ed63', // LeadConnector / HighLevel inbound webhook
  source: 'Binghatti Flare LP',
};
try { window.__adConsent = localStorage.getItem('flare_consent') === 'accepted'; } catch (e) { window.__adConsent = false; }

function leadTracking() {
  try {
    const p = new URLSearchParams(location.search);
    const o = {};
    ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gclid', 'fbclid', 'msclkid']
      .forEach(k => { const v = p.get(k); if (v) o[k] = v; });
    return o;
  } catch (e) { return {}; }
}

async function submitLead(payload) {
  const body = {
    ...payload,
    source: LEAD_CONFIG.source,
    page: (typeof location !== 'undefined' ? location.href : ''),
    referrer: (typeof document !== 'undefined' ? document.referrer : '') || 'direct',
    submittedAt: new Date().toISOString(),
    ...leadTracking(),
  };
  // Local backup so a lead is never lost if the network fails.
  try {
    const k = 'flare_leads';
    const a = JSON.parse(localStorage.getItem(k) || '[]');
    a.push(body); localStorage.setItem(k, JSON.stringify(a));
  } catch (e) { /* ignore */ }

  const tasks = [];
  if (LEAD_CONFIG.googleSheetUrl) {
    // text/plain avoids the CORS preflight Apps Script can't answer.
    tasks.push(fetch(LEAD_CONFIG.googleSheetUrl, {
      method: 'POST', mode: 'no-cors',
      headers: { 'Content-Type': 'text/plain;charset=utf-8' },
      body: JSON.stringify(body),
    }));
  }
  if (LEAD_CONFIG.crmWebhookUrl) {
    // Real JSON (cors) so HighLevel/LeadConnector parses fields for workflow mapping.
    tasks.push(fetch(LEAD_CONFIG.crmWebhookUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    }).catch(function () {}));
  }
  try { await Promise.allSettled(tasks); } catch (e) { /* never block the UX */ }

  // Conversion events — only when the visitor has consented to analytics/advertising cookies.
  if (window.__adConsent) {
    try { if (window.gtag) window.gtag('event', 'generate_lead', { currency: 'AED', value: PRICE_AED, items: [{ item_name: body.unit || 'Unspecified' }] }); } catch (e) {}
    try { if (window.__trackLeadConversion) window.__trackLeadConversion(); } catch (e) {}
    try { if (window.fbq) window.fbq('track', 'Lead', { content_name: 'Binghatti Flare', value: PRICE_AED, currency: 'AED' }); } catch (e) {}
    try { if (window.dataLayer) window.dataLayer.push({ event: 'lead_submit', unit: body.unit || '' }); } catch (e) {}
  }
  return true;
}

/* ---------- currency ---------- */
const PRICE_AED = 800000; // starting price
const CURRENCIES = {
  AED: { sym: 'AED', rate: 1 },
  USD: { sym: '$', rate: 0.2723 },
  EUR: { sym: '€', rate: 0.2487 },
  INR: { sym: '₹', rate: 23.9 },
};
// Live FX: refresh rates (base AED) on load, keep the values above as fallback.
function loadLiveRates(onDone) {
  try {
    fetch('https://open.er-api.com/v6/latest/AED')
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(d => {
        const rt = d && d.rates;
        if (!rt) return;
        if (rt.USD) CURRENCIES.USD.rate = rt.USD;
        if (rt.EUR) CURRENCIES.EUR.rate = rt.EUR;
        if (rt.INR) CURRENCIES.INR.rate = rt.INR;
        if (typeof onDone === 'function') onDone();
      })
      .catch(() => {});
  } catch (e) {}
}
const CurrencyCtx = React.createContext(['AED', () => {}]);
function useCurrency() { return React.useContext(CurrencyCtx); }
function fmtK(aed, cur) {
  const c = CURRENCIES[cur] || CURRENCIES.AED;
  const v = aed * c.rate;
  if (cur === 'INR') return `₹${(v / 1e7).toFixed(1)} Cr`;
  const k = Math.round(v / 1000);
  return cur === 'AED' ? `AED ${k}K` : `${c.sym}${k}K`;
}
function fmtFull(aed, cur) {
  const c = CURRENCIES[cur] || CURRENCIES.AED;
  if (cur === 'INR') return `₹${(aed * c.rate / 1e7).toFixed(2)} Crore`;
  const v = Math.round((aed * c.rate) / 1000) * 1000;
  const n = v.toLocaleString('en-US');
  return cur === 'AED' ? `AED ${n}` : `${c.sym}${n}`;
}
function CurrencySwitcher() {
  const [cur, setCur] = useCurrency();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.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="lg-cur" ref={ref}>
      <button type="button" className="lg-cur-toggle" onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open}>
        {cur}<span className={`lg-cur-caret ${open ? 'lg-cur-caret-up' : ''}`}>▾</span>
      </button>
      {open && (
        <ul className="lg-cur-menu" role="listbox">
          {Object.keys(CURRENCIES).map(k => (
            <li key={k} role="option" aria-selected={cur === k}
                className={`lg-cur-opt ${cur === k ? 'lg-cur-opt-on' : ''}`}
                onClick={() => { setCur(k); setOpen(false); }}>{k}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

/* ---------- icons ---------- */
const IconWhatsApp = ({ s = 18 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17.47 14.38c-.3-.15-1.74-.86-2-.96-.27-.1-.46-.15-.65.15-.2.29-.75.96-.92 1.16-.17.2-.34.22-.63.07-.3-.15-1.25-.46-2.38-1.47-.88-.78-1.47-1.75-1.64-2.04-.17-.3-.02-.46.13-.6.13-.13.3-.34.45-.5.15-.18.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.65-1.57-.9-2.15-.24-.57-.48-.49-.65-.5l-.56-.01c-.2 0-.5.07-.77.36-.27.29-1.02 1-1.02 2.43s1.05 2.82 1.2 3.01c.15.2 2.06 3.15 5 4.42.7.3 1.24.48 1.67.62.7.22 1.34.19 1.84.12.56-.09 1.74-.71 1.98-1.4.24-.69.24-1.28.17-1.4-.07-.13-.27-.2-.56-.34M12.04 21.5h-.01a9.5 9.5 0 0 1-4.84-1.33l-.35-.2-3.6.94.96-3.5-.22-.36a9.46 9.46 0 0 1-1.45-5.04C2.58 6.74 6.82 2.5 12.05 2.5c2.53 0 4.9.99 6.69 2.78a9.43 9.43 0 0 1 2.77 6.69c0 5.23-4.25 9.48-9.47 9.53M20.5 3.5A11.46 11.46 0 0 0 12.04.5C5.7.5.56 5.64.56 11.96c0 2.02.53 4 1.53 5.74L.5 23.5l5.95-1.56a11.45 11.45 0 0 0 5.48 1.4h.01c6.33 0 11.48-5.15 11.48-11.47 0-3.07-1.2-5.95-3.37-8.12"/></svg>
);
const IconPhone = ({ s = 18 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><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.72c.13.96.36 1.9.7 2.81a2 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-.45c.9.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
);
const IconCheck = ({ s = 16 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>);
const IconArrow = ({ s = 16 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>);
const IconPlus = ({ s = 18 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>);
const IconLock = ({ s = 16 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="4.5" y="11" width="15" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>);
// amenity line icons
const IcBeach = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 18h18M3 21h18"/><path d="M12 18V9"/><path d="M12 9c-3 0-6 1.5-7 4 3-1 5-1 7 0 2-1 4-1 7 0-1-2.5-4-4-7-4z"/><circle cx="17" cy="6" r="2.5"/></svg>);
const IcPool = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M2 16c1.5 1.2 3 1.2 4.5 0S9.5 14.8 11 16s3 1.2 4.5 0S18.5 14.8 20 16M2 20c1.5 1.2 3 1.2 4.5 0S9.5 18.8 11 20s3 1.2 4.5 0S18.5 18.8 20 20"/><path d="M8 14V5a2 2 0 0 1 4 0M14 13V5"/></svg>);
const IcGym = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6.5 6.5 17.5 17.5M4 8l-1 1 12 12 1-1M16 4l-1 1 4 4 1-1M8 4 4 8M20 16l-4 4"/></svg>);
const IcPaddle = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="9.5" cy="9" r="6"/><path d="M9.5 6v6M6.5 9h6"/><path d="m13.5 13.5 6 6"/></svg>);
const IcKids = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="12" cy="5" r="2.2"/><path d="M12 7v6M7 10l5 1 5-1M9 20l3-7 3 7"/></svg>);
const IcLobby = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M4 21V6l8-3 8 3v15M4 21h16M9 21v-5h6v5M8 9h.01M12 9h.01M16 9h.01M8 12h.01M16 12h.01"/></svg>);
const IcRetail = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 8h14l-1 12H6L5 8z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>);
const IcView = ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M2 20h20M5 20V9l3-2 3 2v11M14 20V5l3-2 3 2v15M7 11h.01M7 14h.01M16 8h.01M16 11h.01"/></svg>);

/* ---------- chrome ---------- */
function TopBar({ onRegister }) {
  return (
    <header className="lg-top">
      <div className="lg-top-brand">
        <img className="lg-top-logo" src={RES('devLogo')} alt="Binghatti" />
        <span className="lg-top-div" />
        <img className="lg-top-flare" src={RES('logo')} alt="Flare" />
      </div>
      <div className="lg-top-actions">
        {window.LangSwitcher && React.createElement(window.LangSwitcher)}
        <CurrencySwitcher />
        <button className="lg-top-cta" onClick={onRegister}>Register Interest</button>
      </div>
    </header>
  );
}

function UrgencyBar({ show }) {
  if (!show) return null;
  return (<div className="lg-urgency"><span className="lg-dot" /> Launch pricing now live · limited release</div>);
}

function Chip({ children }) { return <div className="lg-chip"><IconCheck s={14} />{children}</div>; }

function Hero({ t, scrollToForm, onRegister }) {
  const [cur] = useCurrency();
  return (
    <section className="lg-hero">
      <div className="lg-hero-blur" style={{ backgroundImage: `url('${t.heroImage}')` }} />
      <img className="lg-hero-img lg-hero-img-d" src={t.heroImage} alt="Binghatti Flare twin towers in Jumeirah Village Triangle, Dubai" />
      <img className="lg-hero-img lg-hero-img-m" src={RES('heroMobile')} alt="Binghatti Flare twin towers" />
      <TopBar onRegister={onRegister || scrollToForm} />
      <div className="lg-hero-overlay">
        <img className="lg-hero-flare" src={RES('logo')} alt="Binghatti Flare" />
        <div className="lg-hero-copy">
          <div className="lg-eyebrow">Jumeirah Village Triangle · Dubai</div>
          <h1 className="lg-hero-title">{t.headline}</h1>
          <p className="lg-hero-sub">A landmark collection of residences, crafted by Binghatti on an easy <strong>70/30 plan</strong>.</p>
          <div className="lg-herostats">
            <div><b>From {fmtK(PRICE_AED, cur)}*</b><span>Starting price</span></div>
            <div><b>Studio to 4 BR</b><span>Residences &amp; retail</span></div>
            <div><b>Q2 2027</b><span>Handover</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function InfoModal({ title, children, onClose }) {
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return (
    <div className="lg-modal-overlay" onClick={onClose}>
      <div className="lg-modal lg-disc-modal" onClick={e => e.stopPropagation()}>
        <button className="lg-modal-close" onClick={onClose} aria-label="Close">×</button>
        <div className="lg-disc-h">{title}</div>
        {children}
      </div>
    </div>
  );
}

const LEGAL = {
  disclaimer: (
    <>
      <p>{AGENCY} is a RERA registered property broker (ORN {ORN}) marketing Binghatti Flare in Jumeirah Village Triangle, Dubai, as an authorised channel partner. We are not the developer. Binghatti and Binghatti Flare are trademarks of Binghatti Developers.</p>
      <p>Prices, payment plans, availability, sizes, imagery and handover dates are indicative, subject to change, and do not form part of any offer or contract. Renders are artist impressions.</p>
      <p>© 2026 {AGENCY}. All rights reserved.</p>
    </>
  ),
  privacy: (
    <>
      <p>At Treysta, privacy of visitors of our website is top priority. This Privacy Policy gives a detailed view into what types of information is collected from our visitors and how we use the same. It only applies to our online activities and does not extend to any data collected offline or through other channels.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Consent.</strong> By using our website, you hereby consent to our Privacy Policy and agree to its terms.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>What we collect.</strong> We collect and record the personal information you share with us when you register. This information includes your name, company name, address, email id, mobile number and other such information. If you contact us directly, we may also receive additional information such as the content of your message and any attachments you choose to provide.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>How we use your information.</strong> To operate and maintain our website; understand and analyse how you use it; improve and personalise our customer approach; develop new products, services and features; ensure customer safety and prevent fraud; communicate with you directly or through a partner; enable good customer service; and undertake marketing and promotional initiatives.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Log files.</strong> Like all hosting companies, we log visitors. These files collect Internet Protocol (IP) addresses, browser type, Internet Service Provider (ISP), referring/exit pages, time spent on the website, number of clicks, and date and time stamp. This information is not linked to any personally identifiable information.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Advertising partners.</strong> Some advertisers on our site may use cookies and web beacons. Each advertising partner has its own privacy policy for how it uses your data. Treysta has no access to or control over the cookies used by third-party advertisers. We advise you to review their respective privacy policies for details on how they use your information and how to opt out.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Children's information.</strong> Treysta does not knowingly collect any personal information from minors. We advise parents and guardians to monitor children's activity online. If you believe your child has shared this type of information on our website, please contact us and we will do our best to promptly remove it.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Your GDPR rights.</strong> Every user is entitled to: the right to access your personal data; the right to rectification; the right to erase, under certain conditions; the right to restrict processing, under certain conditions; and the right to data portability. Any request you make will be adhered to, and Treysta may take up to one month to respond.</p>
      <p><strong style={{ color: 'var(--fg-1)' }}>Contact.</strong> If you need more information about our Privacy Policy, or wish to exercise any of your rights, write to us at <a href="mailto:info@treysta.ae" style={{ color: 'var(--flare-gold)' }}>info@treysta.ae</a>.</p>
    </>
  ),
  cookies: (
    <>
      <p>Treysta uses cookies and web beacons on its website. These cookies collect and store information that is used to optimise visitor experience. This includes visitors' likes and preferences, pages they visited, the time they spent, the browser they used and other information. This helps Treysta customise and personalise its web page content to provide a better experience.</p>
      <p>Some of the advertisers on our site may use cookies and web beacons. Third-party ad servers and ad networks also use technologies such as cookies, web beacons or JavaScript in their advertisements and links. These technologies are used to measure the effectiveness of advertising campaigns and to customise ad content for relevancy.</p>
      <p>You can choose to disable cookies through your own individual browser. You can learn about cookie management specific to your web browser on its respective website.</p>
    </>
  ),
};

function DisclaimerModal({ onClose }) {
  return <InfoModal title="Disclaimer" onClose={onClose}>{LEGAL.disclaimer}</InfoModal>;
}

function FormModal({ t, onClose }) {
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return (
    <div className="lg-modal-overlay">
      <div className="lg-modal" onClick={e => e.stopPropagation()}>
        <button className="lg-modal-close" onClick={onClose} aria-label="Close">×</button>
        <LeadForm t={t} />
      </div>
    </div>
  );
}

const COUNTRIES = [
  ["AE", "United Arab Emirates", "+971"],
  ["SA", "Saudi Arabia", "+966"],
  ["QA", "Qatar", "+974"],
  ["BH", "Bahrain", "+973"],
  ["OM", "Oman", "+968"],
  ["KW", "Kuwait", "+965"],
  ["IN", "India", "+91"],
  ["GB", "United Kingdom", "+44"],
  ["US", "United States", "+1"],
  ["AF", "Afghanistan", "+93"],
  ["AL", "Albania", "+355"],
  ["DZ", "Algeria", "+213"],
  ["AD", "Andorra", "+376"],
  ["AO", "Angola", "+244"],
  ["AG", "Antigua & Barbuda", "+1"],
  ["AR", "Argentina", "+54"],
  ["AM", "Armenia", "+374"],
  ["AU", "Australia", "+61"],
  ["AT", "Austria", "+43"],
  ["AZ", "Azerbaijan", "+994"],
  ["BS", "Bahamas", "+1"],
  ["BD", "Bangladesh", "+880"],
  ["BB", "Barbados", "+1"],
  ["BY", "Belarus", "+375"],
  ["BE", "Belgium", "+32"],
  ["BZ", "Belize", "+501"],
  ["BJ", "Benin", "+229"],
  ["BT", "Bhutan", "+975"],
  ["BO", "Bolivia", "+591"],
  ["BA", "Bosnia & Herzegovina", "+387"],
  ["BW", "Botswana", "+267"],
  ["BR", "Brazil", "+55"],
  ["BN", "Brunei", "+673"],
  ["BG", "Bulgaria", "+359"],
  ["BF", "Burkina Faso", "+226"],
  ["BI", "Burundi", "+257"],
  ["KH", "Cambodia", "+855"],
  ["CM", "Cameroon", "+237"],
  ["CA", "Canada", "+1"],
  ["CV", "Cape Verde", "+238"],
  ["CF", "Central African Republic", "+236"],
  ["TD", "Chad", "+235"],
  ["CL", "Chile", "+56"],
  ["CN", "China", "+86"],
  ["CO", "Colombia", "+57"],
  ["KM", "Comoros", "+269"],
  ["CG", "Congo", "+242"],
  ["CD", "Congo (DRC)", "+243"],
  ["CR", "Costa Rica", "+506"],
  ["CI", "Côte d'Ivoire", "+225"],
  ["HR", "Croatia", "+385"],
  ["CU", "Cuba", "+53"],
  ["CY", "Cyprus", "+357"],
  ["CZ", "Czechia", "+420"],
  ["DK", "Denmark", "+45"],
  ["DJ", "Djibouti", "+253"],
  ["DM", "Dominica", "+1"],
  ["DO", "Dominican Republic", "+1"],
  ["EC", "Ecuador", "+593"],
  ["EG", "Egypt", "+20"],
  ["SV", "El Salvador", "+503"],
  ["GQ", "Equatorial Guinea", "+240"],
  ["ER", "Eritrea", "+291"],
  ["EE", "Estonia", "+372"],
  ["SZ", "Eswatini", "+268"],
  ["ET", "Ethiopia", "+251"],
  ["FJ", "Fiji", "+679"],
  ["FI", "Finland", "+358"],
  ["FR", "France", "+33"],
  ["GA", "Gabon", "+241"],
  ["GM", "Gambia", "+220"],
  ["GE", "Georgia", "+995"],
  ["DE", "Germany", "+49"],
  ["GH", "Ghana", "+233"],
  ["GR", "Greece", "+30"],
  ["GD", "Grenada", "+1"],
  ["GT", "Guatemala", "+502"],
  ["GN", "Guinea", "+224"],
  ["GW", "Guinea-Bissau", "+245"],
  ["GY", "Guyana", "+592"],
  ["HT", "Haiti", "+509"],
  ["HN", "Honduras", "+504"],
  ["HK", "Hong Kong", "+852"],
  ["HU", "Hungary", "+36"],
  ["IS", "Iceland", "+354"],
  ["ID", "Indonesia", "+62"],
  ["IR", "Iran", "+98"],
  ["IQ", "Iraq", "+964"],
  ["IE", "Ireland", "+353"],
  ["IL", "Israel", "+972"],
  ["IT", "Italy", "+39"],
  ["JM", "Jamaica", "+1"],
  ["JP", "Japan", "+81"],
  ["JO", "Jordan", "+962"],
  ["KZ", "Kazakhstan", "+7"],
  ["KE", "Kenya", "+254"],
  ["KI", "Kiribati", "+686"],
  ["KG", "Kyrgyzstan", "+996"],
  ["LA", "Laos", "+856"],
  ["LV", "Latvia", "+371"],
  ["LB", "Lebanon", "+961"],
  ["LS", "Lesotho", "+266"],
  ["LR", "Liberia", "+231"],
  ["LY", "Libya", "+218"],
  ["LI", "Liechtenstein", "+423"],
  ["LT", "Lithuania", "+370"],
  ["LU", "Luxembourg", "+352"],
  ["MO", "Macau", "+853"],
  ["MG", "Madagascar", "+261"],
  ["MW", "Malawi", "+265"],
  ["MY", "Malaysia", "+60"],
  ["MV", "Maldives", "+960"],
  ["ML", "Mali", "+223"],
  ["MT", "Malta", "+356"],
  ["MH", "Marshall Islands", "+692"],
  ["MR", "Mauritania", "+222"],
  ["MU", "Mauritius", "+230"],
  ["MX", "Mexico", "+52"],
  ["FM", "Micronesia", "+691"],
  ["MD", "Moldova", "+373"],
  ["MC", "Monaco", "+377"],
  ["MN", "Mongolia", "+976"],
  ["ME", "Montenegro", "+382"],
  ["MA", "Morocco", "+212"],
  ["MZ", "Mozambique", "+258"],
  ["MM", "Myanmar", "+95"],
  ["NA", "Namibia", "+264"],
  ["NR", "Nauru", "+674"],
  ["NP", "Nepal", "+977"],
  ["NL", "Netherlands", "+31"],
  ["NZ", "New Zealand", "+64"],
  ["NI", "Nicaragua", "+505"],
  ["NE", "Niger", "+227"],
  ["NG", "Nigeria", "+234"],
  ["KP", "North Korea", "+850"],
  ["MK", "North Macedonia", "+389"],
  ["NO", "Norway", "+47"],
  ["PK", "Pakistan", "+92"],
  ["PW", "Palau", "+680"],
  ["PS", "Palestine", "+970"],
  ["PA", "Panama", "+507"],
  ["PG", "Papua New Guinea", "+675"],
  ["PY", "Paraguay", "+595"],
  ["PE", "Peru", "+51"],
  ["PH", "Philippines", "+63"],
  ["PL", "Poland", "+48"],
  ["PT", "Portugal", "+351"],
  ["RO", "Romania", "+40"],
  ["RU", "Russia", "+7"],
  ["RW", "Rwanda", "+250"],
  ["KN", "Saint Kitts & Nevis", "+1"],
  ["LC", "Saint Lucia", "+1"],
  ["VC", "Saint Vincent", "+1"],
  ["WS", "Samoa", "+685"],
  ["SM", "San Marino", "+378"],
  ["ST", "São Tomé & Príncipe", "+239"],
  ["SN", "Senegal", "+221"],
  ["RS", "Serbia", "+381"],
  ["SC", "Seychelles", "+248"],
  ["SL", "Sierra Leone", "+232"],
  ["SG", "Singapore", "+65"],
  ["SK", "Slovakia", "+421"],
  ["SI", "Slovenia", "+386"],
  ["SB", "Solomon Islands", "+677"],
  ["SO", "Somalia", "+252"],
  ["ZA", "South Africa", "+27"],
  ["KR", "South Korea", "+82"],
  ["SS", "South Sudan", "+211"],
  ["ES", "Spain", "+34"],
  ["LK", "Sri Lanka", "+94"],
  ["SD", "Sudan", "+249"],
  ["SR", "Suriname", "+597"],
  ["SE", "Sweden", "+46"],
  ["CH", "Switzerland", "+41"],
  ["SY", "Syria", "+963"],
  ["TW", "Taiwan", "+886"],
  ["TJ", "Tajikistan", "+992"],
  ["TZ", "Tanzania", "+255"],
  ["TH", "Thailand", "+66"],
  ["TL", "Timor-Leste", "+670"],
  ["TG", "Togo", "+228"],
  ["TO", "Tonga", "+676"],
  ["TT", "Trinidad & Tobago", "+1"],
  ["TN", "Tunisia", "+216"],
  ["TR", "Türkiye", "+90"],
  ["TM", "Turkmenistan", "+993"],
  ["TV", "Tuvalu", "+688"],
  ["UG", "Uganda", "+256"],
  ["UA", "Ukraine", "+380"],
  ["UY", "Uruguay", "+598"],
  ["UZ", "Uzbekistan", "+998"],
  ["VU", "Vanuatu", "+678"],
  ["VE", "Venezuela", "+58"],
  ["VN", "Vietnam", "+84"],
  ["YE", "Yemen", "+967"],
  ["ZM", "Zambia", "+260"],
  ["ZW", "Zimbabwe", "+263"],
];
const UNIT_OPTIONS = ['Studio', '1 Bedroom', '2 Bedroom', '3 Bedroom', '4 Bedroom'];

function CountrySelect({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onDoc = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  React.useEffect(() => { if (!open) setQ(''); }, [open]);
  const sel = COUNTRIES.find(c => c[2] === value) || COUNTRIES[0];
  const ql = q.trim().toLowerCase();
  const list = ql ? COUNTRIES.filter(c => c[1].toLowerCase().includes(ql) || c[2].includes(ql) || c[0].toLowerCase() === ql) : COUNTRIES;
  return (
    <div className="lg-cc" ref={ref}>
      <button type="button" className="lg-cc-btn" onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open}>
        <span className="lg-cc-iso">{sel[0]}</span>
        <span className="lg-cc-dial">{sel[2]}</span>
        <span className={`lg-cc-caret ${open ? 'lg-cc-caret-up' : ''}`}>▾</span>
      </button>
      {open && (
        <div className="lg-cc-pop">
          <input className="lg-cc-search" autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Search country" />
          <ul className="lg-cc-list" role="listbox">
            {list.map(c => (
              <li key={c[0]} role="option" aria-selected={c[2] === value}
                  className={`lg-cc-item ${c[2] === value ? 'lg-cc-item-on' : ''}`}
                  onClick={() => { onChange(c[2]); setOpen(false); }}>
                <span className="lg-cc-item-iso">{c[0]}</span>
                <span className="lg-cc-item-name">{c[1]}</span>
                <span className="lg-cc-item-dial">{c[2]}</span>
              </li>
            ))}
            {list.length === 0 && <li className="lg-cc-empty">No match</li>}
          </ul>
        </div>
      )}
    </div>
  );
}

function LeadForm({ t, compact }) {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [vals, setVals] = React.useState({ name: '', cc: '+971', phone: '', email: '', unit: '', consent: true });
  const [err, setErr] = React.useState({});
  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const er = {};
    const digits = vals.phone.replace(/\D/g, '');
    if (vals.name.trim().length < 2 || /\d/.test(vals.name)) er.name = 1;
    if (/[A-Za-z]/.test(vals.phone) || digits.length < 7 || digits.length > 15) er.phone = 1;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(vals.email.trim())) er.email = 1;
    if (!vals.consent) er.consent = 1;
    setErr(er);
    if (Object.keys(er).length > 0) return;
    setSending(true);
    // Dispatch to Sheet/email + CRM, but don't make the user wait on slow
    // endpoints (Apps Script can take several seconds; the requests still
    // complete in the background and the lead is backed up locally).
    await Promise.race([
      submitLead({
        name: vals.name.trim(),
        phone: (vals.cc + ' ' + vals.phone).replace(/\s+/g, ' ').trim(),
        countryCode: vals.cc,
        email: vals.email.trim(),
        unit: vals.unit || 'Not specified',
        consent: vals.consent ? 'Yes' : 'No',
      }),
      new Promise(r => setTimeout(r, 1200)),
    ]);
    setSending(false);
    setSent(true);
  };
  const setField = (k, v) => { setVals(p => ({ ...p, [k]: v })); setErr(p => { if (!p[k]) return p; const n = { ...p }; delete n[k]; return n; }); };
  const MSG = { name: 'Please enter a valid name', phone: 'Enter a valid mobile number', email: 'Enter a valid email address', consent: 'Please tick the box to continue' };
  if (sent) return <ThankYou name={vals.name} />;
  return (
    <form className={`lg-form ${compact ? 'lg-form-compact' : ''}`} onSubmit={submit} noValidate>
      <div className="lg-form-head">
        <div className="lg-form-title">Get the price list &amp; floor plans</div>
        <div className="lg-form-sub">Instant reply on WhatsApp. No spam.</div>
      </div>
      <label className={`lg-field ${err.name ? 'lg-field-err' : ''}`}>
        <span>Full name</span>
        <input value={vals.name} onChange={e => setField('name', e.target.value.replace(/[0-9]/g, ''))} placeholder="Your name" autoComplete="name" />
        {err.name && <span className="lg-err-msg">{MSG.name}</span>}
      </label>
      <label className={`lg-field ${err.phone ? 'lg-field-err' : ''}`}>
        <span>Mobile number</span>
        <div className="lg-phone">
          <CountrySelect value={vals.cc} onChange={cc => setVals(p => ({ ...p, cc }))} />
          <input type="tel" value={vals.phone} onChange={e => setField('phone', e.target.value)} placeholder="50 000 0000" autoComplete="tel" />
        </div>
        {err.phone && <span className="lg-err-msg">{MSG.phone}</span>}
      </label>
      <label className={`lg-field ${err.email ? 'lg-field-err' : ''}`}>
        <span>Email address</span>
        <input type="email" value={vals.email} onChange={e => setField('email', e.target.value)} placeholder="you@email.com" autoComplete="email" />
        {err.email && <span className="lg-err-msg">{MSG.email}</span>}
      </label>
      <label className="lg-field">
        <span>Interested in</span>
        <select className="lg-select" value={vals.unit} onChange={e => setVals(p => ({ ...p, unit: e.target.value }))}>
          <option value="">Select a residence</option>
          {UNIT_OPTIONS.map(u => <option key={u} value={u}>{u}</option>)}
        </select>
      </label>
      <button className="lg-submit" type="submit" disabled={sending} style={sending ? { opacity: .7, cursor: 'wait' } : null}>{sending ? 'Sending…' : <>Send me the details <IconArrow s={16} /></>}</button>
      <label className={`lg-consent ${err.consent ? 'lg-consent-err' : ''}`}>
        <input type="checkbox" checked={vals.consent} onChange={e => setField('consent', e.target.checked)} />
        <span>I agree to be contacted about this project.</span>
      </label>
      {err.consent && <span className="lg-err-msg">{MSG.consent}</span>}
    </form>
  );
}

function ThankYou({ name }) {
  return (
    <div className="lg-thanks">
      <div className="lg-thanks-mark"><IconCheck s={30} /></div>
      <div className="lg-thanks-t">Thank you{name ? `, ${name.split(' ')[0]}` : ''}.</div>
      <p>We'll send the price list and floor plans on WhatsApp shortly.</p>
      <a className="lg-wa-btn" href={waLink()} target="_blank" rel="noopener"><IconWhatsApp s={18} /> Chat now on WhatsApp</a>
    </div>
  );
}

function BrokerTrust() {
  const items = ['Official channel partner', 'Direct developer pricing', 'RERA registered broker', '1,000+ buyers assisted'];
  return (
    <section className="lg-bt">
      {items.map((t, i) => <div className="lg-bt-i" key={i}><span className="lg-bt-dot" />{t}</div>)}
    </section>
  );
}

function WhyDubai() {
  const items = [
    ['0%', 'No annual property, income or capital-gains tax.'],
    ['Up to 10%', 'Gross rental yields, among the world’s strongest.'],
    ['10 Yr', 'Golden Visa on homes of AED 2M+.'],
    ['100%', 'Freehold for all nationalities. RERA escrow protected.'],
    ['Top 10', 'Ranked among the world’s safest cities.'],
  ];
  return (
    <section className="lg-section lg-facts-sec" id="why-dubai">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Why Dubai</div>
        <h2 className="lg-h2">Dubai, in Five Numbers.</h2>
      </div>
      <div className="lg-facts lg-why-grid">
        {items.map(([n, l], i) => (
          <div className="lg-fact" key={i}><b>{n}</b><span>{l}</span></div>
        ))}
      </div>
      <p className="lg-fineprint">Market figures: Dubai Land Department / published portal data, 2025. Indicative only, not financial advice.</p>
    </section>
  );
}

function Facts() {
  const data = [
    ['2', 'Iconic towers · 40 & 34 floors'],
    ['1,378', 'Residences + 79 retail units'],
    ['70 / 30', 'Easy payment plan*'],
    ['JVT', 'Minutes to Marina & Downtown'],
  ];
  return (
    <section className="lg-section lg-facts-sec">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Why Flare</div>
        <h2 className="lg-h2">A Community That Matters.</h2>
      </div>
      <div className="lg-facts">
        {data.map(([n, l], i) => (
          <div className="lg-fact" key={i}><b>{n}</b><span>{l}</span></div>
        ))}
      </div>
    </section>
  );
}

function UnitMix({ scrollToForm }) {
  const [cur] = useCurrency();
  const units = [
    { k: 'Studio', px: `From ${fmtK(PRICE_AED, cur)}*`, mt: 'Investor favourite', img: 'unitStudio' },
    { k: '1 Bedroom', px: 'Price on request', mt: 'Balcony · skyline view', img: 'unit1' },
    { k: '2 Bedroom', px: 'Price on request', mt: 'Family ready', img: 'unit2' },
    { k: '3 & 4 Bedroom', px: 'Price on request', mt: 'Sky terrace · pool', img: 'unit3' },
  ];
  return (
    <section className="lg-section" id="residences">
      <div className="lg-sec-head">
        <div className="lg-eyebrow">Choose your residence</div>
        <h2 className="lg-h2 lg-light">From Studios to Four Bedroom Sky Homes</h2>
      </div>
      <div className="lg-units">
        {units.map((u, i) => (
          <button className="lg-unit" key={i} onClick={scrollToForm}>
            <div className="lg-unit-img" style={{ backgroundImage: `url('${RES(u.img)}')` }} />
            <div className="lg-unit-body">
              <div className="lg-unit-k">{u.k}</div>
              <div className="lg-unit-px">{u.px}</div>
              <div className="lg-unit-mt">{u.mt}</div>
              <span className="lg-unit-cta">Enquire <IconArrow s={14} /></span>
            </div>
          </button>
        ))}
      </div>
      <p className="lg-fineprint">* Indicative starting prices. Confirm availability on enquiry.</p>
    </section>
  );
}

function Amenities() {
  const a = [
    [<IcBeach />, 'Artificial beach', 'Sand & pool deck'],
    [<IcPool />, 'Private sky pools', 'Sky-terrace homes'],
    [<IcGym />, 'Gym & running lane', 'Wellness floor'],
    [<IcPaddle />, 'Paddle court', 'Active living'],
    [<IcKids />, 'Kids wet & dry play', 'Family zones'],
    [<IcLobby />, 'Luxury lobby', 'Signature arrival'],
    [<IcRetail />, 'Retail & shopping', '79 units below'],
    [<IcView />, 'Skyline views', 'Burj on the horizon'],
  ];
  return (
    <section className="lg-section" id="amenities">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Life at Flare</div>
        <h2 className="lg-h2">Resort Amenities at Your Door.</h2>
      </div>
      <div className="lg-amc-grid">
        {a.map(([ic, t, s], i) => (
          <div className="lg-amc" key={i}>
            <span className="lg-amc-ic">{ic}</span>
            <div className="lg-amc-t">{t}</div>
            <div className="lg-amc-s">{s}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function FloorPlans({ scrollToForm }) {
  const plans = [
    { k: 'Studio', f: 'fpStudio' },
    { k: '1 Bedroom', f: 'fp1' },
    { k: '2 Bedroom', f: 'fp2' },
    { k: '3 Bedroom', f: 'fp3' },
    { k: '4 Bedroom', f: 'fp4' },
  ];
  const [i, setI] = React.useState(0);
  return (
    <section className="lg-section lg-fp" id="floorplans">
      <div className="lg-sec-head">
        <div className="lg-eyebrow">Layouts</div>
        <h2 className="lg-h2 lg-light">Floor Plans</h2>
      </div>
      <div className="lg-fp-tabs">
        {plans.map((p, n) => (
          <button key={p.k} className={`lg-fp-tab ${n === i ? 'lg-fp-tab-on' : ''}`} onClick={() => setI(n)}>{p.k}</button>
        ))}
      </div>
      <div className="lg-fp-view">
        <div className="lg-fp-frame">
          <div className="lg-fp-plan" style={{ backgroundImage: `url('${RES(plans[i].f)}')` }} />
          <button className="lg-fp-gate" onClick={scrollToForm} aria-label="Unlock floor plan">
            <span className="lg-fp-lock"><IconLock s={20} /></span>
            <span className="lg-fp-gate-t">Floor plans available on request</span>
            <span className="lg-fp-gate-cta">Tap to unlock <IconArrow s={14} /></span>
          </button>
        </div>
        <div className="lg-fp-side">
          <div className="lg-fp-unit">{plans[i].k}</div>
          <p className="lg-fp-copy">Indicative layout. Request the full floor plan pack with sizes and the current price list.</p>
          <button className="lg-submit lg-submit-inline" onClick={scrollToForm}>Register Interest</button>
        </div>
      </div>
    </section>
  );
}

function GalleryStrip({ onOpen }) {
  const imgs = ['gExtBurj', 'unit1', 'gPodiumNight', 'gExtPoolDay', 'unitStudio', 'gExtSunset', 'unit2', 'gAmDeck', 'gExtFog', 'unit3', 'gExtDay', 'gAmAerial', 'lobby', 'gFooterSunset', 'int4'];
  return (
    <section className="lg-section" id="gallery">
      <div className="lg-sec-head">
        <div className="lg-eyebrow">See it</div>
        <h2 className="lg-h2 lg-light">The Gallery</h2>
      </div>
      <div className="lg-gallery">
        {imgs.slice(0, 5).map((g, i) => (
          <button type="button" className={`lg-gal lg-gal-${i}`} key={g} onClick={() => onOpen(imgs, i)} style={{ backgroundImage: `url('${RES(g)}')` }} aria-label="View image">
            <span className="lg-gal-zoom"><IconPlus s={18} /></span>
          </button>
        ))}
      </div>
      <div style={{ textAlign: 'center' }}>
        <button className="lg-submit lg-submit-inline" onClick={() => onOpen(imgs, 0)}>View All Photos</button>
      </div>
    </section>
  );
}

function Lightbox({ imgs, index, onClose, onNav }) {
  React.useEffect(() => {
    const onKey = e => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onNav(1);
      if (e.key === 'ArrowLeft') onNav(-1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, onNav]);
  return (
    <div className="lg-lb" onClick={onClose}>
      <button className="lg-lb-close" onClick={onClose} aria-label="Close">×</button>
      <button className="lg-lb-nav lg-lb-prev" onClick={e => { e.stopPropagation(); onNav(-1); }} aria-label="Previous">‹</button>
      <img className="lg-lb-img" src={RES(imgs[index])} onClick={e => e.stopPropagation()} alt="Binghatti Flare" />
      <button className="lg-lb-nav lg-lb-next" onClick={e => { e.stopPropagation(); onNav(1); }} aria-label="Next">›</button>
      <div className="lg-lb-count">{index + 1} / {imgs.length}</div>
    </div>
  );
}

function Tour360() {
  return (
    <section className="lg-section" id="tour360">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Step inside</div>
        <h2 className="lg-h2">A 360° Walk Through Flare.</h2>
      </div>
      <div className="lg-tour-frame">
        <iframe
          className="lg-tour-iframe"
          src="https://kuula.co/share/collection/71hd6?logo=-1&info=0&fs=1&vr=0&sd=1&gyro=1&autop=0&thumbs=1&keys=0"
          allow="fullscreen; xr-spatial-tracking; gyroscope; accelerometer"
          allowFullScreen
          title="Binghatti Flare 360 virtual tour"
          loading="lazy"
        />
      </div>
    </section>
  );
}

function Location() {
  const conn = [
    ['Dubai Marina & Harbour', '10 min'],
    ['Mall of the Emirates', '10 min'],
    ['Expo City Dubai', '10 min'],
    ['Palm Jumeirah', '15 min'],
    ['Downtown & Burj Khalifa', '20 min'],
    ['Al Maktoum Intl. Airport', '22 min'],
  ];
  return (
    <section className="lg-section lg-loc" id="location">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Where it is</div>
        <h2 className="lg-h2">JVT. Central and Connected.</h2>
      </div>
      <div className="lg-loc-grid">
        <div className="lg-map" style={{ backgroundImage: `url('${RES('finalBg')}')`, backgroundSize: 'cover', backgroundPosition: 'center' }} role="img" aria-label="Binghatti Flare, Jumeirah Village Triangle, Dubai"></div>
        <ul className="lg-conn">
          {conn.map(([p, tm], i) => <li key={i}><span>{p}</span><b>{tm}</b></li>)}
        </ul>
      </div>
      <p className="lg-fineprint">Drive times indicative.</p>
    </section>
  );
}

function PaymentPlan({ scrollToForm }) {
  const steps = [
    ['Book', '20%', 'Down payment'],
    ['Build', '50%', 'During construction'],
    ['Handover', '30%', 'On completion'],
  ];
  return (
    <section className="lg-section lg-pay" id="payment">
      <div className="lg-sec-head">
        <div className="lg-eyebrow">Easy to own</div>
        <h2 className="lg-h2 lg-light">Built for Buyers and Investors</h2>
      </div>
      <div className="lg-psteps">
        {steps.map(([tag, pct, lbl], i) => (
          <div className={`lg-pstep ${i === 3 ? 'lg-pstep-bonus' : ''}`} key={i}>
            <i>{tag}</i><b>{pct}</b><span>{lbl}</span>
          </div>
        ))}
      </div>
      <div className="lg-pay-foot">
        <button className="lg-submit lg-submit-inline" onClick={scrollToForm}>Book Now</button>
      </div>
    </section>
  );
}

function FAQ() {
  const [cur] = useCurrency();
  const items = [
    ['What types of residences are available?', "Studios to four bedroom apartments across two towers, plus retail."],
    ['Who is the developer?', "Binghatti is one of Dubai's leading developers, known for its bold, sculptural towers and a portfolio of landmark residences across the city."],
    ['What is the payment plan?', "70/30: 20% on booking, 50% during construction, 30% on handover."],
    ['When is handover?', "Targeted for Q2 2027. Indicative, confirmed at booking."],
    ['Can foreign nationals buy?', "Yes. Flare is freehold, open to all nationalities."],
    ['Do I pay tax on a Dubai property?', "No. Dubai has no property tax, no tax on rental income, and no capital-gains tax for individual owners."],
    ['Can buying get me residency?', "Yes. A Dubai home worth AED 2M or more (including off-plan like Flare) qualifies you and your family for a 10-year renewable Golden Visa."],
    ['Can I buy from overseas?', "Yes. The full process (reservation, contracts and payments) can be completed remotely, and we guide you at every step."],
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section className="lg-section lg-faq" id="faq">
      <div className="lg-sec-head">
        <div className="lg-eyebrow lg-eyebrow-dark">Good to know</div>
        <h2 className="lg-h2">Questions, Answered</h2>
      </div>
      <div className="lg-faq-list">
        {items.map(([q, ans], n) => (
          <div className={`lg-faq-item ${open === n ? 'lg-faq-open' : ''}`} key={n}>
            <button className="lg-faq-q" onClick={() => setOpen(open === n ? -1 : n)} aria-expanded={open === n}>
              <span>{q}</span><span className="lg-faq-ic"><IconPlus s={18} /></span>
            </button>
            <div className="lg-faq-a"><p>{ans}</p></div>
          </div>
        ))}
      </div>
    </section>
  );
}

function FinalCTA({ onRegister }) {
  const bgRef = React.useRef(null);
  React.useEffect(() => {
    let raf = 0, last = null;
    const tick = () => {
      const el = bgRef.current;
      if (el) {
        const r = el.parentElement.getBoundingClientRect();
        const vh = window.innerHeight || document.documentElement.clientHeight;
        const prog = Math.max(-1, Math.min(1, (r.top + r.height / 2 - vh / 2) / (vh / 2 + r.height / 2)));
        if (prog !== last) { el.style.transform = `translate3d(0, ${(-prog * 16).toFixed(2)}%, 0) scale(1.28)`; last = prog; }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <section className="lg-final" id="register-2">
      <div className="lg-final-bg" ref={bgRef} style={{ backgroundImage: `url('${RES('finalParallax')}')` }} />
      <div className="lg-final-inner">
        <div className="lg-final-copy">
          <h2 className="lg-h2 lg-light">Own a Piece of the Skyline.</h2>
          <p className="lg-final-sub">Get the price list and floor plans on WhatsApp in minutes.</p>
          <div className="lg-final-btns">
            <button className="lg-submit lg-submit-inline" onClick={onRegister}>Register Interest</button>
            <a className="lg-wa-btn lg-wa-solid" href={waLink()} target="_blank" rel="noopener"><IconWhatsApp s={18} /> Chat on WhatsApp</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function StickyActions({ onRegister }) {
  return (
    <div className="lg-sticky">
      <a className="lg-sticky-btn lg-sticky-call" href={`tel:${TEL}`}><IconPhone s={17} /> Call</a>
      <button className="lg-sticky-btn lg-sticky-enq" onClick={onRegister}><IconArrow s={15} /> Enquire</button>
      <a className="lg-sticky-btn lg-sticky-wa" href={waLink()} target="_blank" rel="noopener"><IconWhatsApp s={18} /> WhatsApp</a>
    </div>
  );
}

function Footer({ onLegal }) {
  return (
    <footer className="lg-footer">
      <div className="lg-foot-top">
        <img className="lg-foot-logo" src={RES('logo')} alt="Binghatti Flare" />
      </div>
      <div className="lg-foot-by">Marketed by {AGENCY} · RERA ORN {ORN}</div>
      <div className="lg-foot-copy">
        © 2026 {AGENCY}
        <span className="lg-foot-sep">·</span>
        <a href="#" className="lg-foot-link" onClick={(e) => { e.preventDefault(); onLegal('privacy'); }}>Privacy Policy</a>
        <span className="lg-foot-sep">·</span>
        <a href="#" className="lg-foot-link" onClick={(e) => { e.preventDefault(); onLegal('cookies'); }}>Cookie Policy</a>
        <span className="lg-foot-sep">·</span>
        <a href="#" className="lg-foot-link" onClick={(e) => { e.preventDefault(); onLegal('disclaimer'); }}>Disclaimer</a>
      </div>
    </footer>
  );
}

function CookieBar({ onLegal }) {
  const [show, setShow] = React.useState(() => {
    try { return localStorage.getItem('flare_consent') == null; } catch (e) { return true; }
  });
  if (!show) return null;
  const decide = (accepted) => {
    try { localStorage.setItem('flare_consent', accepted ? 'accepted' : 'declined'); } catch (e) {}
    window.__adConsent = accepted;
    if (accepted && typeof window.__initPixels === 'function') { try { window.__initPixels(); } catch (e) {} }
    setShow(false);
  };
  return (
    <div className="lg-cookiebar">
      <span>We use cookies to measure our ads and improve your experience. <a href="#" onClick={(e) => { e.preventDefault(); onLegal('cookies'); }}>Learn more</a>.</span>
      <div className="lg-cookie-btns">
        <button className="lg-cookie-decline" onClick={() => decide(false)}>Decline</button>
        <button onClick={() => decide(true)}>Accept</button>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, UrgencyBar, Hero, LeadForm, ThankYou, FormModal, InfoModal, LEGAL, DisclaimerModal, CookieBar, BrokerTrust, WhyDubai, Tour360, Facts, UnitMix, Amenities, FloorPlans, GalleryStrip, Lightbox, Location, PaymentPlan, FAQ, FinalCTA, StickyActions, Footer, waLink, CurrencyCtx });
