// Inventory · Choice — the entry screen at #/inventory.
// Two routes into the address, now as cinematic full-bleed image cards:
//   • "Choose Tower"  → towers  (the 10-tower master-plan selector) — DOMINANT
//     ~70% card carrying the REAL master plan (client 2026-07-08): the aerial
//     photo + the 10 authored gradient tower cutouts from window.TOWER_GEO,
//     alive with the same SMIL stop-color cycling the #/towers screen runs,
//     slow Ken-Burns drift, LIVE availability read straight off the CRM
//     inventory feed (data.jsx). Falls back to the flat render if TOWER_GEO
//     is unavailable.
//   • "Explore G+2 Floors" → gplus (Ground/First/Second podium explorer) — ~30%
//     card, vertical aerial of the amenity courtyard.
// Header, back button, breadcrumb and top-right brand lockup match the other
// inside screens (FloorSelect / FloorPlate / Inventory). Every label is real
// HTML — no baked text images. Imagery degrades gracefully (onError hides the
// img and each card still reads on its cream base).

const IVC_KEYS_ID = 'uni-invchoice-keys-v2';
function ensureIvcKeys() {
  if (typeof document === 'undefined' || document.getElementById(IVC_KEYS_ID)) return;
  const s = document.createElement('style');
  s.id = IVC_KEYS_ID;
  s.textContent = `
    @keyframes ivcUp    { from { opacity:0; transform: translateY(28px); } to { opacity:1; transform: translateY(0); } }
    /* slow, tasteful Ken-Burns drift — transform only, 28s loop, very subtle */
    @keyframes ivcKen   { 0% { transform: scale(1.06) translate3d(0,0,0); } 100% { transform: scale(1.15) translate3d(-1.6%,-1.4%,0); } }
    @keyframes ivcPulse { 0%,100% { transform: scale(1); opacity:1; } 50% { transform: scale(2.1); opacity:0; } }

    .ivc-card  { transition: box-shadow 300ms ease, transform 200ms cubic-bezier(0.22,1,0.36,1); }
    .ivc-card:active { transform: scale(0.98); }
    .ivc-media { transition: transform 700ms cubic-bezier(0.22,1,0.36,1); }
    .ivc-img   { will-change: transform; }
    .ivc-img.ivc-ken { animation: ivcKen 28s ease-in-out infinite alternate; }
    .ivc-frame { transition: border-color 300ms ease, box-shadow 300ms ease; }
    .ivc-arrow { transition: transform 320ms cubic-bezier(0.22,1,0.36,1), background 260ms ease, color 260ms ease, border-color 260ms ease; }
    .ivc-scrim { transition: opacity 320ms ease; }

    .ivc-card:hover              { box-shadow: 0 46px 100px rgba(40,28,10,0.34); }
    .ivc-card:hover .ivc-media   { transform: scale(1.025); }
    .ivc-card:hover .ivc-frame   { border-color: rgba(224,184,110,0.85); box-shadow: inset 0 0 0 1px rgba(255,240,205,0.30); }
    .ivc-card:hover .ivc-scrim   { opacity: 0.86; }
    .ivc-card:hover .ivc-arrow   { transform: translateX(8px); background: var(--gold); color:#241a0a; border-color: var(--gold); }

    /* live-plan cover box: centered, height-bound (card aspect is always taller
       than the 1672/941 photo) — the drift keyframe must carry the centering
       translateX so the two transforms don't fight. */
    .ivc-plan { position:absolute; top:0; bottom:0; left:50%; height:100%; aspect-ratio: 1672 / 941; transform: translateX(-50%) scale(1.04); }
    .ivc-plan.ivc-ken { animation: ivcKenPlan 30s ease-in-out infinite alternate; }
    @keyframes ivcKenPlan { 0% { transform: translateX(-50%) scale(1.05); } 100% { transform: translateX(-51.4%) scale(1.13); } }
    @media (prefers-reduced-motion: reduce){ .ivc-img.ivc-ken, .ivc-plan.ivc-ken { animation: none; } }
  `;
  document.head.appendChild(s);
}

// ── The REAL living master plan, framed inside the Choose Tower card ─────────
// Photo + the 10 verbatim tower cutouts (authored userSpaceOnUse gradients from
// the client SVG), breathing with staggered SMIL stop-color cycles — the same
// life the #/towers screen has, purely decorative here (the card is the button).
function LivePlanMedia() {
  const GEO = (typeof window !== 'undefined' && window.TOWER_GEO) || null;
  if (!GEO) return null;
  const reduce = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const IDS = Object.keys(GEO.towers);
  return (
    <div className="ivc-plan ivc-ken" aria-hidden="true">
      <img src="assets/masterplan/tower-photo.jpg" alt="" draggable="false"
        onError={(ev)=>{ ev.currentTarget.style.display = 'none'; }}
        style={{position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'fill', userSelect:'none'}}/>
      <svg viewBox={`0 0 ${GEO.W} ${GEO.H}`} preserveAspectRatio="none"
        style={{position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none'}}>
        <defs>
          {IDS.map((id, i) => {
            const g = GEO.towers[id].grad;
            const cyc = 7 + (i % 5) * 1.5;
            return (
              <linearGradient key={id} id={`ivcGrad-${id}`} gradientUnits="userSpaceOnUse"
                x1={g.x1} y1={g.y1} x2={g.x2} y2={g.y2}>
                {g.stops.map((st, si) => {
                  const cycle = g.stops.map(x => x[1]); cycle.push(cycle[0]);
                  const rolled = cycle.slice(si).concat(cycle.slice(1, si + 1));
                  return (
                    <stop key={si} offset={st[0]} stopColor={st[1]}>
                      {!reduce && <animate attributeName="stop-color" values={rolled.join(';')} dur={`${cyc}s`} repeatCount="indefinite"/>}
                    </stop>
                  );
                })}
              </linearGradient>
            );
          })}
        </defs>
        {IDS.map((id, i) => {
          const T = GEO.towers[id];
          const shape = T.kind === 'path'
            ? <path d={T.data} fill={`url(#ivcGrad-${id})`} fillOpacity="0.5">
                {!reduce && <animate attributeName="fill-opacity" values="0.42;0.6;0.42" dur={`${5.5 + (i % 4)}s`} begin={`${i * 0.5}s`} repeatCount="indefinite"/>}
              </path>
            : <polygon points={T.data} fill={`url(#ivcGrad-${id})`} fillOpacity="0.5">
                {!reduce && <animate attributeName="fill-opacity" values="0.42;0.6;0.42" dur={`${5.5 + (i % 4)}s`} begin={`${i * 0.5}s`} repeatCount="indefinite"/>}
              </polygon>;
          return (
            <g key={id}>
              {shape}
              {/* hairline leader + tiny letter disc at the client's label anchor */}
              <line x1={T.cx} y1={T.cy} x2={T.label[0]} y2={T.label[1]} stroke="#c9a05e" strokeWidth="1" opacity="0.55"/>
              <g transform={`translate(${T.label[0]} ${T.label[1]})`} opacity="0.9">
                <circle r="15" fill="rgba(12,11,8,0.68)" stroke="#e0b86e" strokeWidth="1.2"/>
                <text x="0" y="5.5" textAnchor="middle" fontFamily="Cinzel, serif" fontSize="16" fontWeight="600" fill="#f4dda0">{id}</text>
              </g>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function ChoiceCard({ img, imgPos, ken, media, index, kicker, title, sub, badge, onGo, delay, glyph, flex, pad, titleSize }) {
  return (
    <button className="ivc-card" onClick={onGo} aria-label={title}
      style={{position:'relative', flex, minWidth:0, height:'100%', borderRadius:34, overflow:'hidden', cursor:'pointer',
        border:'none', background:'#2a2118', textAlign:'left', padding:0, color:'#fdf7ea',
        boxShadow:'0 34px 84px rgba(40,28,10,0.24)',
        animation:`ivcUp .82s cubic-bezier(0.22,1,0.36,1) ${delay}s both`}}>

      {/* full-bleed media: the live plan when provided, else the flat render
          (cover). Falls back to the warm base if missing. */}
      <div className="ivc-media" style={{position:'absolute', inset:0, overflow:'hidden'}}>
        {media || (
          <img className={'ivc-img' + (ken ? ' ivc-ken' : '')} src={img} alt="" aria-hidden="true"
            draggable="false"
            onError={(ev)=>{ ev.currentTarget.style.display = 'none'; }}
            style={{position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover',
              objectPosition: imgPos || 'center', transform: ken ? undefined : 'scale(1.04)', userSelect:'none'}}/>
        )}
      </div>

      {/* dark scrim — anchors the ivory serif titles to the imagery, top + bottom */}
      <div className="ivc-scrim" aria-hidden="true" style={{position:'absolute', inset:0,
        background:'linear-gradient(180deg, rgba(8,6,3,0.60) 0%, rgba(8,6,3,0.14) 20%, rgba(10,7,3,0) 44%, rgba(10,7,3,0.48) 68%, rgba(6,4,2,0.90) 100%)'}}/>
      {/* faint warm gold cast in the top-right corner (calm) */}
      <div aria-hidden="true" style={{position:'absolute', inset:0,
        background:'radial-gradient(120% 82% at 84% 6%, rgba(224,184,110,0.22) 0%, rgba(224,184,110,0) 48%)'}}/>

      {/* gold hairline frame, inset */}
      <div className="ivc-frame" aria-hidden="true" style={{position:'absolute', inset:14, borderRadius:22,
        border:'1px solid rgba(224,184,110,0.42)', pointerEvents:'none'}}/>

      <div style={{position:'relative', height:'100%', display:'flex', flexDirection:'column', justifyContent:'space-between', padding:pad}}>
        {/* top: index + glyph + kicker + (optional) live badge */}
        <div style={{display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:24}}>
          <div style={{display:'flex', flexDirection:'column', gap:22}}>
            <div style={{display:'flex', alignItems:'center', gap:20}}>
              <span style={{width:74, height:74, borderRadius:20, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
                background:'rgba(255,247,232,0.10)', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)',
                border:'1.5px solid rgba(232,205,147,0.85)', color:'#f4dda0',
                boxShadow:'inset 0 1px 0 rgba(255,255,255,0.22)'}}>
                {glyph}
              </span>
              <div className="mono" style={{fontSize:15, letterSpacing:'0.32em', color:'#e8cd93', textShadow:'0 1px 10px rgba(0,0,0,0.55)'}}>{kicker}</div>
            </div>
            {badge}
          </div>
          <span className="serif" style={{fontSize:78, fontWeight:300, lineHeight:0.9, color:'rgba(255,250,238,0.18)', letterSpacing:'-0.02em', textShadow:'0 2px 20px rgba(0,0,0,0.4)'}}>{index}</span>
        </div>

        {/* bottom: title + sub + arrow */}
        <div>
          <div className="serif" style={{fontSize:titleSize, fontWeight:300, letterSpacing:'-0.022em', lineHeight:1.0, color:'#fdf7ea', textShadow:'0 2px 26px rgba(0,0,0,0.55)'}}>{title}</div>
          <div style={{display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:24, marginTop:24}}>
            <div style={{fontSize:23, color:'rgba(253,247,234,0.86)', fontStyle:'italic', lineHeight:1.4, maxWidth:'78%', textShadow:'0 1px 14px rgba(0,0,0,0.5)'}}>{sub}</div>
            <span className="ivc-arrow" style={{width:74, height:74, borderRadius:'50%', flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
              border:'1.5px solid rgba(255,247,232,0.72)', background:'rgba(255,247,232,0.14)', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)', color:'#fdf7ea'}}>
              <Icons.arrow width={30} height={30}/>
            </span>
          </div>
        </div>
      </div>
    </button>
  );
}

// Live-availability badge for the tower card — reads the SAME CRM feed the
// Inventory map does (TOWERS × towerSummary + useInventory). Falls back to a
// calm "600 RESIDENCES" while the feed is still loading.
function LiveAvailBadge({ ready, available, total }) {
  return (
    <div style={{display:'inline-flex', alignItems:'center', gap:13, alignSelf:'flex-start',
      padding:'11px 20px 11px 16px', borderRadius:100,
      background:'rgba(8,6,3,0.42)', backdropFilter:'blur(10px)', WebkitBackdropFilter:'blur(10px)',
      border:'1px solid rgba(232,205,147,0.42)', boxShadow:'inset 0 1px 0 rgba(255,255,255,0.12)'}}>
      <span style={{position:'relative', width:11, height:11, flexShrink:0}}>
        {ready && <span style={{position:'absolute', inset:0, borderRadius:'50%', background:STATUS.available.dot, animation:'ivcPulse 2.4s cubic-bezier(0.22,1,0.36,1) infinite'}}/>}
        <span style={{position:'absolute', inset:0, borderRadius:'50%', background:STATUS.available.dot, boxShadow:`0 0 10px ${STATUS.available.dot}`}}/>
      </span>
      <span className="mono" style={{fontSize:14.5, letterSpacing:'0.14em', color:'#fdf7ea'}}>
        {ready
          ? (<><strong style={{fontWeight:700, color:'#fff8e6'}}>{available}</strong> <span style={{color:'rgba(253,247,234,0.6)'}}>OF</span> {total} RESIDENCES <span style={{color:STATUS.available.dot}}>AVAILABLE</span></>)
          : (<><strong style={{fontWeight:700, color:'#fff8e6'}}>{total}</strong> RESIDENCES</>)}
      </span>
    </div>
  );
}

function InvChoice() {
  ensureIvcKeys();
  const t = useLoop();
  const e = clamp(t/0.5);

  // ── LIVE availability, off the same CRM feed the Inventory map uses ──
  const invV = useInventory();  // re-render when the feed refreshes
  const ready = !!(typeof window !== 'undefined' && window.UNI_INVENTORY && window.UNI_INVENTORY.ready);
  const totals = React.useMemo(() => TOWERS.reduce((a, tw) => {
    const s = towerSummary(tw.id); a.available += s.available; a.total += s.total; return a;
  }, { available:0, total:0 }), [invV]);
  const totalResidences = totals.total || 600;

  const towerGlyph = (
    <svg width="36" height="36" viewBox="0 0 48 48" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 44 L14 12 L24 6 L34 12 L34 44"/><path d="M8 44 L40 44"/>
      <path d="M19 18 L19 22 M29 18 L29 22 M19 28 L19 32 M29 28 L29 32"/><path d="M22 44 L22 36 L26 36 L26 44"/>
    </svg>
  );
  const podiumGlyph = (
    <svg width="36" height="36" viewBox="0 0 48 48" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 40 L42 40"/><path d="M10 40 L10 24 L20 24 L20 40"/><path d="M28 40 L28 16 L38 16 L38 40"/>
      <path d="M13 30 L17 30 M31 22 L35 22 M31 30 L35 30"/><circle cx="24" cy="10" r="3"/>
    </svg>
  );

  return (
    <div style={{position:'absolute', inset:0, background:'transparent', color:'var(--ink)', overflow:'hidden'}}>

      {/* ── HEADER (matches FloorSelect / FloorPlate) ─────────────── */}
      <div style={{position:'absolute', top:54, left:72, right:72, display:'flex', justifyContent:'space-between', alignItems:'flex-end', opacity:e, transform:`translateY(${(1-e)*-12}px)`, zIndex:14}}>
        <div style={{display:'flex', alignItems:'flex-end', gap:34}}>
          <button onClick={()=>navigate('home')} style={fsBackBtn}
            onMouseEnter={ev=>{ev.currentTarget.style.background='var(--gold)'; ev.currentTarget.style.color='#0a0807'; ev.currentTarget.style.borderColor='var(--gold)';}}
            onMouseLeave={ev=>{ev.currentTarget.style.background='transparent'; ev.currentTarget.style.color='var(--ink)'; ev.currentTarget.style.borderColor='var(--line)';}}>
            <Icons.back width={28} height={28}/>
          </button>
          <div>
            <Breadcrumb crumbs={[
              {label:'Home', go:()=>navigate('home')},
              {label:'Inventory'},
            ]}/>
            <div className="serif" style={{fontSize:96, fontWeight:300, letterSpacing:'-0.025em', lineHeight:1, marginTop:12}}>Inventory</div>
            <div style={{fontSize:24, color:'var(--slate)', marginTop:12, fontStyle:'italic'}}>Choose how you would like to explore the address</div>
          </div>
        </div>
        <div role="button" tabIndex={0} aria-label="Go to home"
          onClick={()=>navigate('home')}
          onKeyDown={ev=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); navigate('home'); } }}
          onMouseEnter={ev=>{ ev.currentTarget.style.opacity='0.6'; ev.currentTarget.style.transform='scale(1.03)'; }}
          onMouseLeave={ev=>{ ev.currentTarget.style.opacity='1'; ev.currentTarget.style.transform='scale(1)'; }}
          style={{display:'flex', alignItems:'center', gap:22, cursor:'pointer', transformOrigin:'right center', transition:'opacity 200ms ease, transform 200ms ease'}}>
          <UniverseMonogram size={68} progress={1} color="var(--gold-deep)"/>
          <div style={{display:'flex', flexDirection:'column', gap:8, alignItems:'flex-end'}}>
            <UniverseWordmark size={26} color="var(--ink)" tight/>
            <VenusCredit size={13}/>
          </div>
        </div>
      </div>

      {/* ── TWO CINEMATIC CHOICE CARDS · 70 / 30 ─────────────────── */}
      <div style={{position:'absolute', top:296, left:72, right:72, bottom:76, display:'flex', gap:44}}>
        <ChoiceCard
          index="01" kicker="LIVE AVAILABILITY" glyph={towerGlyph}
          img="assets/renders/choice-towers.jpg" imgPos="center 62%" ken
          media={typeof window !== 'undefined' && window.TOWER_GEO ? <LivePlanMedia/> : null}
          flex="7 1 0" pad="72px 76px" titleSize={98}
          title="Choose Tower"
          sub="Ten towers rising over the address — select one to walk its floors and homes."
          badge={<LiveAvailBadge ready={ready} available={totals.available} total={totalResidences}/>}
          onGo={()=>{ try{ window.RDA && window.RDA.track('inventory_mode','towers'); }catch(e){} navigate('towers'); }} delay={0.12}/>
        <ChoiceCard
          index="02" kicker="G + 2 PODIUM LEVELS" glyph={podiumGlyph}
          img="assets/renders/choice-gplus.jpg" imgPos="center 58%"
          flex="3 1 0" pad="66px 52px" titleSize={62}
          title="Explore G+2 Floors"
          sub="Ground, First & Second — the amenity podium."
          onGo={()=>{ try{ window.RDA && window.RDA.track('inventory_mode','gplus'); }catch(e){} navigate('gplus'); }} delay={0.22}/>
      </div>
    </div>
  );
}

window.InvChoice = InvChoice;
