const { useEffect, useMemo, useState } = React;
const money = new Intl.NumberFormat("nl-NL",{style:"currency",currency:"EUR",maximumFractionDigits:0});
const labels={apartment:"Appartement",detached:"Vrijstaande villa","ground-floor":"Benedenwoning",penthouse:"Penthouse",terraced:"Geschakelde woning",villa:"Villa","semi-detached":"Halfvrijstaande villa"};
const title=p=>`${labels[p.type]||"Woning"} in ${p.town}`;
const icon=(name)=>({bed:"â–±",bath:"â—«",area:"â–¡",plot:"â—‡",heart:"â™¡",heartOn:"â™¥",pin:"âŒ–",search:"âŒ•",map:"âŒ–",grid:"â–¦",close:"Ã—",back:"â€¹",next:"â€º"}[name]);
async function sendLead(property=""){const fields=[...document.querySelectorAll("input,textarea")].slice(-4);const [name,email,phone,message]=fields.map(x=>x?.value||"");const r=await fetch("/contact.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name,email,phone,message,property})});const d=await r.json();alert(d.message||"Bedankt voor uw aanvraag.")}

function useFavorites(){
  const [ids,setIds]=useState(()=>JSON.parse(localStorage.getItem("helder-favorites")||"[]"));
  const toggle=id=>setIds(old=>{const next=old.includes(id)?old.filter(x=>x!==id):[...old,id];localStorage.setItem("helder-favorites",JSON.stringify(next));return next});
  return [ids,toggle];
}
function Header({page,setPage,favorites}){
  return <><div className="topbar">Nederlandse begeleiding in Spanje <span>+34 600 000 000 Â· info@helderrealestate.nl</span></div>
  <header><button className="logo" onClick={()=>setPage("home")}><b>HELDER</b><small>REAL ESTATE</small></button><nav><button onClick={()=>setPage("properties")}>Woningen</button><button onClick={()=>setPage("map")}>Kaart</button><button onClick={()=>setPage("regions")}>Regio's</button><button onClick={()=>setPage("about")}>Over ons</button></nav><div className="actions"><button className="favorite-nav" onClick={()=>setPage("favorites")}>{icon("heart")}<i>{favorites.length}</i></button><button className="primary" onClick={()=>setPage("contact")}>Plan een gesprek</button></div></header></>
}
function FilterBar({filters,setFilters,onSearch,wide=false}){
 const change=k=>e=>setFilters({...filters,[k]:e.target.value});
 return <div className={`filters ${wide?"wide":""}`}><label>Locatie<input placeholder="Plaats, regio of referentie" value={filters.q} onChange={change("q")}/></label><label>Woningtype<select value={filters.type} onChange={change("type")}><option value="">Alle types</option>{Object.entries(labels).map(([v,l])=><option value={v} key={v}>{l}</option>)}</select></label><label>Min. prijs<select value={filters.min} onChange={change("min")}><option value="">Geen minimum</option><option value="200000">â‚¬ 200.000</option><option value="400000">â‚¬ 400.000</option><option value="750000">â‚¬ 750.000</option></select></label><label>Max. prijs<select value={filters.max} onChange={change("max")}><option value="">Geen maximum</option><option value="300000">â‚¬ 300.000</option><option value="500000">â‚¬ 500.000</option><option value="1000000">â‚¬ 1.000.000</option></select></label><label>Slaapkamers<select value={filters.beds} onChange={change("beds")}><option value="">Alle</option><option value="2">2+</option><option value="3">3+</option><option value="4">4+</option></select></label><button className="primary search" onClick={onSearch}>{icon("search")} Zoek woningen</button></div>
}
function Card({p,isFavorite,toggle,onOpen}){
 return <article className="card"><div className="card-img" onClick={()=>onOpen(p)}><img loading="lazy" src={p.image} alt={title(p)}/><span className="tag">{p.newBuild?"Nieuwbouw":"Herverkoop"}</span><span className="photo-count">â–§ {p.images?.length||1}</span></div><button className={`heart ${isFavorite?"on":""}`} onClick={()=>toggle(p.id)}>{isFavorite?icon("heartOn"):icon("heart")}</button><div className="card-copy" onClick={()=>onOpen(p)}><p className="location">{icon("pin")} {p.town}, {p.province}</p><h3>{title(p)}</h3><div className="specs"><span>{icon("bed")} {p.beds}</span><span>{icon("bath")} {p.baths}</span><span>{icon("area")} {p.built} mÂ²</span>{p.plot>0&&<span>{icon("plot")} {p.plot} mÂ²</span>}</div><strong>{money.format(p.price)}</strong><small>Ref. {p.ref}</small></div></article>
}
function PropertyGrid({items,favorites,toggle,onOpen,limit=24}){
 const [count,setCount]=useState(limit); useEffect(()=>setCount(limit),[items,limit]);
 return <><div className="cards">{items.slice(0,count).map(p=><Card key={p.id} p={p} isFavorite={favorites.includes(p.id)} toggle={toggle} onOpen={onOpen}/>)}</div>{count<items.length&&<div className="center"><button className="outline" onClick={()=>setCount(count+24)}>Meer woningen laden</button></div>}</>
}
function Home({properties,favorites,toggle,setPage,onOpen,filters,setFilters,runSearch}){
 const featured=properties.filter(p=>p.images?.length>8).slice(0,8);
 return <><section className="hero-v2"><div className="hero-content"><p className="kicker">Luxury real estate Â· Costa Blanca & Costa CÃ¡lida</p><h1>Vind uw plek<br/><em>onder de Spaanse zon.</em></h1><p>Een zorgvuldig geselecteerd woningaanbod en persoonlijke Nederlandse begeleiding, van oriÃ«ntatie tot sleuteloverdracht.</p></div><FilterBar filters={filters} setFilters={setFilters} onSearch={runSearch}/></section>
 <section className="promise"><div><b>896+</b><span>Actuele woningen</span></div><div><b>98</b><span>Spaanse plaatsen</span></div><div><b>100%</b><span>Persoonlijke begeleiding</span></div><div><b>Helder</b><span>Van zoeken tot kopen</span></div></section>
 <section className="section"><div className="heading"><div><p className="kicker dark">Nieuw in ons aanbod</p><h2>Woningen om verliefd op te worden</h2></div><button className="text-btn" onClick={()=>setPage("properties")}>Bekijk al het aanbod â†’</button></div><PropertyGrid items={featured} favorites={favorites} toggle={toggle} onOpen={onOpen} limit={8}/></section>
 <section className="split"><div className="split-img"></div><div><p className="kicker">Aankopen zonder zorgen</p><h2>Lokale expertise.<br/>Nederlandse helderheid.</h2><p>Een woning kopen in Spanje vraagt om goede begeleiding. Wij selecteren, vergelijken, organiseren bezichtigingen en begeleiden het volledige aankoopproces.</p><ul><li>Onafhankelijke woningselectie</li><li>Persoonlijk aankoopplan</li><li>Juridische en financiÃ«le begeleiding</li><li>Nazorg na de sleuteloverdracht</li></ul><button className="light-btn" onClick={()=>setPage("about")}>Ontdek onze werkwijze</button></div></section>
 <section className="section regions"><div className="heading"><div><p className="kicker dark">Ontdek de regio</p><h2>Waar wilt u thuiskomen?</h2></div></div><div className="region-cards"><button onClick={()=>{setFilters({...filters,q:"Alicante"});runSearch("Alicante")}}><span>Costa Blanca Zuid<small>Levendig, zonnig en bereikbaar</small></span></button><button onClick={()=>{setFilters({...filters,q:"Moraira"});runSearch("Moraira")}}><span>Costa Blanca Noord<small>Baaien, bergen en luxe</small></span></button><button onClick={()=>{setFilters({...filters,q:"Murcia"});runSearch("Murcia")}}><span>Costa CÃ¡lida<small>Authentiek en ontspannen</small></span></button></div></section>
 <section className="cta"><p className="kicker">Persoonlijk zoekprofiel</p><h2>Vertel ons wat u zoekt.<br/>Wij vinden wat bij u past.</h2><button className="light-btn" onClick={()=>setPage("contact")}>Start uw zoektocht</button></section></>
}
function Properties({items,filters,setFilters,runSearch,favorites,toggle,onOpen,setPage}){
 return <><section className="page-hero"><p className="kicker">Woningaanbod Spanje</p><h1>Vind uw droomwoning</h1><p>Ontdek {items.length} actuele woningen aan de Spaanse kust.</p></section><div className="sticky-filter"><FilterBar wide filters={filters} setFilters={setFilters} onSearch={runSearch}/></div><section className="listing section"><div className="result-head"><div><b>{items.length} woningen gevonden</b><span>Actueel aanbod uit onze HabiHub-koppeling</span></div><div><button className="active">{icon("grid")} Lijst</button><button onClick={()=>setPage("map")}>{icon("map")} Kaart</button></div></div><PropertyGrid items={items} favorites={favorites} toggle={toggle} onOpen={onOpen}/></section></>
}
function propertyImages(p){
 return [p.image,...(p.images||[])].filter(Boolean).filter((img,i,all)=>all.indexOf(img)===i);
}
function GalleryDisabled({p,index,setIndex,onClose}){
 const imgs=propertyImages(p), active=Math.min(index,imgs.length-1);
 const previous=()=>setIndex((active-1+imgs.length)%imgs.length), next=()=>setIndex((active+1)%imgs.length);
 useEffect(()=>{const onKey=e=>{if(e.key==="Escape")onClose();if(e.key==="ArrowLeft")previous();if(e.key==="ArrowRight")next()};window.addEventListener("keydown",onKey);return()=>window.removeEventListener("keydown",onKey)},[active,imgs.length]);
 return <div className="gallery-overlay" role="dialog" aria-modal="true"><button className="gallery-close" onClick={onClose} aria-label="Sluit fotogalerij">{icon("close")}</button><div className="gallery-stage"><button className="gallery-arrow left" onClick={previous} aria-label="Vorige foto">{icon("back")}</button><img src={imgs[active]} alt={`${title(p)} foto ${active+1}`}/><button className="gallery-arrow right" onClick={next} aria-label="Volgende foto">{icon("next")}</button></div><div className="gallery-footer"><button className="gallery-nav" onClick={previous}>Vorige</button><span>{active+1} / {imgs.length}</span><button className="gallery-nav" onClick={next}>Volgende</button><div className="gallery-thumbs">{imgs.map((img,i)=><button key={`${img}-${i}`} className={i===active?"active":""} onClick={()=>setIndex(i)} aria-label={`Toon foto ${i+1}`}><img src={img} alt="" loading="lazy"/></button>)}</div></div></div>
}
function Detail({p,onBack,isFavorite,toggle}){
 const imgs=propertyImages(p);
 return <main className="detail-page"><div className="detail-top"><button onClick={onBack}>Terug naar aanbod</button><div><button onClick={()=>toggle(p.id)}>{isFavorite?icon("heartOn"):icon("heart")} {isFavorite?"Bewaard":"Bewaar"}</button><button onClick={()=>navigator.clipboard?.writeText(location.href)}>Deel</button></div></div><section className="property-hero"><div className="property-hero-photo"><img src={imgs[0]} alt={title(p)}/></div><div className="property-hero-panel"><p className="kicker">{p.newBuild?"Nieuwbouw":"Herverkoop"} - Ref. {p.ref}</p><h1>{title(p)}</h1><p>{icon("pin")} {p.town}, {p.province}</p><strong>{money.format(p.price)}</strong><div><span>{icon("bed")} {p.beds} slaapkamers</span><span>{icon("bath")} {p.baths} badkamers</span><span>{icon("area")} {p.built} m2 wonen</span>{p.plot>0&&<span>{icon("plot")} {p.plot} m2 perceel</span>}</div></div></section><section className="detail-grid"><article><div className="description"><h2>Over deze woning</h2>{(p.description||"Neem contact met ons op voor alle informatie over deze woning.").split(/\n\n+/).slice(0,8).map((x,i)=><p key={i}>{x}</p>)}</div><div className="features"><h2>Kenmerken</h2><div>{(p.features||[]).map(x=><span key={x}>✓ {x}</span>)}</div></div><div className="map-placeholder"><span>{icon("pin")}</span><h3>{p.town}, {p.province}</h3><p>Exacte locatie en bezichtiging op aanvraag</p></div></article><aside><div className="contact-card"><p className="kicker dark">Interesse in deze woning?</p><h3>Ontvang alle informatie</h3><p>Wij nemen persoonlijk contact met u op.</p><input placeholder="Naam"/><input placeholder="E-mailadres"/><input placeholder="Telefoonnummer"/><textarea placeholder="Ik ontvang graag meer informatie over deze woning."></textarea><button className="primary">Informatie aanvragen</button><small>Of bel ons direct: +34 600 000 000</small></div></aside></section></main>
}
function MapView({items,onOpen}){return <section className="map-page"><aside><h2>{items.length} woningen op de kaart</h2><p>Selecteer een woning om details te bekijken.</p>{items.slice(0,15).map(p=><button key={p.id} onClick={()=>onOpen(p)}><img src={p.image}/><span><b>{title(p)}</b><small>{money.format(p.price)}</small></span></button>)}</aside><div className="fake-map"><div className="map-grid"></div>{items.slice(0,35).map((p,i)=><button key={p.id} style={{left:`${8+(i*17)%82}%`,top:`${8+(i*29)%80}%`}} onClick={()=>onOpen(p)}>{money.format(p.price).replace(".000","k")}</button>)}</div></section>}
function ContentPage({type,setPage}){
 const content={favorites:["Uw favorieten","Bewaar woningen met het hartje en vergelijk ze op uw gemak."],regions:["Regio's aan de Spaanse kust","Van bruisende kustplaatsen tot rustige golfresorts: ontdek welke omgeving bij u past."],about:["Helder kopen in Spanje","Wij combineren lokale marktkennis met Nederlandse duidelijkheid en begeleiden u bij iedere stap."],contact:["Laten we kennismaken","Vertel ons uw woonwensen. Wij nemen persoonlijk contact met u op."]}[type];
 return <><section className="page-hero"><p className="kicker">Helder Real Estate</p><h1>{content[0]}</h1><p>{content[1]}</p></section>{type==="contact"&&<section className="contact-page"><div><h2>Vertel ons wat u zoekt</h2><p>Van eerste oriÃ«ntatie tot sleuteloverdracht: wij helpen u persoonlijk verder.</p><b>info@helderrealestate.nl</b><b>+34 600 000 000</b></div><form><input placeholder="Naam"/><input placeholder="E-mailadres"/><input placeholder="Telefoonnummer"/><select><option>Ik wil een woning kopen</option><option>Ik wil mijn woning verkopen</option><option>Ik heb een algemene vraag</option></select><textarea placeholder="Vertel ons over uw woonwensen"></textarea><button type="button" className="primary">Verstuur aanvraag</button></form></section>}{type==="about"&&<section className="section prose"><h2>Van droom naar sleutel</h2><p>Helder Real Estate helpt Nederlandstalige kopers bij het vinden en aankopen van een woning in Spanje. Wij beginnen met luisteren, zoeken gericht en zorgen dat u bij iedere stap precies weet waar u aan toe bent.</p><div className="steps"><div><b>01</b><h3>Kennismaken</h3><p>Uw wensen, budget en planning helder in beeld.</p></div><div><b>02</b><h3>Selecteren</h3><p>Een persoonlijke selectie uit het actuele aanbod.</p></div><div><b>03</b><h3>Bezichtigen</h3><p>Een efficiÃ«nt programma met deskundige begeleiding.</p></div><div><b>04</b><h3>Aankopen</h3><p>Onderhandeling, controle en sleuteloverdracht.</p></div></div></section>}</>
}
function Footer({setPage}){return <footer><div className="logo light-logo"><b>HELDER</b><small>REAL ESTATE</small></div><p>Persoonlijke aankoopbegeleiding aan de Spaanse kust.</p><div><button onClick={()=>setPage("properties")}>Woningen</button><button onClick={()=>setPage("about")}>Over ons</button><button onClick={()=>setPage("contact")}>Contact</button></div><small>Â© 2026 Helder Real Estate</small></footer>}
function App(){
 const [properties,setProperties]=useState([]),[settings,setSettings]=useState({}),[page,setPage]=useState("home"),[selected,setSelected]=useState(null),[favorites,toggle]=useFavorites(),[filters,setFilters]=useState({q:"",type:"",min:"",max:"",beds:""});
 useEffect(()=>{fetch("/data/properties.json").then(r=>r.json()).then(setProperties)},[]);
 useEffect(()=>{fetch("/api.php?path=settings").then(r=>r.json()).then(setSettings)},[]);
 useEffect(()=>{setTimeout(()=>{const top=document.querySelector(".topbar span"),h=document.querySelector(".hero-content h1"),p=document.querySelector(".hero-content>p:last-child");if(top)top.textContent=`${settings.phone||"+34 600 000 000"} Â· ${settings.email||"info@helderrealestate.nl"}`;if(h&&settings.hero_title)h.textContent=settings.hero_title;if(p&&settings.hero_text)p.textContent=settings.hero_text},0)},[settings,page]);
 useEffect(()=>window.scrollTo(0,0),[page,selected]);
 useEffect(()=>{const submit=async e=>{const text=e.target?.textContent?.trim();if(!["Informatie aanvragen","Verstuur aanvraag"].includes(text))return;const box=e.target.closest(".contact-card,form");const values=[...box.querySelectorAll("input,textarea")].map(x=>x.value);const [name,email,phone,message]=values;try{const r=await fetch("/contact.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name,email,phone,message,property:selected?`${title(selected)} Â· ${selected.ref}`:"Algemene aanvraag"})});const d=await r.json();alert(d.message)}catch{alert("De aanvraag kon niet worden verzonden. Mail ons via info@helderrealestate.nl.")}};document.addEventListener("click",submit);return()=>document.removeEventListener("click",submit)},[page,selected]);
 const filtered=useMemo(()=>properties.filter(p=>{const q=filters.q.toLowerCase();return(!q||`${p.town} ${p.province} ${p.ref} ${p.type}`.toLowerCase().includes(q))&&(!filters.type||p.type===filters.type)&&(!filters.min||p.price>=+filters.min)&&(!filters.max||p.price<=+filters.max)&&(!filters.beds||p.beds>=+filters.beds)}),[properties,filters]);
 const runSearch=q=>{if(typeof q==="string")setFilters(f=>({...f,q}));setPage("properties")}, open=p=>setSelected(p);
 if(selected)return <><Header page={page} setPage={p=>{setSelected(null);setPage(p)}} favorites={favorites}/><Detail p={selected} onBack={()=>setSelected(null)} isFavorite={favorites.includes(selected.id)} toggle={toggle}/><Footer setPage={setPage}/></>;
 let body=page==="home"?<Home properties={properties} favorites={favorites} toggle={toggle} setPage={setPage} onOpen={open} filters={filters} setFilters={setFilters} runSearch={runSearch}/>:page==="properties"?<Properties items={filtered} filters={filters} setFilters={setFilters} runSearch={runSearch} favorites={favorites} toggle={toggle} onOpen={open} setPage={setPage}/>:page==="map"?<MapView items={filtered} onOpen={open}/>:page==="favorites"?<><ContentPage type="favorites" setPage={setPage}/><section className="section"><PropertyGrid items={properties.filter(p=>favorites.includes(p.id))} favorites={favorites} toggle={toggle} onOpen={open}/>{!favorites.length&&<div className="empty"><h2>Nog geen favorieten</h2><p>Klik op het hartje bij een woning om deze hier te bewaren.</p><button className="primary" onClick={()=>setPage("properties")}>Bekijk woningen</button></div>}</section></>:<ContentPage type={page} setPage={setPage}/>;
 return <><Header page={page} setPage={setPage} favorites={favorites}/>{body}<Footer setPage={setPage}/></>
}
ReactDOM.createRoot(document.getElementById("root")).render(<App/>);

