// screens.jsx — Marsan Properties mobile screens, faithful to the brand system
// Uses: emerald palette + gold accents + Cormorant Garamond / Inter / JetBrains Mono
// Reuses: design-system.css classes (.ms-*) and the MIcon component from marsan-components.jsx

const { useState } = React;

// ─────────────────────────────────────────────────────────────
// Brand tokens (mirror design-system.css :root)
// ─────────────────────────────────────────────────────────────
const M = {
  emeraldDeepest: '#0a1f17',
  emeraldDeep: '#0f2a1f',
  emerald: '#143a2a',
  emeraldMid: '#1a4c38',
  gold: '#c9a55c',
  goldBright: '#e2bd6b',
  goldDeep: '#a88841',
  champagne: '#e8dcc1',
  ivory: '#f6f1e6',
  ivoryWarm: '#efe8d8',
  beige: '#d9cfb8',
  charcoal: '#2a2622',
  charcoalSoft: '#4a4540',
  stone: '#8c857b',
  serif: "'Cormorant Garamond', serif",
  sans: "'Inter', sans-serif",
  mono: "'JetBrains Mono', monospace",
};

// ─────────────────────────────────────────────────────────────
// Inline icon set (subset, matches marsan-components MIcon) — kept local
// so this file works even if we render outside the parent design-canvas.
// ─────────────────────────────────────────────────────────────
const MIcon = ({ name, size = 18, color = 'currentColor', sw = 1.4 }) => {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const map = {
    menu: <path d="M3 6h18M3 12h18M3 18h18" />,
    close: <path d="M6 6l12 12M18 6L6 18" />,
    back: <path d="M15 6l-6 6 6 6" />,
    chev: <path d="M9 6l6 6-6 6" />,
    pin: <g><path d="M12 21s7-7 7-12a7 7 0 1 0-14 0c0 5 7 12 7 12z" /><circle cx="12" cy="9" r="2.5" /></g>,
    phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />,
    wa: <g><path d="M12 3a9 9 0 0 0-7.7 13.6L3 21l4.5-1.2A9 9 0 1 0 12 3z" /><path d="M8.5 9c0 4 2.5 6.5 6.5 6.5l1.5-1.5-2-2-1.5 1c-1-.5-2-1.5-2.5-2.5l1-1.5-2-2z" /></g>,
    mail: <g><rect x="3" y="5" width="18" height="14" /><path d="M3 7l9 6 9-6" /></g>,
    search: <g><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></g>,
    heart: <path d="M12 21s-8-5-8-12a5 5 0 0 1 9-3 5 5 0 0 1 9 3c0 7-8 12-8 12h-2z" />,
    share: <g><circle cx="6" cy="12" r="3" /><circle cx="18" cy="6" r="3" /><circle cx="18" cy="18" r="3" /><path d="M8.5 10.5l7-3M8.5 13.5l7 3" /></g>,
    filter: <path d="M3 5h18M6 12h12M10 19h4" />,
    map: <g><path d="M9 3L3 5v16l6-2 6 2 6-2V3l-6 2z" /><path d="M9 3v16M15 5v16" /></g>,
    arrow: <g><path d="M5 12h14M13 5l7 7-7 7" /></g>,
    plot: <g><rect x="3" y="3" width="18" height="18" /><path d="M3 9h18M3 15h18M9 3v18M15 3v18" /></g>,
    shield: <g><path d="M12 3l8 3v6c0 5-4 8-8 9-4-1-8-4-8-9V6z" /><path d="M9 12l2 2 4-4" /></g>,
    award: <g><circle cx="12" cy="9" r="6" /><path d="M9 14l-2 8 5-3 5 3-2-8" /></g>,
    diamond: <g><path d="M6 3h12l3 6-9 12L3 9z" /><path d="M3 9h18" /></g>,
    // ── Amenity icons ─────────────────────────────────────────
    club:     <g><path d="M3 21h18M5 21V8l7-5 7 5v13M9 21v-6h6v6" /></g>,
    pool:     <g><path d="M3 17c2-1 3 1 5 1s3-2 5-2 3 2 5 2 3-1 5-1" /><path d="M3 21c2-1 3 1 5 1s3-2 5-2 3 2 5 2 3-1 5-1" /><path d="M7 14V7a3 3 0 0 1 3-3 3 3 0 0 1 3 3v7M13 10h-3M13 7h-3" /></g>,
    gym:      <g><path d="M5 8v8M3 10v4M19 8v8M21 10v4M5 12h14M9 6v12M15 6v12" /></g>,
    park:     <g><path d="M12 22V14M9 14h6M5 11l3-7 3 7M14 13l3-9 3 9" /></g>,
    tree:     <g><path d="M12 22V14M7 14h10M9 14l3-7 3 7M10 8l2-5 2 5" /></g>,
    road:     <g><path d="M5 21l3-18M19 21l-3-18M12 6v3M12 12v3M12 18v3" /></g>,
    bolt:     <path d="M13 2L4 14h7l-1 8 9-12h-7z" />,
    water:    <g><path d="M12 3s7 7 7 12a7 7 0 1 1-14 0c0-5 7-12 7-12z" /><path d="M9 14a3 3 0 0 0 3 3" /></g>,
    drain:    <g><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3v18M6 6l12 12M18 6L6 18" /></g>,
    light:    <g><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" /><circle cx="12" cy="12" r="3" /></g>,
    arch:     <g><path d="M3 21V11a9 9 0 0 1 18 0v10" /><path d="M3 21h18" /></g>,
    school:   <g><path d="M3 9l9-5 9 5-9 5z" /><path d="M7 11v6c2 1 3 2 5 2s3-1 5-2v-6" /><path d="M21 9v6" /></g>,
    hospital: <g><rect x="4" y="4" width="16" height="16" /><path d="M12 8v8M8 12h8" /></g>,
    metro:    <g><rect x="6" y="3" width="12" height="14" rx="2" /><circle cx="9" cy="13" r="1" /><circle cx="15" cy="13" r="1" /><path d="M6 9h12M9 17l-2 4M15 17l2 4" /></g>,
    mall:     <g><path d="M3 9l1-4h16l1 4M5 9v11h14V9" /><path d="M9 13c0 2 1 3 3 3s3-1 3-3" /></g>,
    cctv:     <g><rect x="3" y="6" width="14" height="8" /><circle cx="10" cy="10" r="2" /><path d="M17 10h2l2-4M5 14v4M15 14v4" /></g>,
    sparkle:  <g><path d="M12 3l2 7 7 2-7 2-2 7-2-7-7-2 7-2z" /></g>,
    edit:     <g><path d="M12 20h9" /><path d="M16.5 3.5a2 2 0 0 1 2.8 2.8L7 18.6 3 19.6l1-4z" /></g>,
    upload:   <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" /></g>,
    download: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" /></g>,
    user:     <g><circle cx="12" cy="8" r="4" /><path d="M4 21c0-4 4-7 8-7s8 3 8 7" /></g>,
    eye:      <g><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" /><circle cx="12" cy="12" r="3" /></g>,
    layers:   <g><path d="M12 2L2 8l10 6 10-6z" /><path d="M2 14l10 6 10-6M2 11l10 6 10-6" /></g>,
    star:     <path d="M12 2l3 7 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z" />,
    brochure: <g><rect x="4" y="3" width="16" height="18" /><path d="M9 3v18M9 8h11M9 14h11" /></g>,
    settings: <g><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9 1.65 1.65 0 0 0 4.27 7.18l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h0a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09c0 .67.39 1.27 1 1.51a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.24.61.84 1 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" /></g>,
    plus:     <path d="M12 5v14M5 12h14" />,
    check:    <path d="M5 12l5 5 9-12" />,
  };
  // Fall back to a small dot if the icon name isn't recognised — better than
  // an empty bordered box.
  return <svg {...p}>{map[name] || <circle cx="12" cy="12" r="3" fill={color} stroke="none" />}</svg>;
};

// ─────────────────────────────────────────────────────────────
// Live-binding data: pulls from window.MARSAN_DATA (populated by
// MARSAN_BOOT()) when available, otherwise the static fallback so the
// design canvas still renders standalone.
// ─────────────────────────────────────────────────────────────
const STATIC_PROPERTIES = [
  { id: 'evara-estates', slug: 'evara-estates', name: 'Evara Estates', location: 'Pedda Golconda, Shamshabad', category: 'Farm Villa Plots', launch: 'Now Selling', status: 'Available', priceMin: '1.2', priceMax: '4.8', priceUnit: 'Cr', areaMin: '1,200', areaMax: '3,600', areaUnit: 'sq.yd', highlight: '15 min from RGIA · 108 acres · 42% open green' },
];
const STATIC_INSIGHTS = [
  { slug: 'reading-encumbrance', title: 'Reading an encumbrance certificate — a column-by-column guide', kicker: 'Due Diligence', read: '8 min', date: 'Mar 12, 2026', dek: 'The single document that proves a property is unencumbered. How to read it correctly, what each column actually means, and the five red flags that should stop a deal.' },
  { slug: 'plot-vs-apartment-roi', title: 'Plot vs apartment: a 10-year ROI study', kicker: 'Research', read: '12 min', date: 'Feb 28, 2026', dek: 'A held sample of 47 Hyderabad properties, ten years of records, and the two assumptions that decide the answer.' },
  { slug: 'airport-corridor-thesis', title: 'The airport-corridor thesis: why we are quietly buying south of ORR', kicker: 'Thesis', read: '14 min', date: 'Feb 10, 2026', dek: 'An eighteen-month study of price-per-sqft, infrastructure spend, and IT employment in the southern arc of Hyderabad — and what it means for the next decade of land.' },
  { slug: 'rera-2-norms', title: 'TG-RERA 2.0: what the new disclosure norms mean for buyers', kicker: 'Regulation', read: '7 min', date: 'Jan 22, 2026', dek: 'Telangana RERA quietly tightened in 2025. The five disclosures that now sit on every project page, and what to do with them.' },
  { slug: 'nri-buyer-guide', title: 'NRI buyer guide: from Power of Attorney to mutation in 21 days', kicker: 'Practical', read: '10 min', date: 'Jan 04, 2026', dek: 'A practical timeline for buying Indian property without flying back. PoA structuring, FEMA compliance, and the documents that actually slow things down.' },
  { slug: 'orr-west-story', title: 'The ORR West story: why land values held through 2025', kicker: 'Market', read: '9 min', date: 'Dec 18, 2025', dek: 'A boring corridor is the right corridor. Why western Hyderabad land prices barely flinched through 2024–25.' },
];

const KICKER_BY_CATEGORY = {
  'Legal': 'Due Diligence', 'Regulatory': 'Regulation', 'NRI': 'Practical',
  'Investment': 'Research', 'Market Report': 'Market', 'Investor Brief': 'Thesis',
};

function getProperties() {
  const live = window.MARSAN_DATA && window.MARSAN_DATA.PROPERTIES;
  if (!live || !live.length) return STATIC_PROPERTIES;
  return live.map((p) => ({
    id: p.slug,
    slug: p.slug,
    name: p.name,
    location: p.location || p.address || '',
    category: p.category,
    launch: p.launch || p.status || 'Active',
    status: p.status || 'Available',
    priceMin: p.priceMin,
    priceMax: p.priceMax,
    priceUnit: p.priceUnit || 'Cr',
    areaMin: p.areaMin ? Number(p.areaMin).toLocaleString('en-IN') : '—',
    areaMax: p.areaMax ? Number(p.areaMax).toLocaleString('en-IN') : '—',
    areaUnit: p.areaUnit || 'sq.yd',
    highlight: p.highlight || p.tagline || '',
    heroUrl: p.heroUrl,
    rera: p.rera,
    plots: p.plots,
    description: p.description,
    address: p.address,
    plotInventory: p.plotInventory,
    gallery: p.gallery,
    nearby: p.nearby,
  }));
}
function getInsights() {
  const live = window.MARSAN_DATA && window.MARSAN_DATA.ARTICLES;
  if (!live || !live.length) return STATIC_INSIGHTS;
  return live.map((a) => ({
    slug: a.slug,
    title: a.title,
    kicker: KICKER_BY_CATEGORY[a.category] || a.category || 'Insights',
    read: (a.read_min || 5) + ' min',
    date: a.published_at ? new Date(a.published_at).toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }) : '',
    dek: a.excerpt || '',
    cover_url: a.cover_url,
  }));
}

// Late-binding proxies — `PROPERTIES.map(...)`, `INSIGHTS[0]`, `INSIGHTS.length`
// all read live data each access. Means the screens see API data that loaded
// AFTER this file was parsed.
function makeArrayProxy(getter) {
  return new Proxy([], {
    get(_, k) {
      const arr = getter();
      if (k === Symbol.iterator) return arr[Symbol.iterator].bind(arr);
      const v = arr[k];
      return typeof v === 'function' ? v.bind(arr) : v;
    },
  });
}
const PROPERTIES = makeArrayProxy(getProperties);
const INSIGHTS   = makeArrayProxy(getInsights);

// ─────────────────────────────────────────────────────────────
// Shared chrome
// ─────────────────────────────────────────────────────────────

function MarsanWordmark({ light = false, size = 16 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, lineHeight: 1 }}>
      <img src="/assets/marsan-logo.png" alt="Marsan"
        style={{
          width: 36, height: 36, objectFit: 'contain', display: 'block',
          filter: light ? 'drop-shadow(0 1px 4px rgba(0,0,0,0.35))' : 'none',
        }} />
      <div>
        <div style={{ fontFamily: M.serif, fontSize: size, fontWeight: 500, letterSpacing: '0.22em', color: light ? M.champagne : M.emeraldDeepest }}>
          MARSAN
        </div>
        <div style={{ fontFamily: M.sans, fontSize: 8, fontWeight: 500, letterSpacing: '0.4em', textTransform: 'uppercase', color: light ? M.gold : M.goldDeep, marginTop: 3 }}>
          Properties
        </div>
      </div>
    </div>
  );
}

// Single, consistent emerald header on every screen. Layout:
//   [← back-icon]  [Marsan logo + wordmark]                        [☰ menu]
// `light` is always true now (kept as a prop for backwards compat) — the
// header is dark emerald everywhere so navigation feels seamless.
function MobileHeader({ onMenu, onBack /* light kept for backcompat */ }) {
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 60,
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '12px 16px',
      background: 'rgba(10,31,23,0.96)',
      backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
      borderBottom: '1px solid rgba(232,220,193,0.12)',
    }}>
      {onBack && (
        <button onClick={onBack} aria-label="Back" style={{
          background: 'rgba(232,220,193,0.08)', border: '1px solid rgba(232,220,193,0.18)',
          width: 32, height: 32, padding: 0, cursor: 'pointer',
          color: M.goldBright, display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <MIcon name="back" size={14} />
        </button>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <MarsanWordmark light />
      </div>
      <button onClick={onMenu} aria-label="Menu" style={{
        background: 'none', border: 'none', padding: 6, cursor: 'pointer',
        color: M.goldBright, flexShrink: 0,
      }}>
        <MIcon name="menu" size={22} />
      </button>
    </header>
  );
}

function NavDrawer({ open, onClose, nav }) {
  if (!open) return null;
  // Sectioned navigation — covers every public route on the site.
  const sections = [
    { eyebrow: 'Discover', items: [
      ['home',       'Home'],
      ['properties', 'Properties'],
      ['insights',   'Insights'],
    ]},
    { eyebrow: 'Engage', items: [
      ['enquire',    'Enquire / Book Visit'],
      ['contact',    'Contact'],
      ['tools',      'Buyer Tools'],
    ]},
    { eyebrow: 'Company', items: [
      ['about',      'About Marsan'],
      ['faq',        'FAQ'],
      ['privacy',    'Privacy & Legal'],
    ]},
  ];
  return (
    <div className="ms-grain" style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: M.emeraldDeepest, color: M.champagne,
      display: 'flex', flexDirection: 'column', overflow: 'auto',
    }}>
      <div style={{
        padding: '14px 18px', borderBottom: '1px solid rgba(232,220,193,0.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        position: 'sticky', top: 0, background: M.emeraldDeepest, zIndex: 1,
      }}>
        <MarsanWordmark light />
        <button onClick={onClose} aria-label="Close menu" style={{
          background: 'none', border: 'none', padding: 6, cursor: 'pointer', color: M.goldBright,
        }}><MIcon name="close" size={20} /></button>
      </div>
      <div style={{ padding: '20px 22px 24px', position: 'relative', zIndex: 1 }}>
        {sections.map((sec, si) => (
          <div key={sec.eyebrow} style={{ marginTop: si === 0 ? 0 : 24 }}>
            <div style={{ fontFamily: M.sans, fontSize: 10, fontWeight: 500, letterSpacing: '0.28em', textTransform: 'uppercase', color: M.gold, marginBottom: 6 }}>
              {sec.eyebrow}
            </div>
            {sec.items.map(([id, label]) => (
              <button key={id} onClick={() => { nav(id); onClose(); }} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                width: '100%', textAlign: 'left',
                padding: '14px 0', background: 'none', border: 'none',
                borderBottom: '1px solid rgba(232,220,193,0.10)',
                fontFamily: M.serif, fontSize: 22, fontWeight: 400,
                color: M.ivory, cursor: 'pointer', letterSpacing: '0.01em',
              }}>
                {label}
                <MIcon name="chev" size={16} color={M.gold} />
              </button>
            ))}
          </div>
        ))}
      </div>
      <div style={{ padding: '20px 22px', borderTop: '1px solid rgba(232,220,193,0.12)', position: 'relative', zIndex: 1 }}>
        <div style={{ fontFamily: M.sans, fontSize: 10, letterSpacing: '0.28em', textTransform: 'uppercase', color: M.gold, marginBottom: 10 }}>
          Sales Atelier
        </div>
        <a href="tel:+919849999708" style={{ fontFamily: M.serif, fontSize: 20, color: M.champagne, textDecoration: 'none', display: 'block', lineHeight: 1.3 }}>
          +91 98499 99708
        </a>
        <a href="mailto:concierge@marsanproperties.com" style={{ fontSize: 13, color: 'rgba(232,220,193,0.7)', fontFamily: M.sans, textDecoration: 'none', display: 'block', marginTop: 4 }}>
          concierge@marsanproperties.com
        </a>
      </div>
    </div>
  );
}

function ContactDock({ onEnquire }) {
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
      display: 'flex', background: M.ivory, borderTop: `1px solid ${M.beige}`,
    }}>
      <a href="tel:+919849999708" style={dockBtn(false, 'left')}>
        <MIcon name="phone" size={15} color={M.emeraldDeep} />
        <span>Call</span>
      </a>
      <a href="https://wa.me/919849999708" style={dockBtn(false)}>
        <MIcon name="wa" size={15} color={M.emeraldDeep} />
        <span>WhatsApp</span>
      </a>
      <button onClick={onEnquire} style={dockBtn(true)}>
        <span>Enquire Now</span>
      </button>
    </div>
  );
}
function dockBtn(primary, side) {
  return {
    flex: primary ? 1.4 : 1,
    padding: '14px 8px',
    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
    fontFamily: M.sans, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 500,
    color: primary ? M.emeraldDeepest : M.emeraldDeep,
    background: primary ? `linear-gradient(135deg, ${M.gold}, ${M.goldBright})` : '#fff',
    border: 'none',
    borderRight: side === 'left' ? `1px solid ${M.beige}` : (primary ? 'none' : `1px solid ${M.beige}`),
    textDecoration: 'none', cursor: 'pointer',
  };
}

function Eyebrow({ children, light = false, style }) {
  return (
    <div style={{
      fontFamily: M.sans, fontSize: 10, fontWeight: 500,
      letterSpacing: '0.28em', textTransform: 'uppercase',
      color: light ? M.goldBright : M.goldDeep,
      ...style,
    }}>{children}</div>
  );
}

function GoldDivider({ light = false, w = 56 }) {
  return <div style={{
    height: 1, width: w,
    background: `linear-gradient(90deg, transparent, ${M.gold} 30%, ${M.gold} 70%, transparent)`,
  }} />;
}

function ImagePh({ label, h = 200, beige = false }) {
  return (
    <div className={`ms-img-ph${beige ? ' beige' : ''}`} style={{ height: h, width: '100%' }}>
      <span>{label}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 1. HOME
// ─────────────────────────────────────────────────────────────

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

      {/* Hero — emerald with grain + ken-burns image behind */}
      <section className="ms-grain" style={{
        position: 'relative', background: M.emeraldDeepest, color: M.ivory,
        padding: '36px 22px 40px', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.55 }}>
          <ImagePh label="Aerial · estate twilight" h={'100%'} />
        </div>
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, rgba(10,31,23,0.55) 0%, rgba(10,31,23,0.7) 60%, ${M.emeraldDeepest} 100%)`,
        }} />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Eyebrow light>Est. 2014 · Hyderabad</Eyebrow>
          <h1 style={{
            fontFamily: M.serif, fontWeight: 300, fontSize: 40, lineHeight: 1.04,
            color: M.ivory, margin: '14px 0 0', letterSpacing: '-0.01em', textWrap: 'balance',
          }}>
            Premium properties for a <em style={{ color: M.goldBright, fontStyle: 'italic' }}>lifetime</em> of value.
          </h1>
          <p style={{
            fontFamily: M.sans, fontSize: 14, lineHeight: 1.65,
            color: 'rgba(232,220,193,0.78)', margin: '18px 0 0', maxWidth: 320,
          }}>
            A privately-curated portfolio of land, villas and residences — held to investor-grade due diligence.
          </p>

          {/* Search card — glass */}
          <div className="ms-card-glass" style={{ marginTop: 26, padding: 16 }}>
            <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.16em', color: 'rgba(232,220,193,0.55)' }}>
              LOCATION
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: M.ivory, fontSize: 14, marginTop: 6, fontFamily: M.sans }}>
              <MIcon name="pin" size={14} color={M.gold} /> Hyderabad — All corridors
            </div>
            <div style={{ height: 1, background: 'rgba(232,220,193,0.15)', margin: '14px 0' }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.16em', color: 'rgba(232,220,193,0.55)' }}>BUDGET</div>
                <div style={{ color: M.ivory, fontSize: 13, marginTop: 4, fontFamily: M.sans }}>₹50L — ₹6Cr</div>
              </div>
              <div>
                <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.16em', color: 'rgba(232,220,193,0.55)' }}>TYPE</div>
                <div style={{ color: M.ivory, fontSize: 13, marginTop: 4, fontFamily: M.sans }}>All</div>
              </div>
            </div>
            <button onClick={() => nav('properties')} className="ms-btn ms-btn-primary" style={{ width: '100%', marginTop: 16 }}>
              <MIcon name="search" size={14} color={M.emeraldDeepest} /> Search Properties
            </button>
          </div>
        </div>
      </section>

      {/* Stats strip — keep 3-up on phone (explicit `1fr 1fr 1fr` so the
          global @media collapse-grids rule doesn't catch it). */}
      <div className="ms-stats-row" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
        background: M.ivory, borderBottom: `1px solid ${M.beige}`,
      }}>
        {[['₹1,400Cr+', 'assets curated'], ['38', 'developments'], ['2,100+', 'families settled']].map(([n, l], i) => (
          <div key={i} style={{
            padding: '20px 4px', textAlign: 'center',
            borderRight: i < 2 ? `1px solid ${M.beige}` : 'none',
          }}>
            <div style={{ fontFamily: M.serif, fontSize: 21, color: M.emeraldDeepest, lineHeight: 1.05, fontWeight: 400, whiteSpace: 'nowrap' }}>{n}</div>
            <div style={{ fontFamily: M.mono, fontSize: 8.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: M.stone, marginTop: 8, whiteSpace: 'nowrap' }}>{l}</div>
          </div>
        ))}
      </div>

      {/* Featured */}
      <section style={{ padding: '40px 20px 12px', background: M.ivory }}>
        <Eyebrow>Featured</Eyebrow>
        <h2 className="ms-h2" style={{ fontSize: 28, color: M.emeraldDeepest, margin: '12px 0 6px', fontFamily: M.serif, fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.005em' }}>
          Six developments. One standard.
        </h2>
        <GoldDivider />
        <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {PROPERTIES.slice(0, 2).map((p) => (
            <PropertyMobileCard key={p.id} p={p} onClick={() => nav('property', { slug: p.slug || p.id })} />
          ))}
        </div>
        <button onClick={() => nav('properties')} className="ms-btn ms-btn-ghost-dark" style={{ width: '100%', marginTop: 18 }}>
          View All Properties <MIcon name="arrow" size={14} />
        </button>
      </section>

      {/* Why Marsan — emerald section */}
      <section className="ms-grain" style={{ padding: '48px 22px', background: M.emerald, color: M.ivory, position: 'relative' }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Eyebrow light>Why Marsan</Eyebrow>
          <h2 style={{ fontFamily: M.serif, fontSize: 28, fontWeight: 400, color: M.ivory, margin: '12px 0 8px', lineHeight: 1.1 }}>
            Quiet authority. Title-cleared inventory.
          </h2>
          <GoldDivider light />
          <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 22 }}>
            {[
              { i: 'shield', h: 'TG-RERA registered', p: 'Every project carries current Telangana RERA registration and a full disclosure pack.' },
              { i: 'plot', h: 'Title-cleared inventory', p: 'Independent legal opinion on every title. Encumbrance certificates current to 30 days.' },
              { i: 'award', h: 'Investor-grade diligence', p: 'Each plot is evaluated on the same six metrics we use for our own balance sheet.' },
              { i: 'diamond', h: 'Lifetime relationship', p: 'Mutation, possession, resale support — concierge-grade, for the lifetime of the holding.' },
            ].map((x, i) => (
              <div key={i} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                <div style={{
                  width: 40, height: 40, flexShrink: 0,
                  border: `1px solid ${M.gold}`, color: M.goldBright,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <MIcon name={x.i} size={18} color={M.goldBright} />
                </div>
                <div>
                  <div style={{ fontFamily: M.serif, fontSize: 20, color: M.ivory, marginBottom: 4 }}>{x.h}</div>
                  <div style={{ fontFamily: M.sans, fontSize: 13, lineHeight: 1.65, color: 'rgba(232,220,193,0.7)' }}>{x.p}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Insights teaser */}
      <section style={{ padding: '40px 20px', background: M.ivoryWarm }}>
        <Eyebrow>Insights</Eyebrow>
        <h2 style={{ fontFamily: M.serif, fontSize: 28, color: M.emeraldDeepest, margin: '12px 0 6px', fontWeight: 400 }}>
          Notes from a buyer's desk.
        </h2>
        <GoldDivider />
        <div style={{ marginTop: 22 }}>
          {INSIGHTS.slice(0, 3).map((it, i) => (
            <InsightRow key={it.slug} item={it} onClick={() => nav('article', { slug: it.slug })} last={i === 2} />
          ))}
        </div>
        <button onClick={() => nav('insights')} className="ms-btn ms-btn-ghost-dark" style={{ width: '100%', marginTop: 18 }}>
          All Insights <MIcon name="arrow" size={14} />
        </button>
      </section>

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

function PropertyMobileCard({ p, onClick }) {
  const statusClass = p.status === 'Available' ? 'available' : p.status === 'Sold Out' ? 'sold' : p.status === 'Few Left' ? 'few' : 'upcoming';
  const detailUrl = '/property.html?slug=' + encodeURIComponent(p.slug || p.id || 'evara-estates');
  const waText = encodeURIComponent('Hi, I\'d like to know more about ' + (p.name || ''));
  return (
    <div className="ms-card" style={{ background: '#fff' }}>
      <div onClick={onClick} style={{ position: 'relative', cursor: 'pointer' }}>
        {p.heroUrl ? (
          <img src={p.heroUrl} alt={p.name} loading="lazy"
            style={{ display: 'block', width: '100%', height: 200, objectFit: 'cover' }} />
        ) : (
          <ImagePh label={`${p.name} · ${p.category}`} h={200} />
        )}
        {p.launch && <span className="ms-chip gold" style={{ position: 'absolute', top: 12, left: 12 }}>{p.launch}</span>}
        <span className={`ms-status ${statusClass}`} style={{
          position: 'absolute', bottom: 12, left: 12,
          background: 'rgba(255,255,255,0.95)', padding: '5px 10px', color: M.emeraldDeepest,
        }}>{p.status}</span>
      </div>
      <div onClick={onClick} style={{ padding: 18, cursor: 'pointer' }}>
        <Eyebrow>{p.category}</Eyebrow>
        <h3 style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, margin: '8px 0 6px', fontWeight: 500, lineHeight: 1.15 }}>
          {p.name}
        </h3>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: M.stone, fontFamily: M.sans, fontSize: 12.5 }}>
          <MIcon name="pin" size={13} /> {p.location}
        </div>
        <div style={{ height: 1, background: M.beige, margin: '14px 0' }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.14em', color: M.stone }}>PRICE</div>
            <div style={{ fontFamily: M.serif, fontSize: 18, color: M.emeraldDeepest, marginTop: 4 }}>
              ₹{p.priceMin}<span style={{ color: M.stone, fontSize: 13 }}>–</span>{p.priceMax} <span style={{ fontSize: 13, color: M.goldDeep, fontStyle: 'italic', fontFamily: M.serif, fontWeight: 500, marginLeft: 4 }}>{p.priceUnit}</span>
            </div>
          </div>
          <div>
            <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.14em', color: M.stone }}>{p.areaUnit === 'sq.yd' ? 'PLOT' : 'AREA'}</div>
            <div style={{ fontFamily: M.serif, fontSize: 18, color: M.emeraldDeepest, marginTop: 4 }}>
              {p.areaMin}–{p.areaMax} <span style={{ fontSize: 13, color: M.goldDeep, fontStyle: 'italic', fontFamily: M.serif, fontWeight: 500, marginLeft: 4 }}>{p.areaUnit}</span>
            </div>
          </div>
        </div>
        {p.highlight && (
          <div style={{ marginTop: 12, fontFamily: M.sans, fontSize: 12, color: M.goldDeep, fontWeight: 500 }}>
            {p.highlight}
          </div>
        )}
      </div>
      {/* CTA row: gold VIEW DETAILS button + WhatsApp + Call */}
      <div style={{ display: 'flex', gap: 8, padding: '0 14px 14px' }}>
        <a href={detailUrl} className="ms-btn ms-btn-primary"
          style={{ flex: 1, padding: '12px 14px', fontSize: 11, letterSpacing: '0.18em', textAlign: 'center', display: 'inline-flex', justifyContent: 'center', alignItems: 'center', gap: 6 }}>
          View Details
        </a>
        <a href={`https://wa.me/919849999708?text=${waText}`} target="_blank" rel="noopener" aria-label="WhatsApp"
          style={{ width: 44, height: 44, border: `1px solid ${M.beige}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: M.emeraldDeep, textDecoration: 'none' }}
          onClick={(e) => e.stopPropagation()}>
          <MIcon name="wa" size={18} />
        </a>
        <a href="tel:+919849999708" aria-label="Call"
          style={{ width: 44, height: 44, border: `1px solid ${M.beige}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: M.emeraldDeep, textDecoration: 'none' }}
          onClick={(e) => e.stopPropagation()}>
          <MIcon name="phone" size={18} />
        </a>
      </div>
    </div>
  );
}

function InsightRow({ item, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', width: '100%', textAlign: 'left', gap: 14,
      padding: '16px 0', background: 'none', border: 'none',
      borderBottom: last ? 'none' : `1px solid ${M.beige}`,
      cursor: 'pointer', alignItems: 'flex-start',
    }}>
      {item.cover_url ? (
        <img src={item.cover_url} alt={item.title} loading="lazy"
          style={{ width: 88, height: 88, objectFit: 'cover', flexShrink: 0, display: 'block' }} />
      ) : (
        <div style={{ width: 88, height: 88, background: M.ivoryWarm, border: `1px solid ${M.beige}`, flexShrink: 0 }} />
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6, gap: 8 }}>
          <span style={{ fontFamily: M.sans, fontSize: 9, fontWeight: 500, letterSpacing: '0.22em', textTransform: 'uppercase', color: M.goldDeep, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {item.kicker}
          </span>
          <span style={{ fontFamily: M.mono, fontSize: 10, color: M.stone, flexShrink: 0 }}>{item.read}</span>
        </div>
        <div style={{ fontFamily: M.serif, fontSize: 16, color: M.emeraldDeepest, lineHeight: 1.25, fontWeight: 500, letterSpacing: '-0.005em' }}>
          {item.title}
        </div>
      </div>
    </button>
  );
}

function FooterCompact() {
  return (
    <footer className="ms-grain" style={{ background: M.emeraldDeepest, color: M.champagne, padding: '40px 22px 28px', position: 'relative' }}>
      <div style={{ position: 'relative', zIndex: 1 }}>
        <MarsanWordmark light />
        <p style={{ marginTop: 18, fontFamily: M.sans, fontSize: 13, lineHeight: 1.7, color: 'rgba(232,220,193,0.7)' }}>
          A premium real estate atelier curating land, villas and residences across Hyderabad's most resilient corridors.
        </p>
        <div style={{ marginTop: 24 }}>
          <div style={{ fontFamily: M.sans, fontSize: 10, fontWeight: 500, letterSpacing: '0.28em', textTransform: 'uppercase', color: M.gold, marginBottom: 10 }}>
            Sales Atelier
          </div>
          <div style={{ fontFamily: M.sans, fontSize: 13, lineHeight: 1.7, color: 'rgba(232,220,193,0.85)' }}>
            Plot 292, Prashanth Hills Colony<br />
            Khajaguda · Nanakramguda<br />
            Hyderabad, Telangana 500104
          </div>
          <div style={{ fontFamily: M.sans, fontSize: 13, marginTop: 14, color: M.gold }}>
            +91 98499 99708<br />
            concierge@marsanproperties.com
          </div>
        </div>
        <div style={{
          marginTop: 28, paddingTop: 18,
          borderTop: '1px solid rgba(232,220,193,0.1)',
          fontFamily: M.mono, fontSize: 10, letterSpacing: '0.08em', color: 'rgba(232,220,193,0.5)',
        }}>
          © 2026 Marsan Properties · TG-RERA-A-2025-0042
        </div>

        {/* Designer credit — same gold button as the desktop footer */}
        <div style={{ marginTop: 22, paddingTop: 18, borderTop: '1px solid rgba(232,220,193,0.08)', display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
          <span style={{ fontSize: 9.5, color: 'rgba(232,220,193,0.5)', letterSpacing: '0.2em', textTransform: 'uppercase', fontFamily: M.sans }}>
            Website designed by
          </span>
          <button type="button" onClick={() => window.MS_HOLO_OPEN && window.MS_HOLO_OPEN()}
            className="ms-btn ms-btn-primary"
            style={{ width: '100%', padding: '14px 16px', fontSize: 11, letterSpacing: '0.2em', textAlign: 'center' }}>
            Vasishta Reddy Aileni · 9441430088
          </button>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. PROPERTIES (LISTINGS)
// ─────────────────────────────────────────────────────────────

function PropertiesScreen({ nav, menuOpen, setMenuOpen }) {
  const [filter, setFilter] = useState('All');
  // Build chips from real categories present in inventory; fall back to a
  // reasonable static list if MARSAN_DATA isn't loaded yet.
  const allProps = getProperties();
  const liveCategories = Array.from(new Set(allProps.map(p => p.category).filter(Boolean)));
  const filters = ['All', ...(liveCategories.length ? liveCategories : ['Open Plots', 'Villas', 'Apartments', 'Farm Lands', 'Commercial'])];
  // Filter the list. Match the chip exactly OR by case-insensitive substring
  // so "Farm" still matches "Farm Lands".
  const visibleProps = filter === 'All'
    ? allProps
    : allProps.filter(p => (p.category || '').toLowerCase().includes(filter.toLowerCase()));

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

      {/* Hero strip — emerald compact */}
      <div className="ms-grain" style={{ background: M.emeraldDeepest, color: M.ivory, padding: '32px 22px 36px', position: 'relative' }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Eyebrow light>Portfolio</Eyebrow>
          <h1 style={{ fontFamily: M.serif, fontSize: 36, fontWeight: 300, margin: '12px 0 0', lineHeight: 1.05, color: M.ivory }}>
            Active developments.
          </h1>
          <div style={{ fontFamily: M.sans, fontSize: 13, color: 'rgba(232,220,193,0.65)', marginTop: 10 }}>
            {visibleProps.length} of {allProps.length} {allProps.length === 1 ? 'project' : 'projects'} · across Hyderabad
          </div>
        </div>
      </div>

      {/* Filter chips */}
      <div style={{
        position: 'sticky', top: 49, zIndex: 30,
        background: '#fff', borderBottom: `1px solid ${M.beige}`,
        padding: '12px 16px', display: 'flex', gap: 8,
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {filters.map((t) => (
          <span key={t} className="ms-chip" onClick={() => setFilter(t)} style={{
            background: filter === t ? M.emeraldDeepest : '#fff',
            color: filter === t ? M.goldBright : M.emeraldDeepest,
            borderColor: filter === t ? M.emeraldDeepest : M.beige,
            whiteSpace: 'nowrap', cursor: 'pointer', flexShrink: 0,
          }}>{t}</span>
        ))}
      </div>

      {/* Cards */}
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {visibleProps.length === 0 ? (
          <div style={{ padding: '48px 16px', textAlign: 'center', color: M.stone, fontSize: 14 }}>
            No properties match "<strong>{filter}</strong>". <button onClick={() => setFilter('All')} style={{ background: 'none', border: 'none', color: M.goldDeep, cursor: 'pointer', fontWeight: 500 }}>Clear filter</button>
          </div>
        ) : visibleProps.map((p) => (
          <PropertyMobileCard key={p.id} p={p} onClick={() => nav('property', { slug: p.slug || p.id })} />
        ))}
      </div>

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

function toolbarBtn() {
  return {
    flex: 1,
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    fontFamily: M.sans, fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
    fontWeight: 500, color: M.emeraldDeepest,
    padding: '10px 14px', border: `1px solid ${M.beige}`, background: '#fff', cursor: 'pointer',
  };
}

// ─────────────────────────────────────────────────────────────
// 3. PROPERTY DETAIL — Evara Estates
// ─────────────────────────────────────────────────────────────

function PropertyScreen({ nav, menuOpen, setMenuOpen }) {
  const p = PROPERTIES[0];
  const [tab, setTab] = useState('overview');

  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: 360 }}>
        <ImagePh label="Evara · gateway aerial" h={360} />
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, rgba(10,31,23,0.5) 0%, transparent 30%, rgba(10,31,23,0.92) 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>
        {/* Bottom title */}
        <div style={{ position: 'absolute', left: 22, right: 22, bottom: 22 }}>
          <span className="ms-chip gold" style={{ marginBottom: 12, display: 'inline-flex' }}>{p.launch}</span>
          <h1 style={{ fontFamily: M.serif, fontSize: 34, fontWeight: 300, color: M.ivory, margin: '10px 0 6px', lineHeight: 1.05, letterSpacing: '-0.01em' }}>
            {p.name}
          </h1>
          <div style={{ fontFamily: M.sans, fontSize: 13, color: 'rgba(232,220,193,0.8)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <MIcon name="pin" size={13} color={M.gold} /> {p.location}
          </div>
        </div>
      </section>

      {/* Price + size strip */}
      <div style={{
        background: '#fff', padding: '20px 22px',
        borderBottom: `1px solid ${M.beige}`,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
      }}>
        <div>
          <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.14em', color: M.stone }}>PRICE FROM</div>
          <div style={{ fontFamily: M.serif, fontSize: 24, color: M.emeraldDeepest, marginTop: 4 }}>
            ₹{p.priceMin} {p.priceUnit}
          </div>
        </div>
        <div>
          <div style={{ fontFamily: M.mono, fontSize: 10, letterSpacing: '0.14em', color: M.stone }}>PLOT SIZES</div>
          <div style={{ fontFamily: M.serif, fontSize: 24, color: M.emeraldDeepest, marginTop: 4 }}>
            {p.areaMin}–{p.areaMax} <span style={{ fontSize: 12, color: M.stone }}>sq.yd</span>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: M.ivory, display: 'flex',
        borderBottom: `1px solid ${M.beige}`,
      }}>
        {['overview', 'gallery', 'plan', 'docs'].map((id) => (
          <button key={id} onClick={() => setTab(id)} style={{
            flex: 1, padding: '14px 4px',
            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',
          }}>{id}</button>
        ))}
      </div>

      {tab === 'overview' && (
        <>
          <section style={{ padding: '32px 22px' }}>
            <Eyebrow>Overview</Eyebrow>
            <h2 style={{ fontFamily: M.serif, fontSize: 26, color: M.emeraldDeepest, margin: '12px 0 8px', fontWeight: 400, lineHeight: 1.15 }}>
              108 acres of gated eco-luxury, 15 minutes from RGIA.
            </h2>
            <GoldDivider />
            <p style={{ fontFamily: M.sans, fontSize: 14.5, lineHeight: 1.7, 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>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 22 }}>
              {[
                ['Total Land', '108 ac'],
                ['Plots', '248'],
                ['Open Green', '42%'],
                ['Approval', 'TG-RERA'],
                ['Road Width', '40 ft'],
                ['Power', 'Underground'],
              ].map(([l, v], i) => (
                <div key={i} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: 14 }}>
                  <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.14em', color: M.stone }}>{l.toUpperCase()}</div>
                  <div style={{ fontFamily: M.serif, fontSize: 20, color: M.emeraldDeepest, marginTop: 4 }}>{v}</div>
                </div>
              ))}
            </div>
          </section>

          {/* Quote */}
          <section style={{ padding: '0 22px 32px' }}>
            <div className="ms-grain" style={{ padding: '28px 22px', background: M.emerald, color: M.ivory, position: 'relative' }}>
              <div style={{ position: 'relative', zIndex: 1 }}>
                <div style={{ fontFamily: M.serif, fontSize: 56, color: M.gold, lineHeight: 0.6, marginBottom: 4 }}>"</div>
                <div style={{ fontFamily: M.serif, fontSize: 19, fontStyle: 'italic', lineHeight: 1.45, color: M.ivory }}>
                  We expect the southern arc to compound at a different cadence than ORR-West. Evara is the cornerstone holding.
                </div>
                <div style={{ fontFamily: M.sans, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: M.gold, marginTop: 14 }}>
                  — Sandeep · Marsan Properties
                </div>
              </div>
            </div>
          </section>
        </>
      )}

      {tab === 'gallery' && (
        <section style={{ padding: '24px 22px' }}>
          <Eyebrow>Gallery</Eyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18 }}>
            <ImagePh label="Gateway · 01" h={200} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <ImagePh label="Clubhouse" h={140} />
              <ImagePh label="Lake walk" h={140} />
            </div>
            <ImagePh label="Twilight aerial" h={200} beige />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <ImagePh label="Plot mockup" h={140} />
              <ImagePh label="Avenue trees" h={140} />
            </div>
          </div>
        </section>
      )}

      {tab === 'plan' && (
        <section style={{ padding: '24px 22px' }}>
          <Eyebrow>Master Plan · Phase II</Eyebrow>
          <ImagePh label="Masterplan · 142 plots" h={260} beige />
          <p style={{ fontFamily: M.sans, fontSize: 13.5, lineHeight: 1.65, color: M.charcoalSoft, marginTop: 14 }}>
            Phase II opens 142 plots across the eastern ridge — sizes from 1,200 to 3,600 sq yd. Tap to download the high-resolution masterplan with plot numbers and current availability.
          </p>
          <button className="ms-btn ms-btn-ghost-dark" style={{ width: '100%', marginTop: 16 }}>
            Download Masterplan (PDF) <MIcon name="arrow" size={14} />
          </button>
        </section>
      )}

      {tab === 'docs' && (
        <section style={{ padding: '24px 22px' }}>
          <Eyebrow>Documentation</Eyebrow>
          <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              ['TG-RERA Registration', 'P02400003421', 'Verified'],
              ['Encumbrance Certificate', 'Current to 30 days', 'Available'],
              ['Independent Title Opinion', 'Updated 2025', 'Cleared'],
              ['HMDA Layout Approval', 'LP No. 4421/2024', 'Sanctioned'],
            ].map(([h, d, s], i) => (
              <div key={i} style={{ background: '#fff', border: `1px solid ${M.beige}`, padding: '16px 18px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                  <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest }}>{h}</div>
                  <span className="ms-status available" style={{ color: M.emeraldDeepest, fontFamily: M.mono, fontSize: 9 }}>{s}</span>
                </div>
                <div style={{ fontFamily: M.mono, fontSize: 10.5, color: M.stone, letterSpacing: '0.04em' }}>{d}</div>
              </div>
            ))}
          </div>
        </section>
      )}

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

function hudBtn() {
  return {
    width: 38, height: 38,
    background: 'rgba(10,31,23,0.55)', backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    border: '1px solid rgba(232,220,193,0.15)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer',
  };
}

// ─────────────────────────────────────────────────────────────
// 4. INSIGHTS LIST
// ─────────────────────────────────────────────────────────────

function InsightsScreen({ nav, menuOpen, setMenuOpen }) {
  const [filter, setFilter] = useState('All');
  // Build chips from the kickers actually present in the article inventory.
  const allInsights = getInsights();
  const liveKickers = Array.from(new Set(allInsights.map(a => a.kicker).filter(Boolean)));
  const filters = ['All', ...(liveKickers.length ? liveKickers : ['Due Diligence', 'Research', 'Thesis', 'Regulation', 'Practical', 'Market'])];
  const items = filter === 'All' ? allInsights : allInsights.filter((i) => i.kicker === filter);

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

      {/* Header */}
      <section className="ms-grain" style={{ background: M.emeraldDeepest, color: M.ivory, padding: '36px 22px 38px', position: 'relative' }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Eyebrow light>Insights · Vol. 04</Eyebrow>
          <h1 style={{ fontFamily: M.serif, fontSize: 38, fontWeight: 300, color: M.ivory, margin: '12px 0 0', lineHeight: 1.04, letterSpacing: '-0.01em' }}>
            Notes from a buyer's <em style={{ color: M.goldBright, fontStyle: 'italic' }}>desk</em>.
          </h1>
          <p style={{ fontFamily: M.sans, fontSize: 13.5, color: 'rgba(232,220,193,0.72)', marginTop: 14, lineHeight: 1.6 }}>
            Field-tested research on Hyderabad land, regulation, and the corridors we are quietly accumulating in.
          </p>
        </div>
      </section>

      {/* Filter chips */}
      <div style={{
        position: 'sticky', top: 49, zIndex: 30,
        background: '#fff', borderBottom: `1px solid ${M.beige}`,
        padding: '12px 16px', display: 'flex', gap: 8,
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {filters.map((f) => (
          <span key={f} className="ms-chip" onClick={() => setFilter(f)} style={{
            background: filter === f ? M.emeraldDeepest : '#fff',
            color: filter === f ? M.goldBright : M.emeraldDeepest,
            borderColor: filter === f ? M.emeraldDeepest : M.beige,
            whiteSpace: 'nowrap', cursor: 'pointer', flexShrink: 0,
          }}>{f}</span>
        ))}
      </div>

      {/* Featured top */}
      <article onClick={() => nav('article', { slug: items[0]?.slug })} style={{ background: '#fff', cursor: 'pointer' }} className="ms-card">
        {items[0] && items[0].cover_url ? (
          <img src={items[0].cover_url} alt={items[0].title} loading="lazy"
            style={{ display: 'block', width: '100%', height: 220, objectFit: 'cover' }} />
        ) : (
          <ImagePh label={items[0]?.title || 'Featured insight'} h={220} />
        )}
        <div style={{ padding: 22 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <span className="ms-chip gold">{items[0]?.kicker}</span>
            <span style={{ fontFamily: M.mono, fontSize: 10, color: M.stone, letterSpacing: '0.04em' }}>{items[0]?.read}</span>
          </div>
          <h2 style={{ fontFamily: M.serif, fontSize: 24, color: M.emeraldDeepest, margin: '0 0 10px', fontWeight: 500, lineHeight: 1.18, letterSpacing: '-0.005em', textWrap: 'balance' }}>
            {items[0]?.title}
          </h2>
          <p style={{ fontFamily: M.sans, fontSize: 13, lineHeight: 1.65, color: M.charcoalSoft, margin: 0 }}>
            {items[0]?.dek}
          </p>
        </div>
      </article>

      {/* Rest as rows */}
      <div style={{ padding: '8px 22px 0', background: M.ivoryWarm }}>
        {items.slice(1).map((it, i) => (
          <button key={it.slug} onClick={() => nav('article', { slug: it.slug })} style={{
            display: 'flex', width: '100%', textAlign: 'left', gap: 14,
            padding: '20px 0', background: 'none', border: 'none',
            borderBottom: i === items.slice(1).length - 1 ? 'none' : `1px solid ${M.beige}`,
            cursor: 'pointer', alignItems: 'flex-start',
          }}>
            {it.cover_url ? (
              <img src={it.cover_url} alt={it.title} loading="lazy"
                style={{ width: 100, height: 100, objectFit: 'cover', flexShrink: 0, display: 'block' }} />
            ) : (
              <div style={{ width: 100, height: 100, background: '#fff', border: `1px solid ${M.beige}`, flexShrink: 0 }} />
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6, gap: 8 }}>
                <span style={{ fontFamily: M.sans, fontSize: 9, fontWeight: 500, letterSpacing: '0.22em', textTransform: 'uppercase', color: M.goldDeep, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {String(i + 2).padStart(2, '0')} · {it.kicker}
                </span>
                <span style={{ fontFamily: M.mono, fontSize: 10, color: M.stone, flexShrink: 0 }}>{it.read}</span>
              </div>
              <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest, lineHeight: 1.22, fontWeight: 500, letterSpacing: '-0.005em' }}>
                {it.title}
              </div>
              <div style={{ fontFamily: M.mono, fontSize: 9.5, color: M.stone, marginTop: 6, letterSpacing: '0.04em' }}>{it.date}</div>
            </div>
          </button>
        ))}
      </div>

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

// ─────────────────────────────────────────────────────────────
// 5. ARTICLE DETAIL
// ─────────────────────────────────────────────────────────────

// Tiny markdown-to-React renderer (subset matching what the article-detail
// desktop reader supports). Handles ##/### headings, paragraphs, lists,
// blockquotes, **bold**, *italic*. Tables we render as <pre> for now —
// good enough on phone, can be improved later.
function renderArticleBody(raw) {
  if (!raw) return null;
  const lines = String(raw).split('\n');
  const out = [];
  let i = 0, paraBuf = [];
  const flushPara = () => {
    if (!paraBuf.length) return;
    const text = paraBuf.join(' ');
    out.push(<p key={out.length} style={{ fontFamily: M.sans, fontSize: 14.5, lineHeight: 1.75, color: M.charcoalSoft, margin: '0 0 18px' }}>{inline(text)}</p>);
    paraBuf = [];
  };
  function inline(text) {
    // bold + italic (simple, non-greedy)
    const segments = [];
    let cursor = 0;
    const re = /(\*\*[^*]+\*\*|\*[^*]+\*)/g;
    let m;
    while ((m = re.exec(text))) {
      if (m.index > cursor) segments.push(text.slice(cursor, m.index));
      const t = m[0];
      if (t.startsWith('**')) {
        segments.push(<strong key={segments.length} style={{ color: '#0a1f17', fontWeight: 600 }}>{t.slice(2, -2)}</strong>);
      } else {
        segments.push(<em key={segments.length} style={{ color: M.goldDeep }}>{t.slice(1, -1)}</em>);
      }
      cursor = m.index + t.length;
    }
    if (cursor < text.length) segments.push(text.slice(cursor));
    return segments;
  }
  while (i < lines.length) {
    const ln = lines[i];
    const startI = i;
    if (/^##\s/.test(ln)) {
      flushPara();
      out.push(<h2 key={out.length} style={{ fontFamily: M.serif, fontSize: 24, fontWeight: 500, color: M.emeraldDeepest, margin: '28px 0 10px', letterSpacing: '-0.005em' }}>{ln.replace(/^##\s+/, '')}</h2>);
      i++;
    } else if (/^###\s/.test(ln)) {
      flushPara();
      out.push(<h3 key={out.length} style={{ fontFamily: M.serif, fontSize: 18, fontWeight: 500, color: M.emeraldDeepest, margin: '20px 0 8px' }}>{ln.replace(/^###\s+/, '')}</h3>);
      i++;
    } else if (/^>\s/.test(ln)) {
      flushPara();
      out.push(<aside key={out.length} style={{ margin: '24px 0', padding: '18px 18px', background: M.ivoryWarm, borderLeft: `3px solid ${M.gold}`, fontFamily: M.serif, fontSize: 17, fontStyle: 'italic', color: M.emeraldDeepest, lineHeight: 1.5 }}>{ln.replace(/^>\s+/, '')}</aside>);
      i++;
    } else if (/^[-*]\s/.test(ln)) {
      flushPara();
      const items = [];
      while (i < lines.length && /^[-*]\s/.test(lines[i])) {
        items.push(lines[i].replace(/^[-*]\s+/, ''));
        i++;
      }
      out.push(<ul key={out.length} style={{ fontFamily: M.sans, fontSize: 14.5, lineHeight: 1.8, color: M.charcoalSoft, margin: '0 0 18px', paddingLeft: 20 }}>{items.map((t, j) => <li key={j}>{inline(t)}</li>)}</ul>);
    } else if (/^\|/.test(ln)) {
      flushPara();
      const tableLines = [];
      while (i < lines.length && /^\|/.test(lines[i])) { tableLines.push(lines[i]); i++; }
      const splitRow = (row) => row.replace(/^\|/, '').replace(/\|\s*$/, '').split('|').map(c => c.trim());
      const rows = tableLines.map(splitRow);
      const isSep = (cells) => cells.every(c => /^:?-{2,}:?$/.test(c));
      let headerCells = null;
      let bodyRows = rows;
      if (rows.length >= 2 && isSep(rows[1])) {
        headerCells = rows[0];
        bodyRows = rows.slice(2);
      } else if (rows.length >= 1 && isSep(rows[0])) {
        bodyRows = rows.slice(1);
      }
      out.push(
        <div key={out.length} style={{ margin: '0 0 22px', overflowX: 'auto', border: `1px solid ${M.beige}`, borderRadius: 2, background: '#fff' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: M.sans, fontSize: 13, color: M.charcoalSoft }}>
            {headerCells && (
              <thead>
                <tr style={{ background: M.ivoryWarm }}>
                  {headerCells.map((c, ci) => (
                    <th key={ci} style={{ textAlign: 'left', fontFamily: M.serif, fontWeight: 500, fontStyle: 'italic', fontSize: 13.5, color: M.emeraldDeepest, padding: '12px 14px', borderBottom: `1px solid ${M.gold}`, letterSpacing: '0.01em', whiteSpace: 'nowrap' }}>{inline(c)}</th>
                  ))}
                </tr>
              </thead>
            )}
            <tbody>
              {bodyRows.map((cells, ri) => (
                <tr key={ri} style={{ background: ri % 2 === 1 ? M.ivoryWarm : '#fff' }}>
                  {cells.map((c, ci) => {
                    const numericish = /^[₹$€]?[\d,.\s%–\-+x×]+(Cr|L|sq\.?yd|sqft|acres?|yrs?)?$/i.test(c.trim());
                    return (
                      <td key={ci} style={{ padding: '11px 14px', borderTop: `1px solid ${M.beige}`, fontFamily: numericish ? M.mono : M.sans, fontSize: numericish ? 12 : 13, color: ci === 0 ? M.emeraldDeepest : M.charcoalSoft, fontWeight: ci === 0 ? 500 : 400, verticalAlign: 'top', lineHeight: 1.5 }}>{inline(c)}</td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    } else if (ln.trim() === '') {
      flushPara();
      i++;
    } else {
      paraBuf.push(ln);
      i++;
    }
    if (i === startI) i++; // safety net so we always advance
  }
  flushPara();
  return out;
}

function ArticleScreen({ nav, menuOpen, setMenuOpen }) {
  const slug = (() => {
    try { return new URLSearchParams(window.location.search).get('slug'); } catch (_) { return null; }
  })();
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useState(); // (no-op — kept for parity; actual fetch is below)
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setLoading(true); setError(null);
      try {
        if (slug && window.MarsanAPI) {
          const r = await window.MarsanAPI.articles.get(slug);
          if (!cancelled) setArticle(r.item || null);
        } else {
          // No slug → fall back to the first article we have.
          const arts = (window.MARSAN_DATA && window.MARSAN_DATA.ARTICLES) || [];
          if (!cancelled) setArticle(arts[0] || null);
        }
      } catch (e) {
        if (!cancelled) setError(e.message || 'Article not found');
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => { cancelled = true; };
  }, [slug]);

  // Insight list (for "Continue reading") and article-shape adapter.
  const adapted = article ? {
    slug:    article.slug,
    title:   article.title,
    kicker:  KICKER_BY_CATEGORY[article.category] || article.category || 'Insights',
    read:    (article.read_min || 5) + ' min',
    date:    article.published_at ? new Date(article.published_at).toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }) : '',
    dek:     article.excerpt || '',
    body:    article.body || '',
    cover_url: article.cover_url,
  } : null;
  const others = (window.MARSAN_DATA && window.MARSAN_DATA.ARTICLES || [])
    .filter(a => a.slug !== (article && article.slug)).slice(0, 3)
    .map(a => ({
      slug: a.slug, title: a.title,
      kicker: KICKER_BY_CATEGORY[a.category] || a.category || 'Insights',
      read: (a.read_min || 5) + ' min',
      date: a.published_at ? new Date(a.published_at).toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }) : '',
      dek: a.excerpt || '',
      cover_url: a.cover_url,
    }));

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

      {loading && (
        <div style={{ padding: '120px 22px', textAlign: 'center', color: M.stone, fontFamily: M.sans, fontSize: 13 }}>
          Loading article…
        </div>
      )}
      {!loading && (error || !adapted) && (
        <div style={{ padding: '60px 22px' }}>
          <h1 style={{ fontFamily: M.serif, fontSize: 28, color: M.emeraldDeepest, margin: 0, fontWeight: 400 }}>
            Article not found.
          </h1>
          <p style={{ fontFamily: M.sans, fontSize: 14, color: M.charcoalSoft, marginTop: 12 }}>{error || 'The article may have been moved or unpublished.'}</p>
          <button onClick={() => nav('insights')} className="ms-btn ms-btn-primary" style={{ marginTop: 16 }}>
            Browse Insights <MIcon name="arrow" size={14} />
          </button>
        </div>
      )}
      {!loading && adapted && (
        <article>
          <header style={{ padding: '36px 22px 28px', background: M.emeraldDeepest, color: M.ivory }}>
            <span className="ms-chip gold" style={{ background: 'rgba(201,165,92,0.16)', color: M.goldLight, borderColor: 'rgba(201,165,92,0.4)' }}>{adapted.kicker}</span>
            <h1 style={{ fontFamily: M.serif, fontSize: 32, fontWeight: 400, color: M.ivory, margin: '16px 0 0', lineHeight: 1.12, letterSpacing: '-0.01em', textWrap: 'balance' }}>
              {adapted.title}
            </h1>
            {adapted.dek && (
              <p style={{ fontFamily: M.serif, fontSize: 18, fontStyle: 'italic', color: 'rgba(232,220,193,0.78)', lineHeight: 1.5, marginTop: 18 }}>
                {adapted.dek}
              </p>
            )}
            <div style={{ marginTop: 24, paddingTop: 18, borderTop: `1px solid rgba(201,165,92,0.28)`, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 36, height: 36, border: `1px solid ${M.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: M.serif, fontSize: 15, color: M.goldLight }}>S</div>
              <div>
                <div style={{ fontFamily: M.sans, fontSize: 12.5, fontWeight: 500, color: M.ivory }}>
                  Sandeep · Marsan Properties
                </div>
                <div style={{ fontFamily: M.mono, fontSize: 10, color: 'rgba(232,220,193,0.55)', marginTop: 2, letterSpacing: '0.04em' }}>
                  {adapted.date} · {adapted.read} read
                </div>
              </div>
            </div>
          </header>

          {adapted.cover_url ? (
            <img src={adapted.cover_url} alt={adapted.title} loading="lazy"
              style={{ display: 'block', width: '100%', height: 240, objectFit: 'cover' }} />
          ) : (
            <ImagePh label={adapted.title} h={240} beige />
          )}

          <div style={{ padding: '32px 22px' }}>
            {renderArticleBody(adapted.body)}
          </div>
        </article>
      )}

      {others.length > 0 && (
        <section style={{ padding: '32px 22px', background: M.ivoryWarm, borderTop: `1px solid ${M.beige}` }}>
          <Eyebrow>Continue reading</Eyebrow>
          <GoldDivider />
          <div style={{ marginTop: 18 }}>
            {others.map((it, i) => (
              <InsightRow key={it.slug} item={it} onClick={() => nav('article', { slug: it.slug })} last={i === others.length - 1} />
            ))}
          </div>
        </section>
      )}

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

// ─────────────────────────────────────────────────────────────
// 6. CONTACT
// ─────────────────────────────────────────────────────────────

function ContactScreen({ nav, menuOpen, setMenuOpen }) {
  const [form, setForm] = useState({ name: '', email: '', phone: '', interest: 'Evara Estates', notes: '' });
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const submitForm = async (e) => {
    e.preventDefault();
    if (busy) return;
    if (!form.name.trim() || !form.phone.trim()) {
      window.MARSAN_TOAST && window.MARSAN_TOAST('Name and phone are required.', 'error');
      return;
    }
    setBusy(true);
    try {
      await window.MarsanAPI.leads.submit({
        formType: 'contact',
        ...form,
        message: form.notes,
        pageUrl: window.location.href,
      });
      setSent(true);
    } catch (err) {
      window.MARSAN_TOAST && window.MARSAN_TOAST(err.message || 'Submission failed', 'error');
    } finally {
      setBusy(false);
    }
  };

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

      {/* Header */}
      <section className="ms-grain" style={{ background: M.emeraldDeepest, color: M.ivory, padding: '36px 22px 36px', position: 'relative' }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Eyebrow light>Concierge</Eyebrow>
          <h1 style={{ fontFamily: M.serif, fontSize: 36, fontWeight: 300, color: M.ivory, margin: '12px 0 0', lineHeight: 1.05, letterSpacing: '-0.01em' }}>
            Speak directly with us.
          </h1>
          <p style={{ fontFamily: M.sans, fontSize: 13.5, color: 'rgba(232,220,193,0.72)', marginTop: 14, lineHeight: 1.6 }}>
            We respond within one working day. Site visits to Evara are best on Saturday mornings.
          </p>
        </div>
      </section>

      {/* Channels */}
      <div style={{ padding: '24px 22px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <a href="tel:+919849999708" style={chCard()}>
          <MIcon name="phone" size={18} color={M.goldDeep} />
          <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.18em', color: M.stone, marginTop: 14 }}>DIRECT CALL</div>
          <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest, marginTop: 4 }}>+91 98499 99708</div>
        </a>
        <a href="https://wa.me/919849999708" style={chCard()}>
          <MIcon name="wa" size={18} color={M.goldDeep} />
          <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.18em', color: M.stone, marginTop: 14 }}>WHATSAPP</div>
          <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest, marginTop: 4 }}>Chat now</div>
        </a>
        <a href="mailto:concierge@marsanproperties.com" style={{ ...chCard(), gridColumn: '1 / -1' }}>
          <MIcon name="mail" size={18} color={M.goldDeep} />
          <div style={{ fontFamily: M.mono, fontSize: 9.5, letterSpacing: '0.18em', color: M.stone, marginTop: 14 }}>EMAIL</div>
          <div style={{ fontFamily: M.serif, fontSize: 17, color: M.emeraldDeepest, marginTop: 4 }}>concierge@marsanproperties.com</div>
        </a>
      </div>

      {/* Form */}
      <section style={{ padding: '8px 22px 36px' }}>
        <Eyebrow>Or send an enquiry</Eyebrow>
        <GoldDivider />
        {sent ? (
          <div style={{ padding: '32px 24px', background: '#fff', border: `1px solid ${M.beige}`, marginTop: 18, textAlign: 'center' }}>
            <div style={{
              width: 52, height: 52, borderRadius: '50%',
              background: `linear-gradient(135deg, ${M.gold}, ${M.goldBright})`,
              color: M.emeraldDeepest, display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 16px', fontSize: 24,
            }}>✓</div>
            <div style={{ fontFamily: M.serif, fontSize: 24, color: M.emeraldDeepest, marginBottom: 8 }}>
              Thank you.
            </div>
            <div style={{ fontFamily: M.sans, fontSize: 13.5, color: M.charcoalSoft, lineHeight: 1.65 }}>
              We've received your enquiry and will respond within one working day.
            </div>
          </div>
        ) : (
          <form onSubmit={submitForm} style={{ marginTop: 18, display: 'grid', gap: 14 }}>
            <MField label="Name" value={form.name} onChange={(v) => setForm({ ...form, name: v })} />
            <MField label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} />
            <MField label="Phone" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} />
            <div>
              <label className="ms-label">Interested In</label>
              <select className="ms-select" value={form.interest} onChange={(e) => setForm({ ...form, interest: e.target.value })}>
                <option>Evara Estates</option>
                <option>Marsan ORR Residences</option>
                <option>Marsan Kavuri Towers</option>
                <option>Other plots</option>
                <option>General enquiry</option>
              </select>
            </div>
            <div>
              <label className="ms-label">Notes</label>
              <textarea className="ms-input" rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} style={{ resize: 'vertical' }} />
            </div>
            <button type="submit" disabled={busy} className="ms-btn ms-btn-primary ms-btn-lg" style={{ marginTop: 6, opacity: busy ? 0.7 : 1 }}>
              {busy ? 'Sending…' : 'Send Enquiry'} <MIcon name="arrow" size={14} color={M.emeraldDeepest} />
            </button>
          </form>
        )}
      </section>

      {/* Office */}
      <section style={{ padding: '32px 22px', background: M.ivoryWarm, borderTop: `1px solid ${M.beige}` }}>
        <Eyebrow>Sales Atelier</Eyebrow>
        <GoldDivider />
        <div style={{ marginTop: 18 }}>
          <ImagePh label="Map · Khajaguda · Nanakramguda" h={160} beige />
        </div>
        <div style={{ fontFamily: M.serif, fontSize: 22, color: M.emeraldDeepest, marginTop: 18, lineHeight: 1.3, fontWeight: 400 }}>
          Plot 292, Prashanth Hills Colony<br />Khajaguda · Nanakramguda
        </div>
        <div style={{ fontFamily: M.sans, fontSize: 13, color: M.stone, marginTop: 6 }}>
          Hyderabad, Telangana 500104
        </div>
      </section>

      <FooterCompact />
    </div>
  );
}

function MField({ label, value, onChange, type = 'text' }) {
  return (
    <div>
      <label className="ms-label">{label}</label>
      <input className="ms-input" type={type} value={value} onChange={(e) => onChange(e.target.value)} />
    </div>
  );
}
function chCard() {
  return {
    padding: '18px 16px 20px',
    background: '#fff',
    border: `1px solid ${M.beige}`,
    color: M.emeraldDeepest,
    textDecoration: 'none', display: 'block', cursor: 'pointer',
  };
}

// ─────────────────────────────────────────────────────────────
Object.assign(window, {
  HomeScreen, PropertiesScreen, PropertyScreen, InsightsScreen, ArticleScreen, ContactScreen,
});
