// evara-screen.jsx — Full Evara Estates property page with interactive master plan.
// Replaces PropertyScreen from screens.jsx. Uses brand tokens (M), MIcon, helpers
// already attached to window from screens.jsx + screens-extra.jsx.

const { useState: useStateE, useMemo: useMemoE, useRef: useRefE, useEffect: useEffectE } = React;

// ─────────────────────────────────────────────────────────────
// Plot data — Phase II, 142 plots laid out in a believable grid.
// Each plot has: id, row, col, w/h units, size (sq yd), price (Cr), status.
// We hand-place ~64 plots in a meaningful layout (clubhouse, lake, avenues)
// to keep file size sane while feeling like a real plan.
// ─────────────────────────────────────────────────────────────
// Pull plot inventory live from window.MARSAN_DATA.PROPERTIES[0].plotInventory.
// Same data the desktop "Open Interactive Plan" modal reads, so admin's edits
// (admin Studio → Properties → Master Plan) drive both surfaces.
function getLivePlots() {
  const propLive = (window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES && window.MARSAN_DATA.PROPERTIES[0]) || null;
  if (!propLive) return [];
  const inv = propLive.plotInventory || {};
  const total = Number(inv.total) || propLive.plots || 0;
  if (!total) return [];
  const overrides = inv.overrides || {};
  const defaults = {
    status: 'available',
    area:        inv.default_area        || propLive.areaMin || 1200,
    facing:      inv.default_facing      || (propLive.facing && propLive.facing[0]) || 'East',
    price_lakhs: inv.default_price_lakhs || (propLive.priceMin ? Math.round(Number(propLive.priceMin) * (propLive.priceUnit === 'Cr' ? 100 : 1)) : 50),
  };
  // Layout — square-ish grid, wider than tall to suit a 320-px-wide SVG canvas.
  const cols = Math.max(8, Math.min(24, Math.ceil(Math.sqrt(total * 1.4))));
  // Defensive normaliser — admin sometimes types the price in rupees instead
  // of lakhs (e.g. 36000000 for 3.6 Cr); anything > 1e5 lakhs (= 100 Cr) is
  // almost certainly a unit-mistake and gets divided down.
  function normaliseLakhs(v) {
    const n = Number(v) || 0;
    if (!isFinite(n) || n <= 0) return 0;
    if (n > 100000) return n / 100000;   // entered in rupees
    if (n > 10000)  return n / 1000;     // entered in thousands
    return n;
  }
  const out = [];
  for (let i = 0; i < total; i++) {
    const n = i + 1;
    const o = overrides[String(n)] || {};
    const priceL = normaliseLakhs(o.price_lakhs || defaults.price_lakhs);
    out.push({
      id:     String(n).padStart(3, '0'),
      n,
      x:      i % cols,
      y:      Math.floor(i / cols),
      w:      1, h: 1,
      size:   o.area   || defaults.area,
      facing: o.facing || defaults.facing,
      // ≥100 L → display in Cr; else display in L.
      price:  priceL >= 100 ? +(priceL / 100).toFixed(2) : null,
      priceL: +priceL.toFixed(1),
      status: o.status || defaults.status,
    });
  }
  return out;
}

const STATUS_COLORS = {
  available: { fill: '#a8c9b4', stroke: '#143a2a', label: 'Available' },
  premium:   { fill: '#e2bd6b', stroke: '#a88841', label: 'Premium' },
  booked:    { fill: '#5a6b5e', stroke: '#0a1f17', label: 'Booked' },
  hold:      { fill: '#e8dcc1', stroke: '#a88841', label: 'On Hold' },
  // Backwards-compat aliases (the original design used these names).
  sold:      { fill: '#5a6b5e', stroke: '#0a1f17', label: 'Sold' },
  reserved:  { fill: '#e8dcc1', stroke: '#a88841', label: 'Reserved' },
};

// ─────────────────────────────────────────────────────────────
// PropertyScreen v2 — full Evara Estates page
// ─────────────────────────────────────────────────────────────
function PropertyScreen({ nav, menuOpen, setMenuOpen }) {
  const p = PROPERTIES[0];
  const [tab, setTab] = useStateE('overview');
  const [selectedPlot, setSelectedPlot] = useStateE(null);
  const [planFilter, setPlanFilter] = useStateE('all'); // all / available / premium / lake
  const [planZoom, setPlanZoom] = useStateE(1);

  return (
    <div className="ms-root" style={{ background: M.ivory, minHeight: '100%', position: 'relative', paddingBottom: 64 }}>
      <NavDrawer open={menuOpen} onClose={() => setMenuOpen(false)} nav={nav} />

      {/* ═══ HERO ═══ */}
      <section className="ms-fullbleed" style={{ position: 'relative', height: 420 }}>
        {p.heroUrl ? (
          <img src={p.heroUrl} alt={p.name} loading="eager"
            style={{ display: 'block', width: '100%', height: 420, objectFit: 'cover' }} />
        ) : (
          <div className="ms-img-ph" style={{ height: 420, width: '100%' }}>
            <span>{p.name} · hero</span>
          </div>
        )}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(10,31,23,0.55) 0%, rgba(10,31,23,0.1) 32%, rgba(10,31,23,0.15) 55%, rgba(10,31,23,0.95) 100%)',
        }} />
        {/* Top controls */}
        <div style={{ position: 'absolute', top: 14, left: 14, right: 14, display: 'flex', justifyContent: 'space-between' }}>
          <button onClick={() => nav('properties')} style={hudBtn()}>
            <MIcon name="back" size={16} color={M.goldBright} />
          </button>
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={hudBtn()}><MIcon name="heart" size={14} color={M.goldBright} /></button>
            <button style={hudBtn()}><MIcon name="share" size={14} color={M.goldBright} /></button>
            <button onClick={() => setMenuOpen(true)} style={hudBtn()}><MIcon name="menu" size={16} color={M.goldBright} /></button>
          </div>
        </div>
        {/* Image strip indicator */}
        <div style={{ position: 'absolute', top: 14, left: '50%', transform: 'translateX(-50%)', fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.18em', color: M.gold, background: 'rgba(10,31,23,0.55)', padding: '6px 12px', backdropFilter: 'blur(8px)' }}>
          01 / 24
        </div>
        {/* Bottom title */}
        <div style={{ position: 'absolute', left: 22, right: 22, bottom: 24 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            <span className="ms-chip gold">{p.launch}</span>
            <span className="ms-chip" style={{ background: 'rgba(10,31,23,0.55)', borderColor: 'rgba(232,220,193,0.25)', color: M.champagne }}>Phase II Open</span>
          </div>
          <h1 style={{ fontFamily: M.serif, fontSize: 38, fontWeight: 300, color: M.ivory, margin: '0 0 8px', lineHeight: 1, letterSpacing: '-0.01em' }}>
            {p.name}
          </h1>
          <div style={{ fontFamily: M.sans, fontSize: 13, color: 'rgba(232,220,193,0.85)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <MIcon name="pin" size={13} color={M.gold} /> {p.location}
            <span style={{ color: M.gold, margin: '0 4px' }}>·</span>
            <span>15 min from RGIA</span>
          </div>
        </div>
      </section>

      {/* ═══ KEY STATS BAR ═══ */}
      <div className="ms-stats-row" style={{
        background: '#fff', padding: '20px 14px', borderBottom: `1px solid ${M.beige}`,
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 4,
      }}>
        {(() => {
          const livePlots = getLivePlots();
          const live = (window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES && window.MARSAN_DATA.PROPERTIES[0]) || null;
          const priceFrom = live && live.priceMin
            ? { value: `₹${live.priceMin}`, unit: live.priceUnit || 'Cr' }
            : { value: '—', unit: '' };
          const plotSizes = live && live.areaMin && live.areaMax
            ? { value: `${live.areaMin}–${live.areaMax}`, unit: live.areaUnit || 'sq.yd' }
            : { value: '—', unit: '' };
          const availStr  = { value: livePlots.length ? `${livePlots.filter(x => x.status === 'available').length} of ${livePlots.length}` : '—', unit: '' };
          return [
            ['PRICE FROM',   priceFrom],
            ['PLOT SIZES',   plotSizes],
            ['AVAILABILITY', availStr],
          ];
        })().map(([l, v], i) => (
          <div key={i} style={{ borderRight: i < 2 ? `1px solid ${M.beige}` : 'none', paddingRight: 6 }}>
            <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.stone }}>{l}</div>
            <div style={{ fontFamily: M.serif, fontSize: 18, color: M.emeraldDeepest, marginTop: 4, lineHeight: 1.1, whiteSpace: 'nowrap' }}>
              {v.value}
              {v.unit && (
                <span style={{ fontSize: 12, color: M.goldDeep, fontStyle: 'italic', fontFamily: M.serif, fontWeight: 500, marginLeft: 4 }}>
                  {v.unit}
                </span>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* ═══ TABS ═══ */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: M.ivory, display: 'flex',
        borderBottom: `1px solid ${M.beige}`,
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {[
          ['overview', 'Overview'],
          ['plan', 'Master Plan'],
          ['amenities', 'Amenities'],
          ['location', 'Location'],
          ['gallery', 'Gallery'],
        ].map(([id, label]) => (
          <button key={id} onClick={() => setTab(id)} style={{
            padding: '14px 16px', background: 'none', border: 'none',
            fontFamily: M.sans, fontSize: 10, fontWeight: 500,
            letterSpacing: '0.18em', textTransform: 'uppercase',
            color: tab === id ? M.emeraldDeepest : M.stone,
            borderBottom: tab === id ? `2px solid ${M.gold}` : '2px solid transparent',
            cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
          }}>{label}</button>
        ))}
      </div>

      {tab === 'overview' && <OverviewTab nav={nav} setTab={setTab} />}
      {tab === 'plan' && (
        <PlanTab
          selectedPlot={selectedPlot}
          setSelectedPlot={setSelectedPlot}
          filter={planFilter}
          setFilter={setPlanFilter}
          zoom={planZoom}
          setZoom={setPlanZoom}
          nav={nav}
        />
      )}
      {tab === 'amenities' && <AmenitiesTab />}
      {tab === 'location' && <LocationTab />}
      {tab === 'gallery' && <GalleryTab />}
      {tab === 'docs' && <DocsTab />}

      <FooterCompact />
      <ContactDock onEnquire={() => nav('enquire')} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// OVERVIEW TAB
// ─────────────────────────────────────────────────────────────
function OverviewTab({ nav, setTab }) {
  return (
    <>
      <section style={{ padding: '36px 22px 24px' }}>
        <Eyebrow>Overview</Eyebrow>
        <h2 style={{ fontFamily: M.serif, fontSize: 28, color: M.emeraldDeepest, margin: '12px 0 8px', fontWeight: 400, lineHeight: 1.15, textWrap: 'balance' }}>
          108 acres of gated <em style={{ color: M.goldDeep, fontStyle: 'italic' }}>eco-luxury</em>, fifteen minutes from the airport.
        </h2>
        <GoldDivider />
        <p style={{ fontFamily: M.sans, fontSize: 14.5, lineHeight: 1.75, color: M.charcoalSoft, marginTop: 18 }}>
          Evara sits on the southern airport corridor — a stretch we've been quietly accumulating in for eighteen months. The site is bordered by a protected reserve to the east and the proposed Regional Ring Road to the south. Plots are sold with title-cleared documentation and current encumbrance certificates.
        </p>
        <p style={{ fontFamily: M.sans, fontSize: 14.5, lineHeight: 1.75, color: M.charcoalSoft, marginTop: 14 }}>
          Phase II opens 142 plots across the eastern ridge, with sizes ranging from 1,200 to 3,600 sq.yd. All plots are TG-RERA-registered and HMDA-sanctioned.
        </p>
      </section>

      {/* Stat grid */}
      <section style={{ padding: '8px 22px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            ['Total Land', '108 ac', 'plot'],
            ['Plots in Phase II', '142', 'diamond'],
            ['Open Green', '42%', 'shield'],
            ['Approval', 'TG-RERA', 'award'],
            ['Avenue Width', '40 ft', 'map'],
            ['Power & Water', 'Underground', 'shield'],
          ].map(([l, v, ic], i) => (
            <div key={i} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: '16px 14px', position: 'relative' }}>
              <div style={{ position: 'absolute', top: 10, right: 10, opacity: 0.35 }}>
                <MIcon name={ic} size={16} color={M.goldDeep} />
              </div>
              <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.stone }}>{l.toUpperCase()}</div>
              <div style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, marginTop: 6, lineHeight: 1 }}>{v}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Founder quote */}
      <section style={{ padding: '0 22px 32px' }}>
        <div className="ms-grain" style={{ padding: '32px 24px', background: M.emerald, color: M.ivory, position: 'relative' }}>
          <div style={{ position: 'relative', zIndex: 1 }}>
            <div style={{ fontFamily: M.serif, fontSize: 64, color: M.gold, lineHeight: 0.6, marginBottom: 4 }}>"</div>
            <div style={{ fontFamily: M.serif, fontSize: 20, fontStyle: 'italic', lineHeight: 1.45, color: M.ivory, textWrap: 'balance' }}>
              We expect the southern arc to compound at a different cadence than ORR-West. Evara is the cornerstone holding.
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 18 }}>
              <div className="ms-img-ph" style={{ width: 36, height: 36, borderRadius: '50%' }}><span>SR</span></div>
              <div>
                <div style={{ fontFamily: M.serif, fontSize: 14, color: M.ivory, fontWeight: 500 }}>Sandeep Reddy</div>
                <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.gold, marginTop: 2 }}>FOUNDER · MARSAN</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Why this property */}
      <section style={{ padding: '0 22px 36px' }}>
        <Eyebrow>Why Evara</Eyebrow>
        <GoldDivider />
        <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 18 }}>
          {[
            ['shield', 'Title-cleared inventory', 'Independent legal opinion. EC current to 30 days. Mutation history checked back twenty years.'],
            ['award', 'Compounding corridor', 'Eighteen-month thesis on the southern airport arc. Infrastructure spend, employment density, registration trends — all on file.'],
            ['diamond', 'Lifetime concierge', 'Mutation, possession, resale — handled directly by the Marsan desk for the full holding period.'],
          ].map(([ic, h, p], i) => (
            <div key={i} style={{ display: 'flex', gap: 16 }}>
              <div style={{ flexShrink: 0, width: 44, height: 44, border: `1px solid ${M.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <MIcon name={ic} size={20} color={M.goldDeep} />
              </div>
              <div>
                <div style={{ fontFamily: M.serif, fontSize: 18, color: M.emeraldDeepest, fontWeight: 500 }}>{h}</div>
                <div style={{ fontFamily: M.sans, fontSize: 13, lineHeight: 1.65, color: M.charcoalSoft, marginTop: 4 }}>{p}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* CTA to plan */}
      <section style={{ padding: '24px 22px 0' }}>
        <button onClick={() => setTab('plan')} className="ms-btn ms-btn-primary ms-btn-lg" style={{ width: '100%' }}>
          Open Interactive Master Plan <MIcon name="arrow" size={14} />
        </button>
      </section>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// MASTER PLAN TAB — interactive
// ─────────────────────────────────────────────────────────────
function PlanTab({ selectedPlot, setSelectedPlot, filter, setFilter, zoom, setZoom, nav }) {
  const visible = useMemoE(() => {
    const all = getLivePlots();
    if (filter === 'all')       return all;
    if (filter === 'available') return all.filter(p => p.status === 'available');
    if (filter === 'premium')   return all.filter(p => p.status === 'premium');
    if (filter === 'booked')    return all.filter(p => p.status === 'booked');
    if (filter === 'hold')      return all.filter(p => p.status === 'hold');
    return all;
  }, [filter]);
  const allPlots = useMemoE(() => getLivePlots(), []);
  const visibleIds = useMemoE(() => new Set(visible.map(p => p.id)), [visible]);

  // SVG canvas — sized to the actual plot count.
  // Bigger cells so plot numbers fit comfortably and tap targets are accurate.
  const total = allPlots.length;
  const cols = total ? Math.max(8, Math.min(20, Math.ceil(Math.sqrt(total * 1.4)))) : 14;
  const rows = total ? Math.ceil(total / cols) : 12;
  const cellW = total > 250 ? 18 : (total > 120 ? 22 : 28);
  const cellH = cellW;
  const fontPx = cellW >= 26 ? 8.5 : (cellW >= 22 ? 7.5 : 6);
  const W = cols * cellW;
  const H = rows * cellH;

  // Live counts for the chips.
  const counts = { available: 0, premium: 0, booked: 0, hold: 0 };
  allPlots.forEach(p => { counts[p.status] = (counts[p.status] || 0) + 1; });

  return (
    <section style={{ padding: '20px 0 8px' }}>
      <div style={{ padding: '0 22px' }}>
        <Eyebrow>Master Plan</Eyebrow>
        <h2 style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, margin: '10px 0 4px', fontWeight: 400, lineHeight: 1.2 }}>
          Tap any plot for details.
        </h2>
        <GoldDivider />
      </div>

      {/* Filters — match desktop modal exactly */}
      <div style={{ marginTop: 18, padding: '0 22px', display: 'flex', gap: 8, overflowX: 'auto', scrollbarWidth: 'none' }}>
        {[
          ['all',       `All · ${total}`],
          ['available', `Available · ${counts.available}`],
          ['premium',   `Premium · ${counts.premium}`],
          ['booked',    `Booked · ${counts.booked}`],
          counts.hold > 0 && ['hold', `On Hold · ${counts.hold}`],
        ].filter(Boolean).map(([id, label]) => (
          <span key={id} className="ms-chip" onClick={() => setFilter(id)} style={{
            background: filter === id ? M.emeraldDeepest : '#fff',
            color: filter === id ? M.goldBright : M.emeraldDeepest,
            borderColor: filter === id ? M.emeraldDeepest : M.beige,
            whiteSpace: 'nowrap', cursor: 'pointer', flexShrink: 0,
          }}>{label}</span>
        ))}
      </div>

      {/* Legend — only the four real statuses */}
      <div style={{ marginTop: 14, padding: '12px 22px', display: 'flex', gap: 14, flexWrap: 'wrap', borderTop: `1px solid ${M.beige}`, borderBottom: `1px solid ${M.beige}`, background: '#fff' }}>
        {[['available', STATUS_COLORS.available], ['premium', STATUS_COLORS.premium], ['booked', STATUS_COLORS.booked], ['hold', STATUS_COLORS.hold]].map(([k, c]) => (
          <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 12, height: 12, background: c.fill, border: `1px solid ${c.stroke}` }} />
            <span style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.12em', color: M.charcoalSoft, textTransform: 'uppercase' }}>{c.label}</span>
          </div>
        ))}
      </div>

      {/* SVG plan — emerald-grain frame, ivory canvas, gold accents */}
      <div className="ms-grain" style={{
        background: M.emeraldDeepest, padding: '20px 14px 22px', position: 'relative',
        boxShadow: 'inset 0 1px 0 rgba(201,165,92,0.18), inset 0 -1px 0 rgba(201,165,92,0.08)',
      }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', padding: '0 8px 12px' }}>
            <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase', color: M.gold }}>
              Phase II · {total} plots
            </div>
            <div style={{ fontFamily: M.serif, fontStyle: 'italic', fontSize: 11, color: 'rgba(232,220,193,0.6)' }}>
              Tap any plot
            </div>
          </div>
          {total === 0 ? (
            <div style={{ padding: '40px 12px', textAlign: 'center', color: M.stone, fontFamily: M.sans, fontSize: 13, background: M.ivory, border: `1px solid ${M.beige}` }}>
              Plot inventory not configured yet.
            </div>
          ) : (
            <svg viewBox={`-14 -14 ${W + 28} ${H + 28}`} width="100%"
              style={{ display: 'block', background: M.ivory, border: `1px solid ${M.gold}`, boxShadow: '0 12px 28px rgba(0,0,0,0.4)' }}>
              <defs>
                <filter id="plotShadow" x="-20%" y="-20%" width="140%" height="140%">
                  <feDropShadow dx="0" dy="0.4" stdDeviation="0.4" floodColor="#000" floodOpacity="0.18" />
                </filter>
                <linearGradient id="cellAvailable" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#bcd5c5" />
                  <stop offset="100%" stopColor="#9bbda7" />
                </linearGradient>
                <linearGradient id="cellPremium" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#ecca7e" />
                  <stop offset="100%" stopColor="#d4af5e" />
                </linearGradient>
                <linearGradient id="cellBooked" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#6b7c6f" />
                  <stop offset="100%" stopColor="#475650" />
                </linearGradient>
                <linearGradient id="cellHold" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#ece1c7" />
                  <stop offset="100%" stopColor="#d6c5a0" />
                </linearGradient>
              </defs>
              {/* Compass */}
              <g transform={`translate(${W - 22}, ${H - 22})`}>
                <circle cx="0" cy="0" r="14" fill="#fff" stroke={M.gold} strokeWidth="0.7" />
                <path d="M 0 -10 L 4 4 L 0 0 L -4 4 Z" fill={M.emeraldDeepest} />
                <text x="0" y="-16" fontFamily={M.mono} fontSize="6" fill={M.goldDeep} textAnchor="middle" letterSpacing="1">N</text>
              </g>
              {/* Plots */}
              {allPlots.map((plot) => {
                const c = STATUS_COLORS[plot.status] || STATUS_COLORS.available;
                const isVisible = visibleIds.has(plot.id);
                const isSelected = selectedPlot && selectedPlot.id === plot.id;
                const fillId = ({ available: 'cellAvailable', premium: 'cellPremium', booked: 'cellBooked', hold: 'cellHold' })[plot.status] || 'cellAvailable';
                const numColor = (plot.status === 'booked') ? M.champagne : M.emeraldDeepest;
                const cx = plot.x * cellW + cellW / 2;
                const cy = plot.y * cellH + cellH / 2;
                return (
                  <g key={plot.id} onClick={() => setSelectedPlot(plot)} style={{ cursor: 'pointer' }} filter={isSelected ? null : 'url(#plotShadow)'}>
                    <rect
                      x={plot.x * cellW + 0.6}
                      y={plot.y * cellH + 0.6}
                      width={cellW - 1.2}
                      height={cellH - 1.2}
                      rx={isSelected ? 1.5 : 1}
                      fill={`url(#${fillId})`}
                      stroke={isSelected ? M.gold : c.stroke}
                      strokeWidth={isSelected ? 1.6 : 0.5}
                      opacity={isVisible ? 1 : 0.2}
                    />
                    {isVisible && (
                      <text
                        x={cx}
                        y={cy + fontPx * 0.32}
                        fontFamily={M.mono}
                        fontSize={fontPx}
                        fill={numColor}
                        textAnchor="middle"
                        fontWeight="500"
                        letterSpacing="0"
                        style={{ pointerEvents: 'none', opacity: 0.85 }}
                      >
                        {plot.n}
                      </text>
                    )}
                    {isSelected && (
                      <rect
                        x={plot.x * cellW - 1}
                        y={plot.y * cellH - 1}
                        width={cellW + 1}
                        height={cellH + 1}
                        fill="none"
                        stroke={M.goldBright}
                        strokeWidth="0.6"
                        strokeDasharray="2 1.5"
                        opacity="0.9"
                      />
                    )}
                  </g>
                );
              })}
            </svg>
          )}
        </div>
      </div>

      {/* Selected plot detail card */}
      {selectedPlot && (
        <div style={{ padding: '18px 22px 4px' }}>
          <PlotDetailCard plot={selectedPlot} onClose={() => setSelectedPlot(null)} onEnquire={() => nav('enquire')} />
        </div>
      )}

      {/* Status summary — replaces the old Block summary, shows real inventory mix */}
      {total > 0 && (
        <div style={{ padding: '24px 22px 8px' }}>
          <Eyebrow>Inventory summary</Eyebrow>
          <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              ['Available', counts.available, STATUS_COLORS.available.fill],
              ['Premium',   counts.premium,   STATUS_COLORS.premium.fill],
              ['Booked',    counts.booked,    STATUS_COLORS.booked.fill],
              ['On Hold',   counts.hold,      STATUS_COLORS.hold.fill],
            ].map(([label, n, fill]) => (
              <div key={label} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 14, height: 14, background: fill, border: `1px solid rgba(0,0,0,0.15)`, flexShrink: 0 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.stone, textTransform: 'uppercase' }}>{label}</div>
                  <div style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, lineHeight: 1.05, marginTop: 2 }}>{n}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

function PlotDetailCard({ plot, onClose, onEnquire }) {
  const c = STATUS_COLORS[plot.status] || STATUS_COLORS.available;
  const isAvail = plot.status === 'available' || plot.status === 'premium';
  const priceUnit = plot.price ? 'Cr' : 'L';
  const priceVal  = plot.price ? `₹${plot.price}` : `₹${plot.priceL}`;
  return (
    <div style={{ background: '#fff', border: `1px solid ${M.beige}`, position: 'relative', padding: 20 }}>
      <button onClick={onClose} aria-label="Close" style={{
        position: 'absolute', top: 10, right: 10, background: 'none', border: 'none', cursor: 'pointer', padding: 4,
      }}>
        <MIcon name="close" size={14} color={M.stone} />
      </button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <span style={{ width: 10, height: 10, background: c.fill, border: `1px solid ${c.stroke}` }} />
        <span style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.16em', color: M.stone, textTransform: 'uppercase' }}>
          Plot {plot.id}
        </span>
      </div>
      <h3 style={{ fontFamily: M.serif, fontSize: 26, color: M.emeraldDeepest, margin: '4px 0 10px', fontWeight: 400, lineHeight: 1 }}>
        {Number(plot.size).toLocaleString()} <span style={{ fontSize: 16, color: M.goldDeep, fontStyle: 'italic', fontFamily: M.serif, fontWeight: 500, marginLeft: 6 }}>sq.yd</span>
      </h3>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 14, paddingTop: 14, borderTop: `1px solid ${M.beige}` }}>
        <div>
          <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.stone }}>PRICE</div>
          <div style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, marginTop: 2 }}>
            {priceVal} <span style={{ fontSize: 14, color: M.goldDeep, fontStyle: 'italic', fontWeight: 500, marginLeft: 4 }}>{priceUnit}</span>
          </div>
        </div>
        <div>
          <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.stone }}>STATUS</div>
          <div style={{ fontFamily: M.serif, fontSize: 22, color: c.stroke, marginTop: 2, fontStyle: 'italic' }}>{c.label}</div>
        </div>
      </div>
      <div style={{ marginTop: 14, padding: 14, background: M.ivoryWarm, fontFamily: M.sans, fontSize: 12, lineHeight: 1.6, color: M.charcoalSoft }}>
        <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.goldDeep, marginBottom: 6 }}>FACING & ACCESS</div>
        {plot.facing} facing · 40 ft avenue · Underground utilities on site
      </div>
      {isAvail ? (
        <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
          <button onClick={onEnquire} className="ms-btn ms-btn-primary" style={{ flex: 2 }}>
            Hold this plot
          </button>
          <a href={`https://wa.me/919849999708?text=${encodeURIComponent('Interested in Plot ' + plot.id + ' at Evara Estates')}`}
            target="_blank" rel="noopener" className="ms-btn ms-btn-ghost-dark" style={{ flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <MIcon name="wa" size={14} /> WhatsApp
          </a>
        </div>
      ) : (
        <div style={{ marginTop: 14, padding: 14, background: M.emeraldDeepest, color: M.champagne, fontFamily: M.serif, fontSize: 14, fontStyle: 'italic', textAlign: 'center' }}>
          {plot.status === 'booked' ? 'Already booked. Ask us about similar plots.' : plot.status === 'hold' ? 'On hold — call our advisor for current status.' : 'Not currently available.'}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AMENITIES TAB
// ─────────────────────────────────────────────────────────────
function AmenitiesTab() {
  // Pull live amenities from MARSAN_DATA. Each amenity is { icon, label }.
  const propLive = (window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES && window.MARSAN_DATA.PROPERTIES[0]) || null;
  const live = (propLive && propLive.amenities) || (window.MARSAN_DATA && window.MARSAN_DATA.AMENITIES_DEFAULT) || [];
  // Heuristic grouping: split the flat list into 4 themed groups by icon family.
  const ICON_GROUP = {
    pool: 'Wellness & leisure', gym: 'Wellness & leisure', club: 'Wellness & leisure',
    park: 'Nature & quiet', tree: 'Nature & quiet',
    road: 'Infrastructure', bolt: 'Infrastructure', water: 'Infrastructure', drain: 'Infrastructure', light: 'Infrastructure', arch: 'Infrastructure',
    shield: 'For the family', school: 'For the family', hospital: 'For the family',
    plot: 'Land', villa: 'Land', tower: 'Land', farm: 'Land',
  };
  const groupOrder = ['Wellness & leisure', 'For the family', 'Infrastructure', 'Nature & quiet', 'Land', 'Other'];
  const grouped = {};
  live.forEach(a => {
    const g = ICON_GROUP[a.icon] || 'Other';
    (grouped[g] = grouped[g] || []).push(a);
  });
  const groups = groupOrder.filter(g => grouped[g] && grouped[g].length).map(title => ({ title, items: grouped[title] }));

  // Pull a hero photo for the amenities header from the gallery (clubhouse-aerial preferred).
  const photo = (propLive && propLive.gallery || []).map(g => typeof g === 'string' ? { url: g } : g)
    .find(g => /club|amenit|wellness/i.test(g.label || g.url || '')) || (propLive && propLive.gallery || [])[0];

  return (
    <section style={{ padding: '32px 22px' }}>
      <Eyebrow>Amenities · {live.length} in total</Eyebrow>
      <h2 style={{ fontFamily: M.serif, fontSize: 26, color: M.emeraldDeepest, margin: '12px 0 6px', fontWeight: 400, lineHeight: 1.15 }}>
        Built like a community, run like a club.
      </h2>
      <GoldDivider />

      {photo && photo.url ? (
        <img src={photo.url} alt={photo.label || ''} loading="lazy"
          style={{ display: 'block', width: '100%', height: 200, objectFit: 'cover', marginTop: 22 }} />
      ) : (
        <div className="ms-img-ph" style={{ height: 180, marginTop: 22 }}><span>Clubhouse</span></div>
      )}

      <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 28 }}>
        {groups.length === 0 && (
          <div style={{ padding: 24, textAlign: 'center', color: M.stone, fontSize: 13 }}>No amenities listed yet.</div>
        )}
        {groups.map((g, gi) => (
          <div key={gi}>
            <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.18em', color: M.goldDeep, textTransform: 'uppercase' }}>
              {g.title}
            </div>
            <div style={{ height: 1, background: M.beige, margin: '10px 0 14px' }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {g.items.map((a, i) => (
                <div key={i} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: '14px 14px 16px', display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                  <div style={{ width: 36, height: 36, border: `1px solid ${M.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: M.goldDeep, flexShrink: 0 }}>
                    <MIcon name={a.icon || 'plot'} size={16} color={M.goldDeep} />
                  </div>
                  <div style={{ fontFamily: M.serif, fontSize: 14.5, color: M.emeraldDeepest, fontWeight: 500, lineHeight: 1.25 }}>{a.label}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// LOCATION TAB
// ─────────────────────────────────────────────────────────────
function LocationTab() {
  const propLive = (window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES && window.MARSAN_DATA.PROPERTIES[0]) || null;
  const nearby = (propLive && propLive.nearby) || [];
  const address = (propLive && (propLive.address || propLive.location)) || 'Hyderabad';
  const lat = propLive && propLive.latitude;
  const lng = propLive && propLive.longitude;

  // Group nearby items by `type` for the bottom card grid.
  const grouped = {};
  nearby.forEach(n => {
    const key = n.type || 'Other';
    (grouped[key] = grouped[key] || []).push(n);
  });

  return (
    <section style={{ padding: '32px 22px' }}>
      <Eyebrow>Location · {address.split(',')[0]}</Eyebrow>
      <h2 style={{ fontFamily: M.serif, fontSize: 26, color: M.emeraldDeepest, margin: '12px 0 6px', fontWeight: 400, lineHeight: 1.15 }}>
        {propLive && propLive.tagline ? propLive.tagline.split('.')[0] + '.' : 'On the southern airport corridor.'}
      </h2>
      <GoldDivider />

      {/* Real Google Map iframe when we have lat/lng, else placeholder */}
      {lat && lng ? (
        <div style={{ marginTop: 22, height: 240, border: `1px solid ${M.beige}`, overflow: 'hidden' }}>
          <iframe title="map"
            src={`https://www.google.com/maps?q=${lat},${lng}&z=13&output=embed`}
            style={{ width: '100%', height: '100%', border: 0 }} loading="lazy" />
        </div>
      ) : (
        <div className="ms-img-ph beige" style={{ height: 240, marginTop: 22, position: 'relative' }}>
          <span>Map</span>
        </div>
      )}

      {lat && lng && (
        <a href={`https://www.google.com/maps?q=${lat},${lng}`} target="_blank" rel="noopener"
          className="ms-btn ms-btn-ghost-dark" style={{ width: '100%', marginTop: 12 }}>
          <MIcon name="map" size={14} /> Open in Google Maps
        </a>
      )}

      <div style={{ marginTop: 28 }}>
        <Eyebrow>What's around · {nearby.length} places</Eyebrow>
        {nearby.length === 0 ? (
          <div style={{ padding: '24px 0', color: M.stone, fontSize: 13 }}>No nearby places listed yet.</div>
        ) : (
          <div style={{ marginTop: 14 }}>
            {nearby.map((n, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'center', padding: '14px 0', borderBottom: i === nearby.length - 1 ? 'none' : `1px solid ${M.beige}` }}>
                <div>
                  <div style={{ fontFamily: M.mono, fontSize: 9, letterSpacing: '0.14em', color: M.goldDeep, textTransform: 'uppercase', marginBottom: 4 }}>{n.type || 'Place'}</div>
                  <div style={{ fontFamily: M.serif, fontSize: 16, color: M.emeraldDeepest, lineHeight: 1.25 }}>{n.name}</div>
                </div>
                <div style={{ fontFamily: M.serif, fontSize: 17, color: M.goldDeep, fontStyle: 'italic', whiteSpace: 'nowrap' }}>{n.dist}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// GALLERY TAB
// ─────────────────────────────────────────────────────────────
function GalleryTab() {
  // Pull live gallery from window.MARSAN_DATA — first property by default
  // (which is EVARA on the live site). Each gallery entry is either a string
  // URL or { url, label, tag } — handle both shapes.
  const propLive = (window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES && window.MARSAN_DATA.PROPERTIES[0]) || null;
  const tiles = (propLive && propLive.gallery && propLive.gallery.length)
    ? propLive.gallery.map(g => (typeof g === 'string' ? { url: g } : g))
    : [];
  const [open, setOpen] = useStateE(null);

  // Editorial mosaic — first 9 tiles in a designed pattern, the rest in
  // 1/2/3-up rows so it always looks intentional.
  function Tile({ t, height, beige }) {
    if (!t || !t.url) return <div className={`ms-img-ph${beige ? ' beige' : ''}`} style={{ height }}><span>{(t && t.label) || ''}</span></div>;
    return (
      <button onClick={() => setOpen(t.url)} style={{ height, width: '100%', padding: 0, border: 'none', background: 'none', position: 'relative', cursor: 'pointer', overflow: 'hidden' }}>
        <img src={t.url} alt={t.label || ''} loading="lazy"
          style={{ display: 'block', width: '100%', height: '100%', objectFit: 'cover' }} />
        {t.label && (
          <span style={{ position: 'absolute', left: 10, bottom: 10, color: '#e8dcc1', fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', textShadow: '0 1px 4px rgba(0,0,0,0.6)' }}>
            {t.label}
          </span>
        )}
      </button>
    );
  }

  return (
    <section style={{ padding: '24px 14px' }}>
      <div style={{ padding: '0 8px' }}>
        <Eyebrow>Gallery · {tiles.length || 0} frames</Eyebrow>
        <GoldDivider />
      </div>
      <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <Tile t={tiles[0]} height={220} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          <Tile t={tiles[1]} height={160} />
          <Tile t={tiles[2]} height={160} beige />
        </div>
        {tiles[3] && <Tile t={tiles[3]} height={220} beige />}
        {(tiles[4] || tiles[5] || tiles[6]) && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
            <Tile t={tiles[4]} height={110} />
            <Tile t={tiles[5]} height={110} />
            <Tile t={tiles[6]} height={110} />
          </div>
        )}
        {tiles[7] && <Tile t={tiles[7]} height={200} />}
        {(tiles[8] || tiles[9]) && (
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 6 }}>
            <Tile t={tiles[8]} height={140} beige />
            <Tile t={tiles[9]} height={140} />
          </div>
        )}
        {/* Any extras beyond 10 → 2-up rows */}
        {tiles.slice(10).reduce((rows, t, i) => {
          const r = Math.floor(i / 2);
          rows[r] = rows[r] || [];
          rows[r].push(t);
          return rows;
        }, []).map((row, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {row.map((t, j) => <Tile key={j} t={t} height={140} />)}
          </div>
        ))}
      </div>

      {/* Lightbox */}
      {open && (
        <div onClick={() => setOpen(null)} style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,15,12,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <button onClick={() => setOpen(null)} aria-label="Close" style={{ position: 'absolute', top: 18, right: 18, width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,255,255,0.08)', color: '#e2bd6b', border: '1px solid rgba(201,165,92,0.4)', fontSize: 20, cursor: 'pointer' }}>×</button>
          <img src={open} alt="" style={{ maxWidth: '100%', maxHeight: '90vh', objectFit: 'contain' }} onClick={(e) => e.stopPropagation()} />
        </div>
      )}
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// DOCS TAB
// ─────────────────────────────────────────────────────────────
function DocsTab() {
  return (
    <section style={{ padding: '32px 22px' }}>
      <Eyebrow>Documentation</Eyebrow>
      <h2 style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, margin: '12px 0 6px', fontWeight: 400 }}>
        Title-cleared, on file.
      </h2>
      <GoldDivider />

      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          ['TG-RERA Registration', 'P02400003421', 'Verified', '2.1 MB · PDF'],
          ['Encumbrance Certificate', 'Current to 30 days', 'Available', '880 KB · PDF'],
          ['Independent Title Opinion', 'Updated 2025', 'Cleared', '1.4 MB · PDF'],
          ['HMDA Layout Approval', 'LP No. 4421/2024', 'Sanctioned', '3.2 MB · PDF'],
          ['Environmental Clearance', 'Telangana SPCB', 'Filed', '1.1 MB · PDF'],
          ['Engineer · Architect · CA Cert', 'Quarterly · Q1 2026', 'Updated', '480 KB · PDF'],
        ].map(([h, d, s, f], i) => (
          <div key={i} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: '16px 18px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest, fontWeight: 500, lineHeight: 1.2 }}>{h}</div>
                <div style={{ fontFamily: M.mono, fontSize: 10, color: M.stone, letterSpacing: '0.04em', marginTop: 4 }}>{d}</div>
                <div style={{ fontFamily: M.mono, fontSize: 9, color: M.goldDeep, letterSpacing: '0.12em', marginTop: 4 }}>{f}</div>
              </div>
              <span className="ms-status available" style={{ color: M.emeraldDeepest, fontFamily: M.mono, fontSize: 9, flexShrink: 0 }}>{s}</span>
            </div>
            <button style={{ marginTop: 10, background: 'none', border: 'none', padding: 0, fontFamily: M.mono, fontSize: 10, letterSpacing: '0.16em', color: M.goldDeep, textTransform: 'uppercase', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
              Download <MIcon name="arrow" size={11} color={M.goldDeep} />
            </button>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 24, padding: 18, background: M.ivoryWarm, borderLeft: `3px solid ${M.gold}` }}>
        <div style={{ fontFamily: M.serif, fontSize: 15, fontStyle: 'italic', color: M.emeraldDeepest, lineHeight: 1.55 }}>
          The full diligence pack is shared before any token is collected. We will not stand between a buyer and the regulator.
        </div>
      </div>
    </section>
  );
}

// Replace old component on window so app.jsx picks up the new one.
window.PropertyScreen = PropertyScreen;
