// Marsan Properties — runtime data store
// Shape mirrors the design's window.MARSAN_DATA but is filled from the API
// on boot. Pages call window.MARSAN_BOOT() before rendering.

(function () {
  const FALLBACK_TRUST = [
    { num: '01', title: 'Title-clear properties', body: 'Every project undergoes a 14-point legal due-diligence by an independent counsel before a single plot is offered.' },
    { num: '02', title: 'Transparent documentation', body: 'Sale deeds, encumbrance certificates and approvals are shared upfront — no surprises at registration.' },
    { num: '03', title: 'Strategically chosen locations', body: 'We acquire only along proven growth corridors — ORR, HITEC, Airport, and emerging IT clusters.' },
    { num: '04', title: 'Concierged site visits', body: 'Private chauffeured visits, on-site advisors and overnight stays for outstation buyers.' },
    { num: '05', title: 'Investor-grade advisory', body: 'A dedicated relationship advisor walks you through appreciation logic, exit pathways and resale support.' },
    { num: '06', title: 'Lifetime client support', body: 'A single point of contact — for registration, mutation, construction and resale — even years after handover.' },
  ];

  const FALLBACK_AMENITIES = [
    { icon: 'road', label: 'Internal BT roads' },
    { icon: 'bolt', label: 'Underground electricity' },
    { icon: 'water', label: 'Treated water supply' },
    { icon: 'drain', label: 'Stormwater drainage' },
    { icon: 'light', label: 'Avenue lighting' },
    { icon: 'tree', label: 'Avenue plantation' },
    { icon: 'arch', label: 'Grand entrance arch' },
    { icon: 'shield', label: '24x7 security' },
    { icon: 'club', label: 'Private clubhouse' },
    { icon: 'park', label: 'Themed gardens' },
    { icon: 'pool', label: 'Swimming pool' },
    { icon: 'gym', label: 'Wellness centre' },
  ];

  const FALLBACK_NEARBY = [
    { type: 'Highway', name: 'NH-44 (Hyderabad–Bangalore)', dist: '0.8 km' },
    { type: 'Airport', name: 'Rajiv Gandhi Intl. Airport', dist: '34 km' },
    { type: 'IT Hub', name: 'Financial District', dist: '22 km' },
    { type: 'School', name: 'Oakridge International', dist: '9 km' },
    { type: 'Hospital', name: 'Continental Hospital', dist: '24 km' },
    { type: 'Metro', name: 'Shamshabad Metro (Proposed)', dist: '6 km' },
    { type: 'Mall', name: 'Sarath City Capital Mall', dist: '28 km' },
    { type: 'Railway', name: 'Shadnagar Railway Stn.', dist: '4 km' },
  ];

  const FALLBACK_HOMEPAGE = {
    hero: {
      eyebrow: 'Est. 2014 · Hyderabad',
      // headline is rendered word-by-word with the italic word marked with **asterisks**.
      headline: 'Premium properties for a *lifetime* of value.',
      sub: "A privately-curated portfolio of land, villas, residences and commercial spaces — assembled along Hyderabad's most resilient growth corridors and held to investor-grade due diligence.",
      image_url: '/assets/evara/hero-villa-twilight.jpg',
      video_url: '/assets/evara/hero-villa-twilight.mp4',
    },
    stats: [
      { value: '₹1,400 Cr+', label: 'Inventory under management' },
      { value: '38',         label: 'Active developments' },
      { value: '2,100+',     label: 'Families settled' },
    ],
    featured: {
      eyebrow: 'The Marsan Portfolio',
      title:   '', // empty → auto-derive from PROPERTIES.length
      body:    'Our active inventory is small by design. Every project on this page has cleared a 14-point legal review, has approved master plans on file, and is escorted to handover by a dedicated relationship advisor.',
    },
    categories: {
      eyebrow: 'A category for every conviction',
      title:   'The categories we curate.',
      body:    'Whether you are buying a forever home, building a legacy estate or deploying capital across asset classes — Marsan curates inventory across categories with different risk, holding and yield profiles.',
    },
    trust: {
      eyebrow: 'Why families choose Marsan',
      title:   'Six commitments. Independently audited. Delivered every time.',
      body:    "Real estate moves on trust. We've written ours down — and audit ourselves against it every quarter.",
    },
    process: {
      eyebrow: 'The Marsan process',
      title:   'From first enquiry to keys in hand — in five guided steps.',
      steps: [
        { roman: 'I',   title: 'Private brief',         body: 'A 30-minute call to understand your goal, budget, horizon and family.' },
        { roman: 'II',  title: 'Curated shortlist',     body: 'A 3–5 property edit hand-picked to your brief, with full legal files.' },
        { roman: 'III', title: 'Concierged visits',     body: 'Chauffeured site visits with on-ground advisors and overnight stays.' },
        { roman: 'IV',  title: 'Transparent paperwork', body: 'Digital due-diligence pack, sale agreement walk-through, registration support.' },
        { roman: 'V',   title: 'Lifetime stewardship',  body: 'A single advisor on-call for mutation, construction, resale — even years later.' },
      ],
    },
    testimonials_section: { show: true, eyebrow: 'From the families we serve' },
    insights_section: {
      show: true,
      eyebrow: 'Marsan Insights',
      title:   'Notes on Hyderabad real estate.',
      body:    'Quarterly intelligence on growth corridors, micro-market pricing, regulatory shifts and capital strategy — written for buyers and investors, not for clicks.',
    },
    cta: {
      eyebrow: 'Begin your search',
      title:   'Spend a quiet hour with us.',
      body:    "Tell us your brief — horizon, budget, family, intent — and we'll send back a 3-property edit within 48 hours. No pressure. No mass mailers.",
      primary: 'Request a Private Consultation',
    },
  };

  // Deep-merge user overrides onto the fallback so partial edits work.
  function merge(base, over) {
    if (!over || typeof over !== 'object' || Array.isArray(over)) return over !== undefined ? over : base;
    const out = { ...base };
    for (const k of Object.keys(over)) out[k] = merge(base?.[k], over[k]);
    return out;
  }

  window.MARSAN_DATA = {
    PROPERTIES: [],
    CATEGORIES: [],
    TRUST_PILLARS: FALLBACK_TRUST,
    TESTIMONIALS: [],
    AMENITIES_DEFAULT: FALLBACK_AMENITIES,
    NEARBY: FALLBACK_NEARBY,
    ARTICLES: [],
    HOMEPAGE: FALLBACK_HOMEPAGE,
  };
  window.MARSAN_HOMEPAGE_DEFAULT = FALLBACK_HOMEPAGE;
  window.MARSAN_HOMEPAGE_MERGE = merge;

  // camelCase the snake_case fields the API returns.
  function normalizeProperty(p) {
    return {
      id: p.id,
      slug: p.slug,
      name: p.name,
      category: p.category,
      location: p.location,
      address: p.address,
      priceMin: Number(p.price_min),
      priceMax: Number(p.price_max),
      priceUnit: p.price_unit,
      areaMin: Number(p.area_min),
      areaMax: Number(p.area_max),
      areaUnit: p.area_unit,
      status: p.status,
      launch: p.launch,
      rera: p.rera,
      facing: p.facing || [],
      plots: p.plots,
      roadWidth: p.road_width,
      highlight: p.highlight,
      tagline: p.tagline,
      image: p.image,
      featured: p.featured,
      heroUrl: p.hero_url,
      gallery: p.gallery || [],
      amenities: (p.amenities && p.amenities.length) ? p.amenities : FALLBACK_AMENITIES,
      nearby: (p.nearby && p.nearby.length) ? p.nearby : FALLBACK_NEARBY,
      description: p.description,
      latitude: p.latitude,
      longitude: p.longitude,
      plotInventory: p.plot_inventory || {},
    };
  }

  window.MARSAN_BOOT = async function () {
    if (!window.MarsanAPI) return;
    try {
      const [props, cats, tests, articles, hp] = await Promise.all([
        window.MarsanAPI.properties.list().catch(() => ({ items: [] })),
        window.MarsanAPI.properties.categories().catch(() => ({ items: [] })),
        window.MarsanAPI.testimonials.list().catch(() => ({ items: [] })),
        window.MarsanAPI.articles.list().catch(() => ({ items: [] })),
        window.MarsanAPI.homepage.get().catch(() => ({ value: null })),
      ]);
      window.MARSAN_DATA.PROPERTIES = (props.items || []).map(normalizeProperty);
      window.MARSAN_DATA.CATEGORIES = cats.items || [];
      window.MARSAN_DATA.TESTIMONIALS = tests.items || [];
      window.MARSAN_DATA.ARTICLES = articles.items || [];
      if (hp && hp.value) {
        window.MARSAN_DATA.HOMEPAGE = merge(FALLBACK_HOMEPAGE, hp.value);
      }
    } catch (e) {
      console.error('MARSAN_BOOT failed', e);
    }
  };

  window.MARSAN_NORMALIZE_PROPERTY = normalizeProperty;
})();
