// Marsan Properties — Property Detail

// Error boundary so a render exception inside a modal becomes visible instead of
// silently producing an empty container.
class ModalBoundary extends React.Component {
  constructor(props) { super(props); this.state = { err: null }; }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) { console.error('[ModalBoundary]', err, info); }
  render() {
    if (this.state.err) {
      return (
        <div style={{ padding: 32, color: '#e2bd6b', background: '#0a1f17', minHeight: 200, fontFamily: 'JetBrains Mono', fontSize: 12, whiteSpace: 'pre-wrap' }}>
          <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#b04a3a', marginBottom: 12 }}>Modal render error</div>
          {String(this.state.err && (this.state.err.stack || this.state.err.message || this.state.err))}
          <button onClick={this.props.onClose} className="ms-btn ms-btn-ghost ms-btn-sm" style={{ marginTop: 16 }}>Close</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Render a fragment into document.body so we escape any ancestor that has
// transform / filter / will-change (which would trap position:fixed).
const Portal = ({ children }) => {
  const elRef = React.useRef(null);
  if (!elRef.current && typeof document !== 'undefined') {
    elRef.current = document.createElement('div');
    elRef.current.setAttribute('data-ms-portal', '');
  }
  React.useEffect(() => {
    if (!elRef.current) return;
    document.body.appendChild(elRef.current);
    return () => { try { document.body.removeChild(elRef.current); } catch (_) {} };
  }, []);
  if (!elRef.current) return null;
  return ReactDOM.createPortal(children, elRef.current);
};

// Lightbox: full-screen image viewer with keyboard nav (← → Esc) and click-to-close.
const Lightbox = ({ items, index, onClose, onIndex }) => {
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') onIndex((index + 1) % items.length);
      else if (e.key === 'ArrowLeft') onIndex((index - 1 + items.length) % items.length);
    };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; };
  }, [index, items.length, onClose, onIndex]);
  if (!items || !items.length) return null;
  const cur = items[index] || items[0];
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,15,12,0.96)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32,
      animation: 'msFadeIn 180ms ease-out',
    }}>
      <button onClick={(e) => { e.stopPropagation(); onClose(); }} aria-label="Close"
        style={{ position: 'absolute', top: 24, right: 24, width: 44, height: 44, 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>
      {items.length > 1 && (
        <>
          <button onClick={(e) => { e.stopPropagation(); onIndex((index - 1 + items.length) % items.length); }} aria-label="Previous"
            style={{ position: 'absolute', left: 24, top: '50%', transform: 'translateY(-50%)', width: 56, height: 56, borderRadius: '50%', background: 'rgba(255,255,255,0.08)', color: '#e2bd6b', border: '1px solid rgba(201,165,92,0.4)', fontSize: 24, cursor: 'pointer' }}>‹</button>
          <button onClick={(e) => { e.stopPropagation(); onIndex((index + 1) % items.length); }} aria-label="Next"
            style={{ position: 'absolute', right: 24, top: '50%', transform: 'translateY(-50%)', width: 56, height: 56, borderRadius: '50%', background: 'rgba(255,255,255,0.08)', color: '#e2bd6b', border: '1px solid rgba(201,165,92,0.4)', fontSize: 24, cursor: 'pointer' }}>›</button>
        </>
      )}
      <figure onClick={(e) => e.stopPropagation()} style={{ margin: 0, maxWidth: '90vw', maxHeight: '90vh', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
        {/\.(mp4|webm)$/i.test(cur.url || '') ? (
          <video src={cur.url} controls autoPlay style={{ maxWidth: '100%', maxHeight: '80vh', background: '#000' }} />
        ) : (
          <img src={cur.url} alt={cur.label || ''} style={{ maxWidth: '100%', maxHeight: '80vh', objectFit: 'contain', boxShadow: '0 30px 80px rgba(0,0,0,0.6)' }} />
        )}
        {(cur.label || cur.tag) && (
          <figcaption style={{ display: 'flex', alignItems: 'center', gap: 12, color: '#e8dcc1', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase' }}>
            {cur.tag && <span style={{ padding: '4px 10px', background: 'rgba(201,165,92,0.2)', color: '#e2bd6b', border: '1px solid rgba(201,165,92,0.4)' }}>{cur.tag}</span>}
            <span>{cur.label}</span>
            {items.length > 1 && <span style={{ color: 'rgba(232,220,193,0.5)' }}>· {index + 1}/{items.length}</span>}
          </figcaption>
        )}
      </figure>
    </div>
  );
};

// Interactive Master Plan: deterministic plot grid generated from the
// property's plot count. Each cell is clickable — opens a side-card with the
// plot number, area, status, facing, and a "Hold this plot" CTA that pre-fills
// the enquiry form.
const InteractiveMasterPlan = ({ property, onClose, onHold }) => {
  const inv = property.plotInventory || {};
  const total = Number(inv.total) || property.plots || 200;
  const overrides = inv.overrides || {};
  // Defensive: admin sometimes types prices in rupees not lakhs (e.g. 36000000
  // for 3.6 Cr); anything > 100 000 lakhs is almost certainly a unit-mistake.
  const normaliseLakhs = (v) => {
    const n = Number(v) || 0;
    if (!isFinite(n) || n <= 0) return 0;
    if (n > 100000) return n / 100000;
    if (n > 10000)  return n / 1000;
    return n;
  };
  const defaults = {
    status: 'available',
    area:   inv.default_area   || property.areaMin || 167,
    facing: inv.default_facing || (property.facing && property.facing[0]) || 'East',
    price_lakhs: normaliseLakhs(inv.default_price_lakhs) || (property.priceMin ? Math.round(Number(property.priceMin) * (property.priceUnit === 'Cr' ? 100 : 1)) : 50),
  };
  const plotInfo = (n) => {
    const o = overrides[String(n)] || {};
    return {
      n,
      status: o.status || defaults.status,
      area:   o.area   || defaults.area,
      facing: o.facing || defaults.facing,
      price_lakhs: normaliseLakhs(o.price_lakhs) || defaults.price_lakhs,
    };
  };
  const STATUS_META = {
    available: { fill: '#c9a55c', label: 'Available',    text: 'Available — registration open' },
    premium:   { fill: '#e2bd6b', label: 'Premium',      text: 'Premium / Corner — limited release' },
    booked:    { fill: '#b04a3a', label: 'Booked',       text: 'Booked — under registration' },
    hold:      { fill: '#8c857b', label: 'On Hold',      text: 'On hold — under negotiation' },
  };

  const cols = Math.min(20, Math.ceil(Math.sqrt(total * 1.4)));
  const rows = Math.ceil(total / cols);
  const cellW = 38, cellH = 22, gap = 4, pad = 24;
  const W = pad * 2 + cols * (cellW + gap) - gap;
  const H = pad * 2 + rows * (cellH + gap) - gap + 60; // +60 for green spine
  const spineY = pad + Math.floor(rows / 2) * (cellH + gap);

  const [selected, setSelected] = React.useState(null);
  const [filter, setFilter] = React.useState('all');

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [onClose]);

  const counts = { available: 0, premium: 0, booked: 0, hold: 0 };
  for (let i = 0; i < total; i++) counts[plotInfo(i + 1).status]++;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,15,12,0.92)',
      display: 'flex', alignItems: 'stretch', justifyContent: 'center', padding: 32,
      animation: 'msFadeIn 180ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#0a1f17', border: '1px solid rgba(201,165,92,0.3)', maxWidth: 1280, width: '100%',
        display: 'grid', gridTemplateColumns: '1fr 320px', gap: 0, overflow: 'hidden',
      }}>
        {/* Left: SVG plan */}
        <div style={{ padding: 24, overflow: 'auto', background: '#0f2a1f' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#a88841', marginBottom: 4 }}>Interactive Master Plan</div>
              <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 22, color: '#f6f1e6' }}>{property.name} · Phase I</div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {['all', 'available', 'premium', 'booked', 'hold'].map(f => (
                <button key={f} onClick={() => setFilter(f)} style={{
                  padding: '6px 12px', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
                  background: filter === f ? '#c9a55c' : 'transparent',
                  color: filter === f ? '#0a1f17' : '#e8dcc1',
                  border: '1px solid rgba(201,165,92,0.4)', cursor: 'pointer',
                }}>{f === 'all' ? 'All' : `${f} (${counts[f] || 0})`}</button>
              ))}
            </div>
          </div>
          <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block', background: '#0f2a1f' }}>
            <rect x={pad - 4} y={spineY - 4} width={W - (pad - 4) * 2} height={cellH + 8} fill="rgba(78,166,118,0.18)" />
            <text x={W / 2} y={spineY + cellH + 26} fill="rgba(232,220,193,0.5)" fontSize="10" textAnchor="middle" letterSpacing="3">CENTRAL GREEN SPINE · 60-FT AVENUE</text>
            {Array.from({ length: total }).map((_, i) => {
              const col = i % cols;
              const row = Math.floor(i / cols);
              const x = pad + col * (cellW + gap);
              const y = pad + row * (cellH + gap) + (row > rows / 2 ? cellH + gap + 30 : 0);
              if (row === Math.floor(rows / 2)) return null;
              const info = plotInfo(i + 1);
              const meta = STATUS_META[info.status] || STATUS_META.available;
              const dim = filter !== 'all' && filter !== info.status;
              const isSel = selected && selected.i === i;
              return (
                <g key={i} style={{ cursor: dim ? 'default' : 'pointer' }} onClick={() => !dim && setSelected({ i, ...info })}>
                  <rect x={x} y={y} width={cellW} height={cellH}
                    fill={meta.fill}
                    fillOpacity={dim ? 0.18 : (isSel ? 1 : 0.85)}
                    stroke={isSel ? '#fff' : 'rgba(15,42,31,0.9)'}
                    strokeWidth={isSel ? 2 : 1} />
                  {!dim && cellW > 32 && <text x={x + cellW / 2} y={y + cellH / 2 + 3} fill="#0a1f17" fontSize="8" textAnchor="middle" fontFamily="JetBrains Mono">{i + 1}</text>}
                </g>
              );
            })}
          </svg>
          <div style={{ display: 'flex', gap: 16, marginTop: 16, flexWrap: 'wrap' }}>
            {Object.entries(STATUS_META).map(([k, m]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 12, height: 12, background: m.fill, display: 'inline-block' }} />
                <span style={{ fontSize: 11, color: 'rgba(232,220,193,0.75)', letterSpacing: '0.08em' }}>{m.label}</span>
              </div>
            ))}
          </div>
        </div>
        {/* Right: details */}
        <aside style={{ background: '#0a1f17', padding: 28, borderLeft: '1px solid rgba(201,165,92,0.2)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
            <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#a88841' }}>Plot details</div>
            <button onClick={onClose} aria-label="Close" style={{ background: 'transparent', border: '1px solid rgba(201,165,92,0.4)', color: '#e2bd6b', width: 32, height: 32, borderRadius: '50%', cursor: 'pointer', fontSize: 16 }}>×</button>
          </div>
          {selected ? (
            <>
              <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 38, color: '#f6f1e6', lineHeight: 1, marginBottom: 8 }}>Plot {String(selected.i + 1).padStart(3, '0')}</div>
              <div style={{ fontSize: 12, color: STATUS_META[selected.status].fill, letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 24 }}>{STATUS_META[selected.status].text}</div>
              <dl style={{ margin: 0, display: 'grid', gridTemplateColumns: '1fr', gap: 14, color: '#e8dcc1' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid rgba(201,165,92,0.18)', paddingBottom: 10 }}>
                  <dt style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.55)' }}>Area</dt>
                  <dd style={{ margin: 0, fontFamily: 'Cormorant Garamond, serif', fontSize: 22, color: '#e2bd6b' }}>{selected.area} <span style={{ fontSize: 13, color: '#a88841' }}>{property.areaUnit || 'sq.yd'}</span></dd>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid rgba(201,165,92,0.18)', paddingBottom: 10 }}>
                  <dt style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.55)' }}>Facing</dt>
                  <dd style={{ margin: 0, fontSize: 14 }}>{selected.facing}</dd>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid rgba(201,165,92,0.18)', paddingBottom: 10 }}>
                  <dt style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.55)' }}>Indicative price</dt>
                  <dd style={{ margin: 0, fontFamily: 'Cormorant Garamond, serif', fontSize: 18, color: '#e2bd6b' }}>₹ {(selected.price_lakhs >= 100 ? (selected.price_lakhs / 100).toFixed(2) + ' Cr' : selected.price_lakhs + ' L')}</dd>
                </div>
              </dl>
              <div style={{ marginTop: 'auto', paddingTop: 28, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <button disabled={selected.status === 'booked' || selected.status === 'hold'} onClick={() => onHold(selected)}
                  className="ms-btn ms-btn-primary ms-btn-sm" style={{ width: '100%', opacity: (selected.status === 'booked' || selected.status === 'hold') ? 0.4 : 1 }}>
                  {selected.status === 'booked' ? 'Already booked' : selected.status === 'hold' ? 'On hold — call advisor' : `Hold Plot ${String(selected.i + 1).padStart(3, '0')}`}
                </button>
                <a href={`https://wa.me/919849999708?text=${encodeURIComponent(`I'd like to enquire about Plot ${selected.i + 1} at ${property.name}`)}`} target="_blank" rel="noopener"
                  className="ms-btn ms-btn-ghost ms-btn-sm" style={{ width: '100%' }}>WhatsApp our advisor</a>
              </div>
            </>
          ) : (
            <div style={{ color: 'rgba(232,220,193,0.6)', fontSize: 13, lineHeight: 1.7 }}>
              Click any plot on the master plan to see its area, facing, indicative price and current status. Plots are released in disciplined cohorts — premium / corner units are reserved for early advisors.
            </div>
          )}
        </aside>
      </div>
    </div>
  );
};

const DetailPage = () => {
  if (window.MarsanMobile && window.MarsanMobile.isMobile && window.MarsanMobile.isMobile()) {
    return <window.MarsanMobile.Property />;
  }
  const { Icon, Header, Footer } = window.MarsanComponents;
  const { PROPERTIES, NEARBY } = window.MARSAN_DATA;
  const params = new URLSearchParams(window.location.search);
  const slug = params.get('slug');
  const p = (slug ? PROPERTIES.find(x => x.slug === slug) : PROPERTIES[0]) || PROPERTIES[0];

  const [enquiryType, setEnquiryType] = React.useState('Site Visit');
  const [submitting, setSubmitting] = React.useState(false);
  const [showSuccess, setShowSuccess] = React.useState(false);
  const [reference, setReference] = React.useState('');
  const [delivery, setDelivery] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', budget: '₹50L – ₹75L', visitDate: '2026-05-15', message: '' });
  const [lightbox, setLightbox] = React.useState({ open: false, items: [], index: 0 });
  const [planOpen, setPlanOpen] = React.useState(false);
  const openLightbox = (items, index = 0) => setLightbox({ open: true, items, index });

  if (!p) {
    return (
      <div className="ms-root" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16 }}>
        <div className="ms-loader" />
        <div style={{ color: '#8c857b' }}>Loading property…</div>
      </div>
    );
  }

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    try {
      const r = await window.MarsanAPI.leads.submit({
        formType: 'property_enquiry',
        propertySlug: p.slug,
        enquiryType,
        ...form,
        pageUrl: window.location.href,
        utm: Object.fromEntries(new URLSearchParams(window.location.search).entries()),
      });
      setReference(r.reference);
      setDelivery(r.delivery);
      setShowSuccess(true);
    } catch (err) {
      window.MARSAN_TOAST(err.message || 'Submission failed', 'error');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="ms-root" style={{ width: '100%', background: '#f6f1e6' }}>
      <div style={{ background: '#0a1f17' }}><Header active="Properties" light /></div>

      <section style={{ position: 'relative', height: 720, overflow: 'hidden', background: '#0a1f17' }}>
        {p.heroUrl ? (
          <img src={p.heroUrl} alt={p.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div className="ms-img-ph ms-kenburns" style={{ position: 'absolute', inset: 0 }}><span style={{ fontSize: 12 }}>Cinematic Property Hero · Drone Pass</span></div>
        )}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(10,31,23,0.4) 0%, transparent 30%, rgba(10,31,23,0.85) 100%)' }} />

        <div style={{ position: 'absolute', top: 32, left: 56, display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.7)' }}>
          <a href="/properties.html" style={{ color: 'inherit', textDecoration: 'none' }}>Properties</a><Icon name="chevron" size={12} />
          <a href={`/properties.html?cat=${encodeURIComponent(p.category)}`} style={{ color: 'inherit', textDecoration: 'none' }}>{p.category}</a><Icon name="chevron" size={12} />
          <span style={{ color: '#e2bd6b' }}>{p.name}</span>
        </div>

        <div style={{ position: 'absolute', top: 32, right: 56, display: 'flex', gap: 12 }}>
          {[{ icon: 'heart', label: 'Save' }, { icon: 'share', label: 'Share' }, { icon: 'eye', label: '3D Tour' }].map(b => (
            <button key={b.label}
              onClick={() => {
                if (b.label === 'Share' && navigator.share) navigator.share({ title: p.name, url: window.location.href });
                else if (b.label === 'Save') window.MARSAN_TOAST(`${p.name} saved.`, 'success');
              }}
              style={{ padding: '10px 16px', background: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(10px)', border: '1px solid rgba(232,220,193,0.2)', color: '#e8dcc1', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name={b.icon} size={14} /> {b.label}
            </button>
          ))}
        </div>

        <div style={{ position: 'absolute', bottom: 56, left: 56, right: 56, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24 }}>
          <div style={{ maxWidth: 720 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
              <span className="ms-chip gold">{p.launch}</span>
              <span className="ms-chip" style={{ background: 'rgba(255,255,255,0.1)', color: '#e8dcc1', borderColor: 'rgba(232,220,193,0.25)' }}>{p.category}</span>
              <span className={`ms-status ${p.status === 'Available' ? 'available' : p.status === 'Sold Out' ? 'sold' : p.status === 'Few Left' ? 'few' : 'upcoming'}`} style={{ background: 'rgba(255,255,255,0.1)', padding: '6px 12px', color: '#e8dcc1' }}>{p.status}</span>
            </div>
            <h1 className="ms-h1" style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 300, fontSize: 88, color: '#f6f1e6', margin: '0 0 16px', lineHeight: 0.95 }}>
              {p.name}
            </h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'rgba(232,220,193,0.8)', fontSize: 16 }}>
              <Icon name="pin" size={16} color="#c9a55c" /> {p.address || p.location}
            </div>
            <div style={{ display: 'flex', gap: 48, marginTop: 36, paddingTop: 24, borderTop: '1px solid rgba(232,220,193,0.2)', flexWrap: 'wrap' }}>
              <div>
                <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.5)' }}>STARTING</div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 36, color: '#e2bd6b' }}>₹{p.priceMin}<span style={{ fontFamily: 'Cormorant Garamond, serif', fontStyle: 'italic', fontSize: 26, color: '#c9a55c', marginLeft: 10 }}>{p.priceUnit}</span></div>
              </div>
              <div>
                <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.5)' }}>{p.areaUnit === 'sq.yd' || p.areaUnit === 'acres' ? 'PLOT SIZES' : 'AREA'}</div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 36, color: '#f6f1e6' }}>{p.areaMin}<span style={{ color: '#c9a55c', margin: '0 6px' }}>–</span>{p.areaMax}<span style={{ fontFamily: 'Cormorant Garamond, serif', fontStyle: 'italic', fontSize: 26, color: '#c9a55c', marginLeft: 10 }}>{p.areaUnit}</span></div>
              </div>
              {p.rera && <div>
                <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.5)' }}>RERA</div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 22, color: '#f6f1e6', marginTop: 8 }}>{p.rera}</div>
              </div>}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 240 }}>
            <a href="#enquire" className="ms-btn ms-btn-primary ms-btn-lg" style={{ width: '100%' }}>Enquire Now <Icon name="arrow" size={14} /></a>
            <a href={`/enquire.html?type=brochure&property=${encodeURIComponent(p.slug)}`} className="ms-btn ms-btn-ghost ms-btn-lg" style={{ width: '100%' }}><Icon name="download" size={14} /> Download Brochure</a>
            <a href={`/tools.html?loan=${Math.round(p.priceMin * (p.priceUnit === 'Cr' ? 100 : 1))}`} className="ms-btn ms-btn-ghost ms-btn-sm" style={{ width: '100%' }}>
              <Icon name="diamond" size={14} /> Calculate EMI from ₹{p.priceMin}{p.priceUnit === 'Cr' ? 'Cr' : 'L'}
            </a>
            <div style={{ display: 'flex', gap: 8 }}>
              <a href={`https://wa.me/919849999708?text=${encodeURIComponent('Interested in ' + p.name)}`} target="_blank" rel="noopener" className="ms-btn ms-btn-ghost ms-btn-sm" style={{ flex: 1 }}><Icon name="whatsapp" size={14} /> WhatsApp</a>
              <a href="tel:+919849999708" className="ms-btn ms-btn-ghost ms-btn-sm" style={{ flex: 1 }}><Icon name="phone" size={14} /> Call</a>
            </div>
          </div>
        </div>
      </section>

      {/* Quick fact bar (sticky) */}
      <section style={{ background: '#fff', borderBottom: '1px solid #d9cfb8', padding: '24px 56px', position: 'sticky', top: 0, zIndex: 30 }}>
        <div style={{ maxWidth: 1440, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap' }}>
            {['Overview', 'Gallery', 'Master Plan', 'Amenities', 'Location', 'Investment', 'Enquire'].map((t, i) => (
              <a key={t} href={'#' + t.toLowerCase().replace(' ', '-')} style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: i === 0 ? '#0a1f17' : '#8c857b', cursor: 'pointer', borderBottom: i === 0 ? '1px solid #c9a55c' : '1px solid transparent', paddingBottom: 4, fontWeight: i === 0 ? 600 : 400, textDecoration: 'none' }}>{t}</a>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <a href={`/enquire.html?type=visit&property=${encodeURIComponent(p.slug)}`} className="ms-btn ms-btn-ghost-dark ms-btn-sm">Book Site Visit</a>
            <a href="#enquire" className="ms-btn ms-btn-primary ms-btn-sm">Enquire</a>
          </div>
        </div>
      </section>

      {/* OVERVIEW */}
      <section id="overview" style={{ background: '#f6f1e6', padding: '80px 56px' }}>
        <div className="ms-collapse-mobile" style={{ maxWidth: 1440, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 80 }}>
          <div>
            <div className="ms-eyebrow" style={{ marginBottom: 16 }}>About this property</div>
            <h2 className="ms-h2" style={{ color: '#0a1f17', margin: '0 0 24px' }}>{p.tagline || `${p.name} — overview.`}</h2>
            <p style={{ fontSize: 16, lineHeight: 1.8, color: '#4a4540', margin: '0 0 20px' }}>{p.description || p.tagline}</p>
          </div>
          <div style={{ background: '#fff', border: '1px solid #d9cfb8', padding: 32 }}>
            <div className="ms-eyebrow" style={{ marginBottom: 24 }}>Quick facts</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              {[
                { l: 'Plots / Units', v: p.plots || '—' },
                { l: p.areaUnit === 'sq.ft' ? 'Built-up' : 'Plot Sizes', v: `${p.areaMin}–${p.areaMax} ${p.areaUnit}` },
                { l: 'Road Width', v: p.roadWidth || '—' },
                { l: 'Facing', v: (p.facing || []).join(' · ') || '—' },
                { l: 'Approval', v: 'HMDA · RERA' },
                { l: 'Possession', v: p.launch },
              ].map(f => (
                <div key={f.l}>
                  <div className="ms-meta">{f.l.toUpperCase()}</div>
                  <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 22, color: '#0a1f17', marginTop: 4 }}>{f.v}</div>
                </div>
              ))}
            </div>
            <div style={{ height: 1, background: '#d9cfb8', margin: '24px 0' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div className="ms-meta">RERA NUMBER</div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 14, color: '#0a1f17', marginTop: 4 }}>{p.rera || '—'}</div>
              </div>
              <Icon name="check" size={20} color="#4ea676" />
            </div>
          </div>
        </div>
      </section>

      {/* GALLERY */}
      <section id="gallery" style={{ background: '#efe8d8', padding: '80px 56px' }}>
        <div style={{ maxWidth: 1440, margin: '0 auto' }}>
          <div className="ms-mobile-stack" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40 }}>
            <div>
              <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Gallery</div>
              <h2 className="ms-h2" style={{ color: '#0a1f17', margin: 0 }}>Photos, drone shots & walkthroughs.</h2>
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {['All', 'Photos', 'Drone', 'Layout', 'Video'].map((t, i) => (
                <button key={t} style={{ padding: '8px 16px', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', border: '1px solid #d9cfb8', background: i === 0 ? '#0a1f17' : '#fff', color: i === 0 ? '#e2bd6b' : '#0a1f17', cursor: 'pointer' }}>{t}</button>
              ))}
            </div>
          </div>
          {(() => {
            // Normalise gallery: items can be strings or { url, label, tag }.
            const tiles = (p.gallery && p.gallery.length ? p.gallery : []).map(g => (typeof g === 'string' ? { url: g } : g));
            const featureTile = tiles[0] || { url: p.heroUrl, label: 'Walkthrough · 2:14' };
            const rest = tiles.slice(1, 5);
            const open = (i) => openLightbox(tiles.length ? tiles : [featureTile], i);
            return (
              <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gridTemplateRows: '320px 320px', gap: 12 }} className="ms-collapse-mobile">
                <button onClick={() => open(0)} style={{ gridColumn: 'span 1', gridRow: 'span 2', position: 'relative', overflow: 'hidden', background: '#0a1f17', border: 0, padding: 0, cursor: 'pointer' }}>
                  <img src={featureTile.url || p.heroUrl} alt={featureTile.label || p.name}
                    style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', filter: 'brightness(0.9)' }} />
                  <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(201,165,92,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0a1f17' }}>
                      <Icon name="eye" size={20} />
                    </span>
                  </div>
                  <span style={{ position: 'absolute', bottom: 16, left: 16, color: '#e8dcc1', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{featureTile.label || 'Cover'}</span>
                  {featureTile.tag && <span style={{ position: 'absolute', top: 16, left: 16, padding: '4px 10px', background: 'rgba(10,31,23,0.7)', color: '#e2bd6b', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{featureTile.tag}</span>}
                </button>
                {rest.map((g, i) => (
                  <button key={i} onClick={() => open(i + 1)} style={{ position: 'relative', overflow: 'hidden', background: '#0a1f17', border: 0, padding: 0, cursor: 'pointer' }}>
                    <img src={g.url} alt={g.label || ''} loading="lazy"
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                    {g.label && <span style={{ position: 'absolute', bottom: 12, left: 12, right: 12, color: '#e8dcc1', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', textShadow: '0 1px 4px rgba(0,0,0,0.6)', textAlign: 'left' }}>{g.label}</span>}
                    {g.tag && <span style={{ position: 'absolute', top: 12, right: 12, padding: '3px 8px', background: 'rgba(10,31,23,0.7)', color: '#e2bd6b', fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase' }}>{g.tag}</span>}
                  </button>
                ))}
                {tiles.length > 5 && (
                  <button onClick={() => open(0)} style={{ position: 'absolute', right: 56, marginTop: -56, padding: '10px 18px', background: 'rgba(10,31,23,0.85)', color: '#e2bd6b', border: '1px solid #c9a55c', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer' }}>+{tiles.length - 5} more</button>
                )}
              </div>
            );
          })()}
        </div>
      </section>

      {/* AMENITIES */}
      <section id="amenities" style={{ background: '#f6f1e6', padding: '80px 56px' }}>
        <div style={{ maxWidth: 1440, margin: '0 auto' }}>
          <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Amenities & infrastructure</div>
          <h2 className="ms-h2" style={{ color: '#0a1f17', margin: '0 0 48px' }}>Built like a community, run like a club.</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, border: '1px solid #d9cfb8', background: '#fff' }} className="ms-collapse-mobile">
            {(p.amenities || window.MARSAN_DATA.AMENITIES_DEFAULT).map((a, i, arr) => (
              <div key={a.label} style={{
                padding: 32, display: 'flex', flexDirection: 'column', gap: 16,
                borderRight: (i + 1) % 4 !== 0 ? '1px solid #d9cfb8' : 'none',
                borderBottom: i < arr.length - 4 ? '1px solid #d9cfb8' : 'none',
              }}>
                <div style={{ width: 48, height: 48, border: '1px solid #c9a55c', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a88841' }}>
                  <Icon name={a.icon} size={20} />
                </div>
                <div style={{ fontSize: 14, color: '#0a1f17', fontWeight: 500 }}>{a.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* MASTER PLAN */}
      {(() => {
        // Real-data master plan summary — read from plot_inventory the admin manages.
        const inv = p.plotInventory || {};
        const total = Number(inv.total) || p.plots || 0;
        const overrides = inv.overrides || {};
        const defaultStatus = 'available';
        const counts = { available: 0, premium: 0, booked: 0, hold: 0 };
        for (let n = 1; n <= total; n++) {
          const st = (overrides[String(n)] || {}).status || defaultStatus;
          counts[st] = (counts[st] || 0) + 1;
        }
        const breakdown = [
          { c: '#c9a55c',               l: 'Available plots',         n: counts.available },
          { c: '#e2bd6b',               l: 'Premium / Corner plots',  n: counts.premium },
          { c: '#b04a3a',               l: 'Booked',                  n: counts.booked },
          counts.hold > 0 && { c: '#8c857b', l: 'On hold',             n: counts.hold },
          inv.open_green_acres ? { c: 'rgba(232,220,193,0.3)', l: 'Open green & utilities', n: `${inv.open_green_acres} ac` } : null,
        ].filter(Boolean);
        const planDescription = inv.master_plan_description || 'The layout has been designed around a central green spine, with wide internal avenues, an entrance-court arrival sequence, and a clubhouse-park complex anchoring the south boundary.';
        return (
      <section id="master-plan" style={{ background: '#0a1f17', padding: '100px 56px', position: 'relative' }} className="ms-grain">
        <div className="ms-collapse-mobile" style={{ maxWidth: 1440, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 64, position: 'relative', zIndex: 1, alignItems: 'center' }}>
          <div>
            <div className="ms-eyebrow on-dark" style={{ marginBottom: 16 }}>Master plan</div>
            <h2 className="ms-h2" style={{ color: '#f6f1e6', margin: '0 0 24px' }}>{total || 248} plots. One disciplined plan.</h2>
            <p style={{ fontSize: 15, lineHeight: 1.7, color: 'rgba(232,220,193,0.75)', margin: '0 0 32px' }}>
              {planDescription}
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {breakdown.map(s => (
                <div key={s.l} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ width: 12, height: 12, background: s.c }} />
                  <span style={{ flex: 1, fontSize: 13, color: 'rgba(232,220,193,0.85)' }}>{s.l}</span>
                  <span style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, color: '#e2bd6b' }}>{s.n}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 32 }}>
              <button onClick={() => setPlanOpen(true)} className="ms-btn ms-btn-primary ms-btn-sm">Open Interactive Plan</button>
              <a href={`/enquire.html?type=brochure&property=${encodeURIComponent(p.slug)}`} className="ms-btn ms-btn-ghost ms-btn-sm"><Icon name="download" size={14} /> PDF</a>
            </div>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(201,165,92,0.25)', padding: 16, position: 'relative', minHeight: 480 }}>
            {(() => {
              const masterPlanUrl =
                p.masterPlanUrl ||
                ((p.gallery || []).find(g => (g.tag || '').toLowerCase() === 'master plan') || {}).url ||
                ((p.gallery || []).find(g => (typeof g === 'string' ? g : g.url || '').includes('master-plan')) || {}).url ||
                null;
              return masterPlanUrl ? (
                <a href={masterPlanUrl} target="_blank" rel="noopener" title="Open full master plan in a new tab — pinch / scroll to zoom"
                  style={{ display: 'block', position: 'relative', cursor: 'zoom-in' }}>
                  <img src={masterPlanUrl} alt="Master plan"
                    style={{ width: '100%', height: 480, objectFit: 'contain', background: '#fff', display: 'block' }} />
                  <span style={{ position: 'absolute', bottom: 12, right: 12, padding: '6px 12px', background: 'rgba(10,31,23,0.85)', color: '#e2bd6b', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', border: '1px solid rgba(201,165,92,0.4)', display: 'flex', alignItems: 'center', gap: 6 }}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /><line x1="11" y1="8" x2="11" y2="14" /><line x1="8" y1="11" x2="14" y2="11" /></svg>
                    Zoom · open in new tab
                  </span>
                </a>
              ) : (
                <svg viewBox="0 0 600 380" style={{ width: '100%', height: '100%' }}>
                  <rect x="0" y="0" width="600" height="380" fill="#0f2a1f" />
                  <path d="M50 180 Q 200 140 300 200 T 550 180 L 550 220 Q 400 240 300 220 T 50 220 Z" fill="rgba(78,166,118,0.25)" />
                  <line x1="20" y1="60" x2="580" y2="60" stroke="rgba(201,165,92,0.4)" strokeWidth="2" />
                  <line x1="20" y1="320" x2="580" y2="320" stroke="rgba(201,165,92,0.4)" strokeWidth="2" />
                  {[100, 240, 380, 520].map(x => <line key={x} x1={x} y1="20" x2={x} y2="360" stroke="rgba(201,165,92,0.3)" strokeWidth="1" />)}
                  {Array.from({ length: 60 }).map((_, i) => {
                    const col = i % 12, row = Math.floor(i / 12);
                    const x = 30 + col * 46, y = 30 + row * 60;
                    if (y > 150 && y < 240) return null;
                    const colors = ['rgba(201,165,92,0.6)', 'rgba(201,165,92,0.6)', 'rgba(201,165,92,0.6)', 'rgba(226,189,107,0.85)', 'rgba(176,74,58,0.7)'];
                    return <rect key={i} x={x} y={y} width="42" height="22" fill={colors[i % 5]} stroke="rgba(15,42,31,0.8)" strokeWidth="1" />;
                  })}
                  <circle cx="300" cy="340" r="14" fill="#e2bd6b" />
                </svg>
              );
            })()}
            <div style={{ position: 'absolute', top: 24, left: 24, background: 'rgba(10,31,23,0.85)', padding: '6px 12px', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#e2bd6b' }}>Phase I · Approved</div>
          </div>
        </div>
      </section>
        );
      })()}

      {/* LOCATION */}
      <section id="location" style={{ background: '#f6f1e6', padding: '100px 56px' }}>
        <div style={{ maxWidth: 1440, margin: '0 auto' }}>
          <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Location & connectivity</div>
          <h2 className="ms-h2" style={{ color: '#0a1f17', margin: '0 0 48px' }}>{p.address || p.location}</h2>
          <div className="ms-collapse-mobile" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 32 }}>
            <div style={{ position: 'relative', height: 480, background: '#143a2a', overflow: 'hidden' }}>
              {p.latitude && p.longitude ? (
                <iframe title="map" src={`https://www.google.com/maps?q=${p.latitude},${p.longitude}&z=13&output=embed`}
                  style={{ width: '100%', height: '100%', border: 0 }} loading="lazy" />
              ) : (
                <div style={{ position: 'absolute', inset: 0,
                  backgroundImage: `linear-gradient(rgba(201,165,92,0.06) 1px, transparent 1px),
                                    linear-gradient(90deg, rgba(201,165,92,0.06) 1px, transparent 1px)`,
                  backgroundSize: '32px 32px',
                }} />
              )}
              <a href={`https://www.google.com/maps?q=${p.latitude || ''},${p.longitude || ''}`} target="_blank" rel="noopener"
                 className="ms-btn ms-btn-primary ms-btn-sm" style={{ position: 'absolute', bottom: 16, right: 16, zIndex: 2 }}>
                <Icon name="map" size={12} /> Open in Google Maps
              </a>
            </div>
            <div style={{ background: '#fff', border: '1px solid #d9cfb8', padding: 32 }}>
              <div className="ms-eyebrow" style={{ marginBottom: 20 }}>What's around</div>
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {(p.nearby || NEARBY).map((n, i, arr) => (
                  <div key={n.name} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: i < arr.length - 1 ? '1px solid #d9cfb8' : 'none' }}>
                    <div style={{ width: 36, height: 36, border: '1px solid #c9a55c', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a88841' }}>
                      <Icon name={n.type === 'School' ? 'school' : n.type === 'Hospital' ? 'hospital' : n.type === 'Metro' ? 'metro' : n.type === 'Airport' ? 'sparkle' : 'pin'} size={14} />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div className="ms-meta">{n.type}</div>
                      <div style={{ fontSize: 13, color: '#0a1f17', marginTop: 2 }}>{n.name}</div>
                    </div>
                    <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, color: '#a88841' }}>{n.dist}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* INVESTMENT */}
      <section id="investment" style={{ background: '#efe8d8', padding: '100px 56px' }}>
        <div style={{ maxWidth: 1440, margin: '0 auto' }}>
          <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Investment thesis</div>
          <h2 className="ms-h2" style={{ color: '#0a1f17', margin: '0 0 48px', maxWidth: 800 }}>Why {p.location.split(',')[0]} — and why now.</h2>
          <div className="ms-collapse-mobile" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {[
              { t: 'Corridor maturing', body: 'Highway widening complete and ORR extension funded for FY26.', s: '+18% CAGR (2021–25)' },
              { t: 'Employment anchors', body: 'Major IT campuses within a 22-km radius. 14,000+ direct jobs added in the past 24 months.', s: '14,000+ jobs · 24 mo' },
              { t: 'Best for', body: 'Long-horizon investors (5–8 yr hold) and second-home builders looking for proximity-to-airport land at sub-Cr ticket sizes.', s: 'Hold: 5–8 yrs' },
            ].map(t => (
              <div key={t.t} className="ms-reveal" style={{ background: '#fff', border: '1px solid #d9cfb8', padding: 32, position: 'relative' }}>
                <Icon name="sparkle" size={20} color="#c9a55c" />
                <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 24, color: '#0a1f17', margin: '20px 0 12px' }}>{t.t}</h3>
                <p style={{ fontSize: 14, lineHeight: 1.7, color: '#4a4540', margin: '0 0 20px' }}>{t.body}</p>
                <div style={{ height: 1, background: '#d9cfb8', margin: '20px 0' }} />
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#a88841' }}>{t.s}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ENQUIRY */}
      <section id="enquire" style={{ background: '#0a1f17', padding: '100px 56px', position: 'relative' }} className="ms-grain">
        <div className="ms-collapse-mobile" style={{ maxWidth: 1100, margin: '0 auto', position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 64, alignItems: 'start' }}>
          <div>
            <div className="ms-eyebrow on-dark" style={{ marginBottom: 16 }}>Private consultation</div>
            <h2 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 48, color: '#f6f1e6', margin: '0 0 20px', lineHeight: 1.1 }}>Tell us how we can help.</h2>
            <p style={{ fontSize: 15, lineHeight: 1.7, color: 'rgba(232,220,193,0.7)', margin: '0 0 36px' }}>
              Every enquiry is personally read by a senior advisor and answered within 4 working hours. We do not spam, we do not transfer your details to third parties.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {[
                { i: 'phone', l: 'Direct', v: '+91 98499 99708', href: 'tel:+919849999708' },
                { i: 'whatsapp', l: 'WhatsApp Concierge', v: '+91 98499 99708', href: 'https://wa.me/919849999708' },
                { i: 'mail', l: 'Email', v: 'concierge@marsanproperties.com', href: 'mailto:concierge@marsanproperties.com' },
              ].map(c => (
                <a key={c.l} href={c.href} target={c.href.startsWith('http') ? '_blank' : undefined} rel="noopener" style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 18px', border: '1px solid rgba(201,165,92,0.3)', background: 'rgba(255,255,255,0.03)', textDecoration: 'none', color: 'inherit' }}>
                  <Icon name={c.i} size={18} color="#c9a55c" />
                  <div>
                    <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.55)' }}>{c.l.toUpperCase()}</div>
                    <div style={{ color: '#e8dcc1', fontSize: 14, marginTop: 2 }}>{c.v}</div>
                  </div>
                </a>
              ))}
            </div>
          </div>

          <form onSubmit={submit} style={{ background: 'rgba(255,255,255,0.04)', backdropFilter: 'blur(20px)', border: '1px solid rgba(201,165,92,0.25)', padding: 40 }}>
            {showSuccess ? (
              <div style={{ textAlign: 'center', padding: '40px 20px' }}>
                <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'linear-gradient(135deg, #c9a55c, #e2bd6b)', margin: '0 auto 24px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0a1f17' }}>
                  <Icon name="check" size={28} />
                </div>
                <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 32, color: '#f6f1e6', margin: '0 0 12px' }}>Thank you.</h3>
                <p style={{ color: 'rgba(232,220,193,0.7)', fontSize: 15, lineHeight: 1.6, margin: '0 0 24px' }}>
                  Your enquiry has been routed to the Marsan concierge. A senior advisor will be in touch within 4 working hours.
                </p>
                <div className="ms-meta" style={{ color: '#e2bd6b' }}>REFERENCE · {reference}</div>
                {delivery && <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.4)', marginTop: 8 }}>WEBHOOK · {delivery.status} · {delivery.latency_ms}ms</div>}
                <a href="/thank-you.html" className="ms-btn ms-btn-ghost ms-btn-sm" style={{ marginTop: 28 }}>View Thank-you Page</a>
              </div>
            ) : (
              <>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                  <div>
                    <div className="ms-label on-dark">Full Name</div>
                    <input className="ms-input dark" required value={form.name} onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Your name" />
                  </div>
                  <div>
                    <div className="ms-label on-dark">Mobile</div>
                    <input className="ms-input dark" required value={form.phone} onChange={(e) => setForm(f => ({ ...f, phone: e.target.value }))} placeholder="+91" />
                  </div>
                </div>
                <div style={{ marginBottom: 16 }}>
                  <div className="ms-label on-dark">Email</div>
                  <input className="ms-input dark" type="email" value={form.email} onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))} placeholder="you@example.com" />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                  <div>
                    <div className="ms-label on-dark">Budget</div>
                    <select className="ms-select dark" value={form.budget} onChange={(e) => setForm(f => ({ ...f, budget: e.target.value }))}>
                      <option>₹50L – ₹75L</option><option>₹75L – ₹1.5Cr</option><option>₹1.5Cr+</option>
                    </select>
                  </div>
                  <div>
                    <div className="ms-label on-dark">Visit Date</div>
                    <input type="date" className="ms-input dark" value={form.visitDate} onChange={(e) => setForm(f => ({ ...f, visitDate: e.target.value }))} />
                  </div>
                </div>
                <div style={{ marginBottom: 16 }}>
                  <div className="ms-label on-dark">Enquiry Type</div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {['Site Visit', 'Callback', 'Brochure', 'Price Details'].map(t => (
                      <button type="button" key={t} onClick={() => setEnquiryType(t)} style={{
                        padding: '10px 16px', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
                        background: enquiryType === t ? 'linear-gradient(135deg, #c9a55c, #e2bd6b)' : 'transparent',
                        color: enquiryType === t ? '#0a1f17' : 'rgba(232,220,193,0.75)',
                        border: enquiryType === t ? 'none' : '1px solid rgba(232,220,193,0.25)',
                        cursor: 'pointer', fontWeight: enquiryType === t ? 600 : 400,
                      }}>{t}</button>
                    ))}
                  </div>
                </div>
                <div style={{ marginBottom: 24 }}>
                  <div className="ms-label on-dark">Message</div>
                  <textarea className="ms-input dark" rows="3" value={form.message} onChange={(e) => setForm(f => ({ ...f, message: e.target.value }))} placeholder="Anything we should know?" style={{ resize: 'vertical' }} />
                </div>
                <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 12, color: 'rgba(232,220,193,0.65)', marginBottom: 24 }}>
                  <input type="checkbox" defaultChecked required style={{ accentColor: '#c9a55c', marginTop: 2 }} />
                  I consent to Marsan Properties contacting me about this enquiry. Read the <a href="/privacy.html" style={{ color: '#e2bd6b' }}>privacy policy</a>.
                </label>
                <button type="submit" disabled={submitting} className="ms-btn ms-btn-primary ms-btn-lg" style={{ width: '100%', opacity: submitting ? 0.7 : 1 }}>
                  {submitting ? 'Sending…' : 'Request a Private Consultation'} <Icon name="arrow" size={14} />
                </button>
              </>
            )}
          </form>
        </div>
      </section>

      <Footer />

      {lightbox.open && (
        <Portal>
          <ModalBoundary onClose={() => setLightbox({ open: false, items: [], index: 0 })}>
            <Lightbox
              items={lightbox.items}
              index={lightbox.index}
              onIndex={(i) => setLightbox(s => ({ ...s, index: i }))}
              onClose={() => setLightbox({ open: false, items: [], index: 0 })}
            />
          </ModalBoundary>
        </Portal>
      )}
      {planOpen && (
        <Portal>
          <ModalBoundary onClose={() => setPlanOpen(false)}>
            <InteractiveMasterPlan
              property={p}
              onClose={() => setPlanOpen(false)}
              onHold={(plot) => {
                setPlanOpen(false);
                setEnquiryType('Site Visit');
                setForm(f => ({ ...f, message: `I'd like to hold Plot ${String(plot.i + 1).padStart(3, '0')} (${plot.area} ${p.areaUnit || 'sq.yd'} · ${plot.facing} facing).` }));
                const el = document.getElementById('investment');
                if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
              }}
            />
          </ModalBoundary>
        </Portal>
      )}
    </div>
  );
};

window.DetailPage = DetailPage;
