/* ============================================================
   DAMAC Islands — Lead-Gen Landing Page  (React + Babel)
   ============================================================ */
const { useState, useEffect, useRef } = React;
const A = "assets/";
const asset = (f) => (window.__resources && window.__resources[f]) ? window.__resources[f] : (A + f);
const T = (s) => (window.I18N ? window.I18N.t((window.__lang)||'en', s) : s);
const FILM_ID = "GWe5TfoidxA"; // official DAMAC Islands brand film (YouTube)
const PHONE = "+971585336375";
const WA = "https://wa.me/971582475234?text=" + encodeURIComponent("Hello, I'd like to know more about DAMAC Islands.");
function trackWA(){ try{ if(window.gtag){ window.gtag('event','conversion',{'send_to':'AW-18230373248/rq1_CKz9-LwcEIDX9fRD'}); } if(window.fbq){ window.fbq('track','Contact',{method:'whatsapp'}); } }catch(err){} }
function trackCall(){ try{ if(window.gtag){ window.gtag('event','conversion',{'send_to':'AW-18230373248/3uYoCO7X-bwcEIDX9fRD'}); } if(window.fbq){ window.fbq('track','Contact',{method:'phone'}); } }catch(err){} }
/* Paste your Google Apps Script Web App URL here (see campaign/google-apps-script.gs for setup). */
const LEAD_ENDPOINT = "https://script.google.com/macros/s/AKfycbybehi7F42qraOdJYQOxWfAtT53eZRsBKpPyHp4fgZF3OpDCzVEQn5FDbRN0PDp4Y8/exec";
/* LeadConnector (GoHighLevel) inbound webhook — DAMAC Islands */
const LEADCONNECTOR_ENDPOINT = "https://services.leadconnectorhq.com/hooks/mQIGQSfkaBURi1jHWkv7/webhook-trigger/b09f53a5-22f6-4ebd-8b80-b49e490f9d97";
function postLead(url, data){
  if(!url) return;
  var body;
  try { body = new URLSearchParams(data).toString(); } catch(e){ body = ''; }
  try {
    if (navigator.sendBeacon) {
      var ok = navigator.sendBeacon(url, new Blob([body], { type:'application/x-www-form-urlencoded;charset=UTF-8' }));
      if (ok) return;
    }
  } catch(e){}
  try { fetch(url, { method:'POST', mode:'no-cors', headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}, body: body }).catch(function(){}); } catch(e){}
}
function sendLead(data){
  postLead(LEAD_ENDPOINT, data);
  postLead(LEADCONNECTOR_ENDPOINT, data);
  return Promise.resolve();
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "lifestyle",
  "formPlacement": "sticky",
  "heroMood": "dark",
  "ctaColor": "#CCB073",
  "ctaLabel": "Register Interest"
}/*EDITMODE-END*/;

const HEADLINES = {
  lifestyle: {
    eyebrow: "DAMAC Islands · Dubailand",
    h1: "Live the Island State of Mind",
    sub: "Inspired by six of the world's best island destinations. Luxury villas & townhouses in the heart of Dubai."
  },
  investor: {
    eyebrow: "DAMAC Islands · Now Launching",
    h1: "Own a Tropical Island Home in Dubai",
    sub: "Luxury villas and trendy townhouses from AED 2.5M on an easy 75 / 25 payment plan, in a 30 million sq ft island community in Dubailand."
  }
};

/* ---- helpers ---- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((es) => es.forEach(e => { if (e.isIntersecting){ e.target.classList.add('in'); io.unobserve(e.target);} }), { threshold:.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}
function Icon({ name, style }) {
  const ref = useRef(null);
  useEffect(() => { if(ref.current && window.lucide){ ref.current.innerHTML=''; const i=document.createElement('i'); i.setAttribute('data-lucide',name); ref.current.appendChild(i); window.lucide.createIcons(); } }, [name]);
  return <span ref={ref} style={{display:'inline-flex',...style}} />;
}
const scrollTo = (id) => { const el=document.getElementById(id); if(!el) return; const sc=document.scrollingElement||document.documentElement; sc.scrollTop=Math.max(0, el.getBoundingClientRect().top+sc.scrollTop-56); };

/* starting price across currencies. EUR/INR auto-update from a live FX feed on load
   (free, no key, CORS-enabled). USD stays fixed via the AED→USD peg. Values below are fallbacks. */
var STARTING = { AED:'AED 2.5M', USD:'USD 681K', EUR:'EUR 630K', INR:'INR 5.7Cr' };
var AED_BASE = 2500000;
function fmtCur(cur, amount){
  if(cur==='INR'){ var cr=amount/1e7; return 'INR ' + (cr>=10?Math.round(cr):cr.toFixed(1).replace(/\.0$/,'')) + 'Cr'; }
  var k=amount/1000; if(k>=1000){ return cur+' '+(k/1000).toFixed(2).replace(/\.?0+$/,'')+'M'; }
  return cur+' '+Math.round(k)+'K';
}
function loadRates(done){
  try {
    fetch('https://open.er-api.com/v6/latest/AED').then(function(r){return r.json();}).then(function(d){
      if(d && d.rates){
        if(d.rates.EUR) STARTING.EUR = fmtCur('EUR', AED_BASE*d.rates.EUR);
        if(d.rates.INR) STARTING.INR = fmtCur('INR', AED_BASE*d.rates.INR);
        if(d.rates.USD) STARTING.USD = fmtCur('USD', AED_BASE*d.rates.USD);
        done && done();
      }
    }).catch(function(){});
  } catch(e){}
}
const RERA = 'RERA Permit 0343324169';
const CURRENCIES = ['AED','USD','EUR','INR'];
function CurrencySwitch({ cur, setCur }) {
  const [open,setOpen]=useState(false);
  const ref=useRef(null);
  useEffect(()=>{ if(!open) return; const f=(e)=>{ if(ref.current&&!ref.current.contains(e.target)) setOpen(false); }; document.addEventListener('mousedown',f); return ()=>document.removeEventListener('mousedown',f); },[open]);
  return (
    <div className="cur-switch2" ref={ref}>
      <button type="button" className="cur-trigger" onClick={()=>setOpen(o=>!o)} aria-label="Currency"><span>{cur}</span><Icon name="chevron-down" /></button>
      {open && (
        <div className="cur-menu">
          {CURRENCIES.map(c=>(
            <button type="button" key={c} className={"cur-opt"+(c===cur?" on":"")} onClick={()=>{ setCur(c); setOpen(false); }}>{c}</button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- language switcher ---- */
function LangSwitch({ lang, setLang }) {
  const [open,setOpen]=useState(false);
  const ref=useRef(null);
  useEffect(()=>{ if(!open) return; const f=(e)=>{ if(ref.current&&!ref.current.contains(e.target)) setOpen(false); }; document.addEventListener('mousedown',f); return ()=>document.removeEventListener('mousedown',f); },[open]);
  const langs=(window.I18N&&window.I18N.langs)||[['en','EN','English']];
  const cur=langs.find(l=>l[0]===lang)||langs[0];
  return (
    <div className="lang-switch" ref={ref}>
      <button type="button" className="lang-trigger" onClick={()=>setOpen(o=>!o)} aria-label="Language"><Icon name="globe" /><span>{cur[1]}</span><Icon name="chevron-down" /></button>
      {open && (
        <div className="lang-menu">
          {langs.map(l=>(
            <button type="button" key={l[0]} className={"lang-opt"+(l[0]===lang?" on":"")} onClick={()=>{ setLang(l[0]); setOpen(false); }}>{l[2]}</button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- top bar ---- */
function Bar({ t, lang, setLang, cur, setCur }) {
  return (
    <header className="bar">
      <div className="wrap bar-in">
        <a className="logo" href="#top"><img src={asset("logo-white.webp")} alt="DAMAC Islands logo" /></a>
        <div className="bar-r">
          <CurrencySwitch cur={cur} setCur={setCur} />
          <LangSwitch lang={lang} setLang={setLang} />
          <a className="bar-phone bar-wa" href={WA} onClick={trackWA} target="_blank" rel="noopener" aria-label="WhatsApp"><Icon name="message-circle" /></a>
          <a className="bar-phone" href={"tel:"+PHONE} onClick={trackCall} aria-label="Call us"><Icon name="phone" /></a>
          <button className="btn btn-primary bar-register" style={{backgroundColor:t.ctaColor}} onClick={()=>scrollTo('register')}>{T('Register Interest')}</button>
        </div>
      </div>
    </header>
  );
}

/* ---- lead form ---- */
const COUNTRIES = window.COUNTRIES || [["United Arab Emirates","+971","AE"]];

/* custom country-code dropdown: collapsed shows "ISO +dial", open lists full names */
function CountrySelect({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const ref = useRef(null);
  const sel = COUNTRIES.find(c=>c[1]===value) || COUNTRIES.find(c=>c[2]==='AE') || COUNTRIES[0];
  useEffect(()=>{
    if(!open) return;
    const onDoc=(e)=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown',onDoc);
    return ()=>document.removeEventListener('mousedown',onDoc);
  },[open]);
  const list = COUNTRIES.filter(([n,c,iso])=>{
    const s=q.trim().toLowerCase(); if(!s) return true;
    return n.toLowerCase().includes(s) || c.includes(s) || iso.toLowerCase().includes(s);
  });
  return (
    <div className="cc" ref={ref}>
      <button type="button" className="field cc-trigger" onClick={()=>setOpen(o=>!o)} aria-label="Country dial code" aria-expanded={open}>
        <span className="cc-val">{sel[2]} {sel[1]}</span>
        <span className={"cc-chev"+(open?" up":"")}><Icon name="chevron-down" /></span>
      </button>
      {open && (
        <div className="cc-panel">
          <input className="cc-search" autoFocus placeholder="Search country" value={q} onChange={(e)=>setQ(e.target.value)} />
          <div className="cc-list">
            {list.map(([n,c,iso],i)=>(
              <button type="button" key={iso+i} className={"cc-opt"+(c===value?" on":"")} onClick={()=>{ onChange(c); setOpen(false); setQ(''); }}>
                <span className="cc-iso">{iso}</span><span className="cc-name">{n}</span><span className="cc-dial">{c}</span>
              </button>
            ))}
            {list.length===0 && <div className="cc-empty">No match</div>}
          </div>
        </div>
      )}
    </div>
  );
}

function LeadForm({ t, compact }) {
  const [done, setDone] = useState(false);
  const [f, setF] = useState({ name:'', email:'', code:'+971', phone:'' });
  const [err, setErr] = useState({});
  const set = (k)=>(e)=>{ const v=e.target.value; setF(p=>({...p,[k]:v})); setErr(p=>({...p,[k]:null})); };
  const validate = ()=>{
    const er={};
    if(!f.name.trim() || f.name.trim().length<2) er.name = T('Please enter your full name.');
    if(!/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(f.email.trim())) er.email = T('Please enter a valid email address.');
    var digits=(f.phone.match(/\d/g)||[]).length;
    if(/[^\d\s()+\-.]/.test(f.phone) || digits<7 || digits>15) er.phone = T('Please enter a valid phone number.');
    return er;
  };
  const submit = (e)=>{ e.preventDefault(); const er=validate(); if(Object.keys(er).length){ setErr(er); return; } var nm=f.name.trim(); var parts=nm.split(/\s+/); var utm={}; try{ var qp=new URLSearchParams(location.search); ['utm_source','utm_medium','utm_campaign','utm_term','utm_content'].forEach(function(k){ if(qp.get(k)) utm[k]=qp.get(k); }); }catch(err){} sendLead(Object.assign({ name:nm, first_name:parts[0]||nm, last_name:parts.slice(1).join(' '), email:f.email.trim(), countryCode:f.code, phone:(f.code+' '+f.phone).trim(), consent:'Yes', language:(window.__lang||'en'), source:'DAMAC Islands Landing', page:(typeof location!=='undefined'?location.href:''), submittedAt:new Date().toISOString() }, utm)); try{ if(window.gtag){ window.gtag('event','conversion',{'send_to':'AW-18230373248/sPkXCLj3-LwcEIDX9fRD'}); } if(window.fbq){ window.fbq('track','Lead',{content_name:'DAMAC Islands Landing'}); } }catch(err){} setDone(true); };
  return (
    <div className="lead" id="register">
      <button className="lead-close" onClick={()=>scrollTo('lifestyle')} aria-label="Close form"><Icon name="x" /></button>
      {!done ? (
        <React.Fragment>
          <div className="lead-top">
            <div className="t">{T('Register your interest')}</div>
            <div className="s">{T('Get floor plans, the full price list & payment plan.')}</div>
          </div>
          <form className="lead-body" onSubmit={submit} noValidate>
            <div className="field-row">
              <label>{T('Full name')}</label>
              <input className={"field"+(err.name?" invalid":"")} placeholder={T('Your name')} value={f.name} onChange={set('name')} aria-invalid={!!err.name} />
              {err.name && <div className="field-err">{err.name}</div>}
            </div>
            <div className="field-row">
              <label>{T('Email address')}</label>
              <input className={"field"+(err.email?" invalid":"")} type="email" placeholder="you@email.com" value={f.email} onChange={set('email')} aria-invalid={!!err.email} />
              {err.email && <div className="field-err">{err.email}</div>}
            </div>
            <div className="field-row">
              <label>{T('Phone number')}</label>
              <div className="phone-row">
                <CountrySelect value={f.code} onChange={(c)=>setF(p=>({...p,code:c}))} />
                <input className={"field"+(err.phone?" invalid":"")} type="tel" inputMode="tel" placeholder="50 123 4567" value={f.phone} onChange={set('phone')} aria-invalid={!!err.phone} />
              </div>
              {err.phone && <div className="field-err">{err.phone}</div>}
            </div>
            <button className="btn btn-primary" type="submit" style={{backgroundColor:t.ctaColor}}>{T(t.ctaLabel)} <Icon name="arrow-right" /></button>
            <div className="lead-note"><Icon name="lock" /> {T('Your details stay private. No spam, just a call back from a Treysta advisor.')}</div>
          </form>
        </React.Fragment>
      ) : (
        <div className="lead-success">
          <div className="ck"><Icon name="check" /></div>
          <h3>{T('Thank you')}, {f.name.split(' ')[0]||'friend'}.</h3>
          <p>{T('A Treysta property advisor will reach out shortly with floor plans, pricing and the payment plan for DAMAC Islands.')}</p>
        </div>
      )}
    </div>
  );
}

/* ---- hero ---- */
function Hero({ t, onFilm, cur, setCur }) {
  const h = HEADLINES[t.headline] || HEADLINES.lifestyle;
  const heroForm = t.formPlacement === 'hero';
  return (
    <section className="hero" id="top" data-mood={t.heroMood}>
      <div className="hero-bg"><img src={asset("hero-lagoon.jpg")} alt="DAMAC Islands lagoon and island living" /></div>
      <div className="hero-video"><iframe src="https://player.vimeo.com/video/1198991510?background=1&autoplay=1&loop=1&muted=1&dnt=1" title="DAMAC Islands film" frameBorder="0" allow="autoplay; fullscreen; picture-in-picture" allowFullScreen></iframe></div>
      <div className="hero-scrim" />
      <div className="wrap hero-grid">
        <div className="hero-l">
          <div className="eyebrow light">{h.eyebrow}</div>
          <h1>{T(h.h1)}</h1>
          <p className="sub">{T(h.sub)}</p>
          <div className="hero-chips">
            <span className="hchip"><Icon name="tag" /> {T('From')} {STARTING[cur]}</span>
            <span className="hchip"><Icon name="palmtree" /> {T('Six Island Destinations')}</span>
          </div>
          <button className="film-btn" onClick={onFilm}><span className="play"><Icon name="play" /></span> {T('Watch the film')}</button>

        </div>
        {heroForm && (
        <div className="hero-r">
          <LeadForm t={t} />
        </div>
        )}
      </div>
    </section>
  );
}

/* ---- trust strip ---- */
function Strip({ cur }) {
  const s = [['6','island destinations'],['30M','sq ft community'],['22','world-class amenities'],['4–7','bedroom homes']];
  return (
    <section className="strip"><div className="wrap strip-in">
      {s.map(([n,l])=> <div className="st" key={l}><div className="num">{n}</div><div className="lbl">{l}</div></div>)}
    </div></section>
  );
}

/* ---- amenities (official project renders) ---- */
function Lifestyle() {
  const feat = {ic:'sparkles', n:'The Central Hub Fountain', d:'The heart of paradise — where water, light and lasers dance in harmony.', img:'amenity-central-hub-fountain.jpg'};
  const amen = [
    {ic:'waves', n:'Aqua Dome', img:'amenity-aqua-dome.jpg'},
    {ic:'umbrella', n:'Aqua Park & Rapids', img:'amenity-aqua-park.jpg'},
    {ic:'wind', n:'Jungle Swings', img:'amenity-jungle-swings.jpg'},
    {ic:'bird', n:'Wildlife & Tortoise Garden', img:'amenity-tortoise-garden.jpg'},
    {ic:'sailboat', n:'Gondola-Style Paddling', img:'proj-lagoon-gondola-day.jpg'},
    {ic:'droplets', n:'Lagoon Waterfalls & Hot Springs Spa', img:'proj-beach-waterfall-yoga.jpg'},
  ];
  return (
    <section className="sec life" id="lifestyle"><div className="wrap">
      <div className="sec-head reveal"><div className="eyebrow">{T('22 world-class amenities')}</div><h2>{T('Your Island Life, Curated to Perfection')}</h2></div>
      <article className="amen-feature reveal">
        <img src={asset(feat.img)} alt={feat.n + ' — DAMAC Islands, Dubai'} />
        <div className="ainfo">
          <div className="abadge"><Icon name={feat.ic} /></div>
          <div className="aname">{T(feat.n)}</div>
          <div className="adesc">{T(feat.d)}</div>
        </div>
      </article>
      <div className="amen-photos">
        {amen.map((a,i)=>(
          <article className="aphoto reveal" key={a.n} style={{transitionDelay:(i*55)+'ms'}}>
            <img src={asset(a.img)} alt={a.n + ' — DAMAC Islands amenity'} />
            <div className="ainfo">
              <div className="abadge"><Icon name={a.ic} /></div>
              <div className="aname">{T(a.n)}</div>
            </div>
          </article>
        ))}
      </div>
    </div></section>
  );
}

/* ---- residences / prices ---- */
function Residences({ t, cur }) {
  const r = [
    {tag:'Townhouse',nm:'Trendy Townhouse · 4–5 Bedroom',meta:'DITH-M & DITH-E · 4–5BR + maid',price:'From AED 2.5M',img:'townhouses-garden-evening.jpg'},
    {tag:'Luxury Villa',nm:'DIV-55 · 6 Bedroom',meta:'Luxury villa · 6BR + maid',price:'From AED 13.57M',img:'villa-luxury-front-dusk.jpg'},
    {tag:'Luxury Villa',nm:'DIV-75 · 7 Bedroom',meta:'Luxury villa · 7BR + maid + gym',price:'From AED 18.61M',img:'villa-luxury-pool-rear.jpg'},
  ];
  return (
    <section className="sec res" id="residences"><div className="wrap">
      <div className="sec-head reveal"><div className="eyebrow">{T('The residences')}</div><h2>{T('Find Your Island Home')}</h2><p className="lead-p">{T('Trendy townhouses and luxury villas with breezy, open-plan layouts that capture cooling cross-winds and blend indoor living with the lush outdoors.')}</p></div>
      <div className="res-grid">
        {r.map((x,i)=>(
          <article className="rcard reveal" key={x.nm} style={{transitionDelay:(i*60)+'ms'}} onClick={()=>scrollTo('register')}>
            <div className="rcard-ph"><img src={asset(x.img)} alt={x.nm + ' for sale at DAMAC Islands, Dubai'} /><span className="rcard-tag">{T(x.tag)}</span></div>
            <div className="rcard-bd">
              <div className="nm">{x.nm}</div>
              <div className="meta">{T(x.meta)}</div>
              <div className="pr">
                <div><div className="from">{T('Pricing')}</div><div className="amt">{T('On request')}</div></div>
                <div className="go"><Icon name="arrow-up-right" /></div>
              </div>
            </div>
          </article>
        ))}
      </div>
    </div></section>
  );
}

/* ---- island clusters ---- */
function Clusters() {
  const cl = [
    {n:'Maldives', d:'Powder-sand beaches and turquoise shallows', img:'cluster-maldives.jpg'},
    {n:'Bora Bora', d:'Island clubhouse ringed by clear lagoon', img:'cluster-borabora.jpg'},
    {n:'Seychelles', d:'Lush jungle rivers and green canopy', img:'cluster-seychelles.jpg'},
    {n:'Hawaii', d:'Cascading waterfalls and tropical bloom', img:'cluster-hawaii.jpg'},
    {n:'Bali', d:'Serene lagoon retreats at golden hour', img:'cluster-bali.jpg'},
    {n:'Fiji', d:'Gondola lagoons and barefoot luxury', img:'cluster-fiji.jpg'},
  ];
  return (
    <section className="sec clusters" id="clusters"><div className="wrap">
      <div className="sec-head reveal"><div className="eyebrow light">{T('Inspired by six island destinations')}</div><h2>{T('Six Islands, One Address')}</h2></div>
      <div className="cluster-plan reveal" style={{backgroundImage:`url(${asset("masterplan-birdseye.jpg")})`}} role="img" aria-label="DAMAC Islands masterplan"><span className="cluster-plan-cap">{T('The DAMAC Islands masterplan')}</span></div>
      <div className="cluster-grid">
        {cl.map((c,i)=>(
          <article className="ccard reveal" key={c.n} style={{transitionDelay:((i%3)*60)+'ms'}}>
            <img src={asset(c.img)} alt={c.n + ' cluster at DAMAC Islands, Dubai'} />
            <span className="ci">0{i+1}</span>
            <div className="cc"><div className="cn">{c.n}</div><div className="cd">{T(c.d)}</div></div>
          </article>
        ))}
      </div>
    </div></section>
  );
}

/* ---- floor plans / brochure ---- */
function FloorPlans({ t }) {
  const plans = [
    {pn:'DITH-M · 4 Bedroom', ps:'Trendy townhouse · 4BR + maid', img:'floorplan-townhouse.jpg'},
    {pn:'DIV-55 · 6 Bedroom', ps:'Luxury villa · 10,671 sqft', img:'floorplan-villa-ground.jpg'},
    {pn:'DIV-75 · 7 Bedroom', ps:'Luxury villa · 7BR + gym + maid', img:'floorplan-villa-second.jpg'},
  ];
  return (
    <section className="sec plans" id="plans"><div className="wrap">
      <div className="sec-head reveal"><div className="eyebrow">{T('Floor plans')}</div><h2>{T('Explore the Layouts')}</h2><p className="lead-p">{T('Spacious, light-filled homes designed around indoor and outdoor living. Get the full set of floor plans with your info pack.')}</p></div>
      <div className="plans-grid">
        {plans.map((p,i)=>(
          <article className="plan reveal" key={p.pn} style={{transitionDelay:(i*60)+'ms'}} onClick={()=>scrollTo('register')}>
            <div className="plan-img"><img src={asset(p.img)} alt={p.pn + ' floor plan — DAMAC Islands'} /><div className="plan-lock"><Icon name="lock" /><span>{T('Register to unlock')}</span></div></div>
            <div className="plan-bd"><div><div className="pn">{p.pn}</div><div className="ps">{T(p.ps)}</div></div><div className="plan-dl"><Icon name="download" /></div></div>
          </article>
        ))}
      </div>
      <div className="plans-cta reveal"><button className="btn btn-primary" style={{backgroundColor:t.ctaColor}} onClick={()=>scrollTo('register')}>{T('Download Brochure & Floor Plans')} <Icon name="download" /></button></div>
    </div></section>
  );
}

/* ---- why dubai (international investor stats) ---- */
function WhyDubai() {
  const stats = [
    {n:'0%', l:'No annual property, income or capital-gains tax'},
    {n:'Up to 10%', l:"Gross rental yields, among the world's strongest"},
    {n:'10 Yr', l:'Golden Visa on homes of AED 2M+'},
    {n:'100%', l:'Freehold for all nationalities · RERA escrow protected'},
    {n:'Top 10', l:"Ranked among the world's safest cities"},
  ];
  return (
    <section className="sec whydubai" id="why-dubai"><div className="wrap">
      <div className="sec-head center reveal"><div className="eyebrow light">{T('Why Dubai')}</div><h2>{T('The world\u2019s smartest place to own a home')}</h2></div>
      <div className="whyd-grid">
        {stats.map((s,i)=>(
          <div className="whyd reveal" key={s.l} style={{transitionDelay:(i*60)+'ms'}}>
            <div className="whyd-n">{s.n}</div>
            <div className="whyd-l">{T(s.l)}</div>
          </div>
        ))}
      </div>
    </div></section>
  );
}

/* ---- why invest ---- */
function Invest({ cur }) {
  const pts = [
    ['shield-check','A proven developer','DAMAC has handed over more than 50,000 homes across Dubai since 2002.'],
    ['percent','Zero income tax','Keep every dirham of your rental income and capital gains. Dubai charges no income tax.'],
    ['globe','Golden Visa eligibility','A qualifying island home can grant you long term UAE residency.'],
  ];
  return (
    <section className="sec invest" id="invest"><div className="wrap">
      <div className="sec-head reveal"><div className="eyebrow light">{T('Why invest')}</div><h2>{T('A Landmark Address, a Smart Investment')}</h2></div>
      <div className="invest-grid">
        <div className="invest-points reveal">
          {pts.map(([ic,tt,d])=>(
            <div className="ipoint" key={tt}><div className="ic"><Icon name={ic} /></div><div><div className="t">{T(tt)}</div><div className="d">{T(d)}</div></div></div>
          ))}
        </div>
        <div className="invest-stats reveal">
          <div className="istat"><div className="n">Up to 10%</div><div className="k">{T('rental yields, among the strongest in the world')}</div></div>
          <div className="istat"><div className="n">100+</div><div className="k">{T('international awards received by DAMAC')}</div></div>
          <div className="istat"><div className="n">9</div><div className="k">{T('countries across the DAMAC footprint')}</div></div>
          <div className="istat"><div className="n">75/25</div><div className="k">{T('easy payment plan')}</div></div>
        </div>
      </div>
    </div></section>
  );
}

/* ---- payment plan ---- */
function Payment() {
  return (
    <section className="sec pay" id="payment"><div className="wrap">
      <div className="sec-head center reveal"><div className="eyebrow">{T('Payment plan')}</div><h2>{T('An Easy 75 / 25 Payment Plan')}</h2></div>
      <div className="pay-bar reveal">
        <div className="pay-seg during"><div className="pct">75%</div><div className="ph">{T('During Construction')}</div><div className="pd">{T('Spread comfortably across the build in easy milestone instalments.')}</div></div>
        <div className="pay-seg on-comp"><div className="pct">25%</div><div className="ph">{T('On Handover')}</div><div className="pd">{T('A final 25% on completion of your island home.')}</div></div>
      </div>
    </div></section>
  );
}

/* ---- location ---- */
function Location() {
  const near = [['Sports City, Motor City & DAMAC Hills','car-front',15],['Expo 2020 Venue','map-pin',20],['Al Maktoum Int. Airport','plane',23],['Dubai Investment Park','map-pin',15],['Burj Al Arab','map-pin',30],['Dubai Int. Airport','plane',28]];
  return (
    <section className="sec loc" id="location"><div className="wrap">
      <div className="loc-grid">
        <div className="reveal">
          <div className="eyebrow light">{T('Location')}</div>
          <h2>{T('Minutes from the Heart of Dubai')}</h2>
          <p className="lead-p" style={{color:'rgba(255,255,255,.8)'}}>{T("Set along Emirates Road in Dubailand. A quick drive from the city's landmarks and both airports.")}</p>
          <div className="loc-list">
            {near.map(([p,ic,m])=>(
              <div className="loc-row" key={p}><span className="p"><Icon name={ic} /> {T(p)}</span><span className="m">{m}<small>MIN</small></span></div>
            ))}
          </div>
        </div>
        <div className="loc-map reveal"><img src={asset("proj-lagoon-aerial-day.jpg")} alt="DAMAC Islands aerial — Dubailand" /><span className="cluster-plan-cap">{T('Dubailand, Dubai')}</span></div>
      </div>
    </div></section>
  );
}

/* ---- faq ---- */
function Faq() {
  const items = [
    {q:'What is DAMAC Islands?', a:'A 30 million sq ft tropical island community in Dubailand by DAMAC Properties, inspired by six of the world\u2019s best island destinations \u2014 Maldives, Bora Bora, Seychelles, Hawaii, Bali and Fiji.'},
    {q:'What home types are available?', a:'Trendy townhouses (4BR and 5BR + maid) and luxury villas (6BR and 7BR + maid + gym), with breezy, open-plan layouts that capture cooling cross-winds.'},
    {q:'What are the starting prices?', a:'Pricing is available on request. Register your interest and a Treysta advisor will share the full price list and the latest 75 / 25 payment plan.'},
    {q:'Can overseas buyers purchase here?', a:'Yes. DAMAC Islands is freehold and open to all nationalities, and a qualifying home can make you eligible for the UAE Golden Visa.'},
    {q:'Where is the community located?', a:'Along Emirates Road in Dubailand \u2014 around 15 minutes to Sports City, Motor City and DAMAC Hills, 20 minutes to the Expo 2020 venue and 23 minutes to Al Maktoum International Airport.'},
    {q:'What amenities can residents enjoy?', a:'22 world-class amenities including the Central Hub Fountain, Aqua Dome, Aqua Park, jungle river and rapids, jungle swings, lagoon waterfalls and hot springs spa, mini golf island, wildlife and tortoise gardens and gondola-style paddling.'},
    {q:'Why invest in Dubai?', a:'Dubai offers tax-free rental income and capital gains, a US dollar-pegged currency, world-class infrastructure and safety, and some of the strongest rental yields in the world — a top choice for European and American investors.'},
    {q:'Can I buy from outside the UAE?', a:'Yes. Overseas buyers can reserve remotely. The paperwork is handled digitally and a Treysta advisor guides you through every step, from booking to handover.'},
    {q:'Are there taxes or ownership restrictions for foreign buyers?', a:'No. DAMAC Islands is freehold and open to all nationalities, with no property tax, no income tax on rent and no capital gains tax. A qualifying purchase can also grant a 10-year UAE Golden Visa.'},
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="sec faq" id="faq"><div className="wrap">
      <div className="sec-head center reveal"><div className="eyebrow">{T('Good to know')}</div><h2>{T('Frequently Asked Questions')}</h2></div>
      <div className="faq-list reveal">
        {items.map((it,i)=>(
          <div className={"faq-item"+(open===i?" open":"")} key={i}>
            <button className="faq-q" onClick={()=>setOpen(open===i?-1:i)}>{T(it.q)}<span className="chev"><Icon name="chevron-down" /></span></button>
            <div className="faq-a" style={{maxHeight:open===i?'320px':'0'}}><div className="faq-a-inner">{T(it.a)}</div></div>
          </div>
        ))}
      </div>
    </div></section>
  );
}

/* ---- final CTA ---- */
function Final({ t }) {
  return (
    <section className="final" id="enquire">
      <div className="final-bg"><img src={asset("proj-neighbourhood-lagoon-dusk.jpg")} alt="DAMAC Islands waterfront community at golden hour" /></div>
      <div className="final-scrim" />
      <div className="wrap final-in reveal">
        <div className="eyebrow light">{T('Limited first release')}</div>
        <h2>{T('Begin Your Island Life Today')}</h2>
        <p>{T('Register now to receive the full price list, floor plans and exclusive launch offers for DAMAC Islands.')}</p>
        <div className="final-cta">
          <button className="btn btn-primary" style={{backgroundColor:t.ctaColor}} onClick={()=>scrollTo('register')}>{t.ctaLabel} <Icon name="arrow-right" /></button>
        </div>
      </div>
    </section>
  );
}

/* ---- footer ---- */
function Footer({ onPolicy }) {
  return (
    <footer className="ft">
      <div className="wrap ft-in">
        <a className="logo" href="#top"><img src={asset("logo-white.webp")} alt="DAMAC Islands" /></a>
      </div>
      <div className="wrap ft-legal">
        <div className="ft-broker">{T('Marketed by')} Treysta Real Estate Broker L.L.C · RERA ORN 46270</div>
        <div className="ft-copy">© 2026 Treysta Real Estate Broker L.L.C
          <span className="ft-sep"> · </span><a href="#privacy" onClick={(e)=>{e.preventDefault();onPolicy('privacy');}}>{T('Privacy Policy')}</a>
          <span className="ft-sep"> · </span><a href="#cookies" onClick={(e)=>{e.preventDefault();onPolicy('cookies');}}>{T('Cookie Policy')}</a>
          <span className="ft-sep"> · </span><a href="#terms" onClick={(e)=>{e.preventDefault();onPolicy('terms');}}>{T('Disclaimer')}</a>
        </div>
      </div>
    </footer>
  );
}

/* ---- legal modal (privacy / cookies / terms) ---- */
const LEGAL = {
  privacy: { t:'Privacy Policy', body:[
    'At Treysta, the privacy of our visitors is one of our top priorities. This Privacy Policy explains what information we collect and how we use it, and applies only to our online activities and to information you choose to share with us. By using this page you consent to this Privacy Policy.',
    'What we collect: the personal details you provide when you register or enquire — typically your name, email address, phone number and the content of your message. Like most websites we also collect standard log data (IP address, browser type, internet service provider, referring/exit pages, date and time stamp, and clicks) for analytics; this is not linked to any personally identifiable information.',
    'How we use your information: to respond to your enquiry and contact you about relevant properties; to operate, maintain and improve our website; to understand and analyse usage; to develop new products and services; to prevent fraud and keep the site secure; and to carry out marketing and promotional activity. We do not sell your data; we may share it with the developer, DAMAC Properties, strictly to progress your interest.',
    'Cookies & advertising: we use cookies and web beacons to optimise your experience. Third-party advertising partners (e.g. Meta, Google) may set their own cookies and technologies, governed by their own privacy policies; we have no access to or control over these. You can disable cookies via your browser settings.',
    "Children's information: we do not knowingly collect personal information from children under 13. If you believe a child has provided information, contact us and we will promptly remove it.",
    'Your GDPR rights (EU/EEA & UK): you have the right to access, rectify, erase, restrict or object to processing, and to data portability, and to withdraw consent at any time. We action valid requests within one month. Where data is transferred outside the EEA (including to the UAE) we rely on appropriate safeguards. To exercise any right or make a complaint, email info@treysta.ae — you may also complain to your local data protection authority.',
  ]},
  cookies: { t:'Cookie Policy', body:[
    'Treysta uses cookies and web beacons to remember your preferences (such as the pages you visit, time spent on the site, and the browser you use) so we can personalise and improve your experience.',
    'Essential cookies make the page work; optional analytics and marketing cookies measure campaign performance and show relevant ads. Third-party advertising partners (e.g. Meta, Google) may set their own cookies under their own privacy policies.',
    'You can accept or decline non-essential cookies via the banner, and clear or block cookies at any time in your browser settings. Blocking essential cookies may affect how the page works.',
  ]},
  terms: { t:'Terms & Conditions', body:[
    'This website is operated by The Treysta Real Estate Broker L.L.C for marketing DAMAC Islands. Content is for general information only and is not an offer, invitation or contract.',
    'All prices, payment plans, areas, layouts and availability are indicative and may change without notice. Images are artist renderings and may differ from the final build.',
    'Any booking is subject to the developer sale and purchase agreement and prevailing terms. Please verify details with an advisor before making a decision.',
  ]},
};
function LegalModal({ which, onClose }) {
  const data = LEGAL[which];
  useEffect(()=>{ const k=(e)=>{ if(e.key==='Escape') onClose(); }; window.addEventListener('keydown',k); return ()=>window.removeEventListener('keydown',k); },[]);
  if(!data) return null;
  return (
    <div className="legal-modal" onClick={onClose}>
      <div className="legal-card" onClick={(e)=>e.stopPropagation()}>
        <button className="legal-close" onClick={onClose} aria-label="Close"><Icon name="x" /></button>
        <h3 className="serif">{T(data.t)}</h3>
        {data.body.map((p,i)=><p key={i}>{T(p)}</p>)}
      </div>
    </div>
  );
}

/* ---- cookie consent banner ---- */
function CookieBar({ onPolicy }) {
  const [show, setShow] = useState(false);
  useEffect(()=>{ try{ if(!localStorage.getItem('treysta_cookie_consent')) setShow(true); }catch(e){ setShow(true); } },[]);
  const decide = (v) => { try{ localStorage.setItem('treysta_cookie_consent', v); }catch(e){} setShow(false); };
  if(!show) return null;
  return (
    <div className="cookie-bar">
      <div className="cookie-txt">We use cookies to improve your experience and measure our campaigns. See our <a href="#cookies" onClick={(e)=>{e.preventDefault();onPolicy('cookies');}}>Cookie Policy</a>.</div>
      <div className="cookie-acts">
        <button className="cookie-decline" onClick={()=>decide('declined')}>{T('Decline')}</button>
        <button className="btn btn-primary cookie-accept" onClick={()=>decide('accepted')}>{T('Accept')}</button>
      </div>
    </div>
  );
}

/* ---- sticky CTA bar (sticky form placement) ---- */
function StickyCta({ t, cur }) {
  const [show, setShow] = useState(false);
  useEffect(() => { const f=()=>setShow(window.scrollY>640); window.addEventListener('scroll',f); f(); return ()=>window.removeEventListener('scroll',f); }, []);
  return (
    <div className={"sticky-cta"+(show?" show":"")}>
      <div className="wrap sticky-in">
        <div className="txt"><div className="t">{T('Live the island state of mind')}</div><div className="s">{T('Luxury villas & trendy townhouses')}</div></div>
        <button className="btn btn-primary" style={{backgroundColor:t.ctaColor}} onClick={()=>scrollTo('register')}>{t.ctaLabel} <Icon name="arrow-right" /></button>
      </div>
    </div>
  );
}

/* ---- brand film modal ---- */
function FilmModal({ onClose }) {
  useEffect(()=>{ const onKey=(e)=>{ if(e.key==='Escape') onClose(); }; window.addEventListener('keydown',onKey); return ()=>window.removeEventListener('keydown',onKey); },[]);
  return (
    <div className="film-modal" onClick={onClose}>
      <div className="film-frame" onClick={(e)=>e.stopPropagation()}>
        <button className="film-close" onClick={onClose} aria-label="Close film"><Icon name="x" /></button>
        <iframe src={"https://www.youtube-nocookie.com/embed/"+FILM_ID+"?autoplay=1&rel=0"} title="DAMAC Islands brand film" allow="autoplay; encrypted-media; fullscreen" allowFullScreen></iframe>
      </div>
    </div>
  );
}

/* ---- sticky action footer (Call · WhatsApp · Enquire) ---- */
function MobileActionBar({ t }) {
  return (
    <div className="mbar">
      <a className="mbar-b call" href={"tel:"+PHONE} onClick={trackCall}><Icon name="phone" /><span>{T('Call')}</span></a>
      <a className="mbar-b wa" href={WA} onClick={trackWA} target="_blank" rel="noopener"><Icon name="message-circle" /><span>WhatsApp</span></a>
      <button className="mbar-b enquire" style={{backgroundColor:t.ctaColor}} onClick={()=>scrollTo('register')}><Icon name="send" /><span>{T('Enquire')}</span></button>
    </div>
  );
}

/* ---- app ---- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [film, setFilm] = useState(false);
  const [legal, setLegal] = useState(null);
  const [cur, setCur] = useState('USD');
  const [, bumpFx] = useState(0);
  useEffect(()=>{ loadRates(function(){ bumpFx(function(n){return n+1;}); }); }, []);
  const [lang, setLang] = useState(()=>{ try { return localStorage.getItem('di_lang')||'en'; } catch(e){ return 'en'; } });
  window.__lang = lang;
  const changeLang = (l)=>{ try{ localStorage.setItem('di_lang',l); }catch(e){} setLang(l); };
  useReveal();
  useEffect(()=>{ if(window.lucide) window.lucide.createIcons(); });
  return (
    <React.Fragment>
      <Bar t={t} lang={lang} setLang={changeLang} cur={cur} setCur={setCur} />
      <Hero t={t} onFilm={()=>setFilm(true)} cur={cur} setCur={setCur} />
      <Strip cur={cur} />
      <Lifestyle />
      <Clusters />
      <Residences t={t} cur={cur} />
      <FloorPlans t={t} />
      <WhyDubai />
      <Payment />
      <Location />
      <Faq />
      {t.formPlacement === 'sticky' && (
        <section className="sec" style={{background:'var(--shell)'}} id="register-section">
          <div className="wrap" style={{maxWidth:560}}>
            <div className="sec-head center reveal" style={{marginBottom:28}}><div className="eyebrow">{T('Register')}</div><h2>{T('Request Your Info Pack')}</h2></div>
            <div className="reveal"><LeadForm t={t} /></div>
          </div>
        </section>
      )}
      <Final t={t} />
      <Footer onPolicy={setLegal} />
      <MobileActionBar t={t} />
      {film && <FilmModal onClose={()=>setFilm(false)} />}
      {legal && <LegalModal which={legal} onClose={()=>setLegal(null)} />}
      <CookieBar onPolicy={setLegal} />

      <TweaksPanel>
        <TweakSection label="Campaign message" />
        <TweakRadio label="Headline angle" value={t.headline} options={['lifestyle','investor']} onChange={(v)=>setTweak('headline',v)} />
        <TweakText label="CTA label" value={t.ctaLabel} onChange={(v)=>setTweak('ctaLabel',v)} />
        <TweakSection label="Layout & look" />
        <TweakRadio label="Lead form" value={t.formPlacement} options={['hero','sticky']} onChange={(v)=>setTweak('formPlacement',v)} />
        <TweakRadio label="Hero mood" value={t.heroMood} options={['dark','light']} onChange={(v)=>setTweak('heroMood',v)} />
        <TweakColor label="CTA colour" value={t.ctaColor} options={['#CCB073','#0E7E8C','#D2754C','#222222']} onChange={(v)=>setTweak('ctaColor',v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
