/* ============ Bhoomi Pooja stamp ============ */
function PujaStamp() {
  return (
    <div className="puja-stamp">
      <span className="k">Bhumi Pooja Performed</span>
      <b>12 · 12 · 2024</b>
      <span className="s">Pre-launch bookings now open</span>
    </div>
  );
}

/* ============ Amenities — Photo Edition ============ */
function Amenities() {
  /* Unsplash free-license lifestyle photos — one per amenity */
  const photos = {
    gym:    "https://images.unsplash.com/photo-1571019614242-c5c5dee9f50b?w=640&h=440&q=82&auto=format&fit=crop",
    garden: "https://images.unsplash.com/photo-1585320806297-9794b3e4eeae?w=640&h=440&q=82&auto=format&fit=crop",
    yoga:   "https://images.unsplash.com/photo-1506126613408-eca07ce68773?w=640&h=440&q=82&auto=format&fit=crop",
    bbq:    "https://images.unsplash.com/photo-1555396273-367ea4eb4db5?w=640&h=440&q=82&auto=format&fit=crop",
    star:   "https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=640&h=440&q=82&auto=format&fit=crop",
    gazebo: "https://images.unsplash.com/photo-1600210492493-0946911123ea?w=640&h=440&q=82&auto=format&fit=crop",
    track:  "https://images.unsplash.com/photo-1476480862126-209bfaa8edc8?w=640&h=440&q=82&auto=format&fit=crop",
  };
  const hero = "https://images.unsplash.com/photo-1600585154526-990dced4db0d?w=1600&h=680&q=88&auto=format&fit=crop";

  return (
    <div className="reveal amen-wrap" style={{marginTop:"30px"}}>

      {/* ── Rooftop hero banner ── */}
      <div className="amen-hero" style={{backgroundImage:`url(${hero})`}}>
        <div className="amen-hero-inner">
          <span className="eyebrow light" style={{justifyContent:"center",display:"flex"}}>Rooftop Living · Srivari Empire</span>
          <h2 className="amen-hero-h">A terrace built<br/>for the good life</h2>
          <p className="amen-hero-p">An entire rooftop given over to wellness, leisure and gathering — high above Madhurawada.</p>
        </div>
      </div>

      {/* ── "LIFESTYLE AMENITIES" title bar ── */}
      <div className="amen-bar">
        <span className="amen-bar-line"/>
        <span className="amen-bar-txt">✦&nbsp;&nbsp;LIFESTYLE AMENITIES&nbsp;&nbsp;✦</span>
        <span className="amen-bar-line amen-bar-line--r"/>
      </div>

      {/* ── Photo card grid ── */}
      <div className="amen-pgrid">
        {SITE.amenities.map(function(a, i){
          return (
            <div
              key={i}
              className="amen-pc"
              style={{backgroundImage:`url(${photos[a.icon]})`}}
            >
              <div className="amen-pc-body">
                <span className="amen-pc-ic"><Icon name={a.icon} size={30} stroke={1.5}/></span>
                <h4 className="amen-pc-h">{a.t}</h4>
                <p className="amen-pc-p">{a.d}</p>
              </div>
            </div>
          );
        })}
      </div>

    </div>
  );
}

/* ============ Floor-plan viewer — pinch-zoom, keyboard, unit hotspots ============ */
function FloorPlanViewer() {
  const [scale, setScale] = React.useState(1);
  const [tx, setTx] = React.useState(0);
  const [ty, setTy] = React.useState(0);
  const [fs, setFs] = React.useState(false);
  const [activeUnit, setActiveUnit] = React.useState(null);
  const drag = React.useRef(null);
  const pinch = React.useRef(null);
  const stageRef = React.useRef(null);
  const scaleRef = React.useRef(1);

  const MIN = 1, MAX = 8;
  const cl = (v,a,b)=>Math.max(a,Math.min(b,v));

  const reset = ()=>{ setScale(1); scaleRef.current=1; setTx(0); setTy(0); setActiveUnit(null); };

  const zoomAt = (factor, ox, oy)=>{
    setScale(prev=>{
      const ns = cl(+(prev*factor).toFixed(3), MIN, MAX);
      scaleRef.current = ns;
      if(ns===1){ setTx(0); setTy(0); return 1; }
      if(ox!=null){
        setTx(t=> t + (ox - t)*(1 - ns/prev));
        setTy(t=> t + (oy - t)*(1 - ns/prev));
      }
      return ns;
    });
  };

  /* --- Wheel zoom anchored to cursor --- */
  const onWheel = (e)=>{
    e.preventDefault();
    const rect = stageRef.current.getBoundingClientRect();
    const ox = e.clientX - rect.left - rect.width/2;
    const oy = e.clientY - rect.top  - rect.height/2;
    zoomAt(e.deltaY < 0 ? 1.18 : 1/1.18, ox, oy);
  };

  /* --- Mouse drag --- */
  const onMouseDown = (e)=>{
    if(scale<=1) return;
    drag.current = {x:e.clientX, y:e.clientY, tx, ty};
  };
  const onMouseMove = (e)=>{
    if(!drag.current) return;
    setTx(drag.current.tx + (e.clientX - drag.current.x));
    setTy(drag.current.ty + (e.clientY - drag.current.y));
  };
  const onMouseUp = ()=>{ drag.current=null; };

  /* --- Touch: single-finger pan + two-finger pinch-zoom --- */
  const onTouchStart = (e)=>{
    if(e.touches.length===2){
      e.preventDefault();
      const dist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      const rect = stageRef.current.getBoundingClientRect();
      const mcx = (e.touches[0].clientX + e.touches[1].clientX)/2 - rect.left - rect.width/2;
      const mcy = (e.touches[0].clientY + e.touches[1].clientY)/2 - rect.top  - rect.height/2;
      pinch.current = {dist, scale:scaleRef.current, tx, ty, mcx, mcy};
      drag.current = null;
    } else if(e.touches.length===1){
      pinch.current = null;
      if(scaleRef.current<=1) return;
      drag.current = {x:e.touches[0].clientX, y:e.touches[0].clientY, tx, ty};
    }
  };
  const onTouchMove = (e)=>{
    e.preventDefault();
    if(e.touches.length===2 && pinch.current){
      const dist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      const ns = cl(+(pinch.current.scale*(dist/pinch.current.dist)).toFixed(3), MIN, MAX);
      scaleRef.current = ns;
      setScale(ns);
      if(ns===1){ setTx(0); setTy(0); }
    } else if(e.touches.length===1 && drag.current){
      setTx(drag.current.tx + (e.touches[0].clientX - drag.current.x));
      setTy(drag.current.ty + (e.touches[0].clientY - drag.current.y));
    }
  };
  const onTouchEnd = ()=>{ drag.current=null; pinch.current=null; };

  /* --- Keyboard controls --- */
  React.useEffect(()=>{
    const PAN = 50;
    const k = (e)=>{
      if(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA') return;
      if(e.key==='Escape'){ setFs(false); reset(); return; }
      if(e.key==='+'||e.key==='=') zoomAt(1.35);
      if(e.key==='-') zoomAt(1/1.35);
      if((e.key==='r'||e.key==='R')&&scaleRef.current>1) reset();
      if(scaleRef.current>1){
        if(e.key==='ArrowLeft')  { e.preventDefault(); setTx(t=>t+PAN); }
        if(e.key==='ArrowRight') { e.preventDefault(); setTx(t=>t-PAN); }
        if(e.key==='ArrowUp')    { e.preventDefault(); setTy(t=>t+PAN); }
        if(e.key==='ArrowDown')  { e.preventDefault(); setTy(t=>t-PAN); }
      }
    };
    window.addEventListener('keydown', k);
    return ()=>window.removeEventListener('keydown', k);
  }, []);

  /* --- 8 unit hotspots (percentage positions on floorAerial image) --- */
  const units = [
    {id:'A', x:11, y:27, facing:'East'},
    {id:'B', x:36, y:27, facing:'West'},
    {id:'C', x:63, y:27, facing:'East'},
    {id:'D', x:88, y:27, facing:'West'},
    {id:'E', x:11, y:73, facing:'West'},
    {id:'F', x:36, y:73, facing:'East'},
    {id:'G', x:63, y:73, facing:'West'},
    {id:'H', x:88, y:73, facing:'East'},
  ];

  const stage = (
    <div
      ref={stageRef}
      className={`fpz-stage ${scale>1?"zoomed":""}`}
      onWheel={onWheel}
      onMouseDown={onMouseDown} onMouseMove={onMouseMove}
      onMouseUp={onMouseUp} onMouseLeave={onMouseUp}
      onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd}
      onDoubleClick={()=>scale>1 ? reset() : zoomAt(2.5)}
      tabIndex={0}
    >
      <img
        className="fpz-img"
        src={SITE.images.floorAerial}
        alt="Srivari Empire — 3D aerial floor plan, 8 residences"
        draggable="false"
        style={{transform:`translate(${tx}px,${ty}px) scale(${scale})`}}
      />

      {/* Unit hotspots — same transform as image so they track correctly */}
      <div className="fpz-units" style={{transform:`translate(${tx}px,${ty}px) scale(${scale})`}}>
        {units.map(u=>(
          <button key={u.id}
            className={`fpz-unit-btn ${activeUnit===u.id?'active':''}`}
            style={{left:u.x+'%', top:u.y+'%'}}
            onMouseDown={e=>e.stopPropagation()}
            onClick={e=>{e.stopPropagation(); setActiveUnit(activeUnit===u.id?null:u.id);}}
            aria-label={`Unit ${u.id} — 3 BHK 1600 sft`}
          >
            <span className="fpz-dot"/>
            {activeUnit===u.id && (
              <div className="fpz-tip">
                <b>Unit {u.id}</b>
                <span>3 BHK · 1600 sft</span>
                <span>{u.facing}-facing</span>
              </div>
            )}
          </button>
        ))}
      </div>

      <span className="fpz-tag">3D AERIAL VIEW · 8 RESIDENCES / FLOOR</span>
      <span className="fpz-zlevel">{scale===1?'1.0':scale.toFixed(1)}×</span>

      <div className="fpz-controls" onMouseDown={e=>e.stopPropagation()}>
        <button onClick={()=>zoomAt(1.4)} aria-label="Zoom in">+</button>
        <button onClick={()=>zoomAt(1/1.4)} aria-label="Zoom out">−</button>
        <button onClick={reset} aria-label="Reset">Reset</button>
        <button onClick={()=>setFs(true)} aria-label="Fullscreen" className="exp">⤢</button>
      </div>
      <span className="fpz-hint">
        {scale>1
          ? "Drag · ←→↑↓ keys · R to reset · tap unit dots to explore"
          : "Scroll · pinch · or tap + to zoom · tap ● dots to explore units"}
      </span>
    </div>
  );

  return (
    <div className="reveal" style={{marginTop:"clamp(64px,9vw,110px)"}}>
      <div className="sec-head">
        <span className="eyebrow">Explore The Plan</span>
        <h2 className="section-title">A 3D floor plan you can zoom right into</h2>
        <p>Eight 3 BHK residences of 1600 sft on a 40&apos;0&quot; wide road. Pinch or scroll to zoom, drag to pan, tap the gold dots to explore each unit.</p>
      </div>
      <div className="fpz">
        {stage}
        <div className="fpz-side">
          <div className="fpz-spec">
            <span className="n">3 BHK</span>
            <div><b>1600 sft</b><span>Per residence</span></div>
          </div>
          <ul className="fpz-list">
            <li><span className="ic"><Icon name="check" size={16}/></span>Dedicated Pooja niche in every home</li>
            <li><span className="ic"><Icon name="check" size={16}/></span>Wide balconies &amp; a 6&apos;6&quot; corridor</li>
            <li><span className="ic"><Icon name="check" size={16}/></span>8 residences per floor, cross-ventilated</li>
            <li><span className="ic"><Icon name="check" size={16}/></span>40&apos;0&quot; wide road frontage</li>
          </ul>
          <a className="btn btn-gold" href={SITE.brochure} download>
            <Icon name="download" size={16}/> Download Floor Plan &amp; Brochure
          </a>
        </div>
      </div>
      {fs && (
        <div className="fpz-modal" onClick={()=>setFs(false)}>
          <button className="fpz-close" onClick={()=>setFs(false)} aria-label="Close">×</button>
          <div className="fpz-modal-stage" onClick={e=>e.stopPropagation()}>{stage}</div>
        </div>
      )}
    </div>
  );
}

/* ============ Specs accordion ============ */
function SpecRow({ icon, t, d, open, onToggle }) {
  const ref = React.useRef(null);
  return (
    <div className={`spec-row ${open?"open":""}`}>
      <button className="spec-q" onClick={onToggle} aria-expanded={open}>
        <b><span className="si"><Icon name={icon} size={22} stroke={1.4}/></span>{t}</b>
        <span className="pm">+</span>
      </button>
      <div className="spec-a" style={{maxHeight: open ? (ref.current ? ref.current.scrollHeight+4 : 400)+"px" : 0}}>
        <div className="spec-a-inner" ref={ref}>{d}</div>
      </div>
    </div>
  );
}
function SpecsAccordion() {
  const [open, setOpen] = React.useState(()=>new Set([0]));
  const toggle = (idx)=> setOpen(prev=>{ const n=new Set(prev); n.has(idx)?n.delete(idx):n.add(idx); return n; });
  const left = SITE.specs.slice(0, Math.ceil(SITE.specs.length/2));
  const right = SITE.specs.slice(Math.ceil(SITE.specs.length/2));
  return (
    <div className="reveal" style={{marginTop:"clamp(64px,9vw,110px)"}}>
      <div className="sec-head">
        <span className="eyebrow">Specifications</span>
        <h2 className="section-title">Specified to the last fitting</h2>
        <p>Brand-name materials, honestly listed — exactly as written in our brochure. Tap any line to read the detail.</p>
      </div>
      <div className="specs">
        <div>{left.map((s,idx)=><SpecRow key={idx} {...s} open={open.has(idx)} onToggle={()=>toggle(idx)}/>)}</div>
        <div>{right.map((s,idx)=>{const gi=idx+left.length;return <SpecRow key={gi} {...s} open={open.has(gi)} onToggle={()=>toggle(gi)}/>;})}</div>
      </div>
    </div>
  );
}

/* ============ Location ============ */
function Location() {
  return (
    <div className="reveal" style={{marginTop:"clamp(64px,9vw,110px)"}}>
      <div className="sec-head">
        <span className="eyebrow">The Address</span>
        <h2 className="section-title">Madhurawada — at the centre of it all</h2>
        <p>Midhilapuri, VUDA Colony — minutes from the highway, the IT hub and the beach corridor.</p>
      </div>
      <div className="loc">
        <ul className="loc-list">
          {SITE.location.map((l,i)=>(
            <li key={i}>
              <span className="loc-km">{l.km}<span> {l.u}</span></span>
              <span className="loc-name">{l.n}</span>
            </li>
          ))}
        </ul>
        <div className="loc-map">
          <iframe src={SITE.mapEmbed} title="Srivari Empire location" loading="lazy" referrerPolicy="no-referrer-when-downgrade"></iframe>
        </div>
      </div>
    </div>
  );
}

/* ============ Flagship wrapper ============ */
function SrivariFlagship() {
  return (
    <section className="flagship" id="srivari">
      <div className="flag-render">
        <img src={SITE.images.render} alt="Srivari Empire elevation render" />
        <div className="flag-overlay">
          <span className="eyebrow light">Flagship · Under Construction</span>
          <h2>Srivari Empire</h2>
          <div className="meta">
            <span><b>3 BHK</b> Deluxe</span>
            <span><b>1600</b> sft</span>
            <span><b>40</b> Residences</span>
            <span><Icon name="pin" size={15}/> Madhurawada, Vizag</span>
          </div>
        </div>
        <div className="flag-badge"><PujaStamp/></div>
      </div>
      <div className="wrap section-pad">
        <Amenities/>
        <FloorPlanViewer/>
        <SpecsAccordion/>
        <Location/>
        <div className="reveal" style={{marginTop:"clamp(56px,8vw,96px)",textAlign:"center",borderTop:"1px solid var(--line)",paddingTop:"clamp(48px,7vw,80px)"}}>
          <span className="eyebrow center">Reserve Your Home</span>
          <h2 className="section-title" style={{margin:".3em 0 .6em"}}>Come see it for yourself</h2>
          <p className="lead" style={{maxWidth:"46ch",margin:"0 auto 1.8em"}}>Pre-launch bookings are open. Walk the site, study the plans and reserve your preferred unit.</p>
          <div style={{display:"flex",gap:"14px",justifyContent:"center",flexWrap:"wrap",alignItems:"center"}}>
            <a className="btn btn-primary" href={waLink()} target="_blank" rel="noopener noreferrer"><Icon name="whatsapp" size={16}/> Book a Site Visit</a>
            <a className="btn btn-outline" href={SITE.brochure} download><Icon name="download" size={15}/> Download Brochure</a>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PujaStamp, Amenities, FloorPlanViewer, SpecsAccordion, Location, SrivariFlagship });
