// App shell — page router

const PAGE_META = {
  'home':            { title: 'AMG · Ashok Malhotra Group · Premium Real Estate in Ludhiana',       desc: 'Ashok Malhotra Group (AMG) — 40 years of premier commercial and residential real estate across Punjab. Explore Palm Marina, One AMG, Palm Garden, and more.' },
  'commercial':      { title: 'Commercial Projects · AMG Real Estate Ludhiana',                      desc: 'World-class commercial developments in Ludhiana — Palm Marina, One AMG, Palm Walk. High-footfall malls, shops, and offices designed for brand growth.' },
  'residential':     { title: 'Residential Projects · AMG Real Estate Ludhiana',                     desc: 'Premium residential townships in Ludhiana — Palm Garden, Palm City, Palm Enclave, Maurya Greens. RERA-approved homes built for lasting value.' },
  'about':           { title: 'About AMG · 40 Years of Real Estate Legacy in Punjab',                desc: 'Founded in 1985 by Ashok Malhotra, AMG has shaped Ludhiana\'s real estate landscape for four decades. Trusted by 10,000+ investor families across Punjab.' },
  'leadership':      { title: 'Leadership · Ashok Malhotra Group',                                   desc: 'Meet the visionaries behind AMG — Ashok Malhotra (Founder & Chairman) and Karan Malhotra. Four decades of real estate leadership in Punjab.' },
  'contact':         { title: 'Contact AMG · Book a Consultation · Ludhiana',                        desc: 'Book a consultation or reach out to AMG. Shop No 14-15, Palm Heights, Sidhwan Canal Road, Ludhiana – 141122. Call +91 70872-15304.' },
  'palm-marina':     { title: 'Palm Marina · Landmark Commercial Mall · Canal Road, Ludhiana',       desc: '400,000 sq.ft. mixed-use destination on Canal Road, South City, Ludhiana. Retail, dining, gaming, and cinema — projected 12.4 lakh annual footfall.' },
  'one-amg':         { title: 'One AMG · Neighbourhood Commercial Hub · Dugri, Ludhiana',            desc: 'Curated neighbourhood commercial hub in Dugri, Ludhiana. Fashion, food, and daily-needs brands in a community-first commercial destination.' },
  'palm-walk':       { title: 'Palm Walk · Commercial Spaces · Ludhiana',                            desc: 'Palm Walk by AMG — premium retail and office spaces in Ludhiana designed for high-growth brands and professional businesses.' },
  'palm-garden':     { title: 'Palm Garden · Residential Township · Sahnewal, Ludhiana',             desc: 'Premium residential township at Sahnewal, Ludhiana. Spacious plots in a master-planned green community by AMG.' },
  'palm-city-2':     { title: 'Palm City · Residential Township · Ludhiana',                         desc: 'Palm City — AMG\'s established residential township in Ludhiana. Well-connected, planned community with plots and homes for every stage of life.' },
  'palm-enclave':    { title: 'Palm Enclave · Residential Enclave · Ludhiana',                       desc: 'Palm Enclave — RERA-approved premium residential plots in a secure, landscaped community by AMG, Ludhiana.' },
  'maurya-greens':   { title: 'Maurya Greens · Luxury Residential Township · Ludhiana',              desc: 'Maurya Greens — luxury residential township by AMG with premium amenities and lush green surroundings in Ludhiana, Punjab.' },
  'palm-city-ph-ii': { title: 'Palm City Phase II · Residential Township · Ludhiana',                desc: 'Palm City Phase II — AMG\'s next-generation residential township in Ludhiana. Expansive RERA-approved plots for discerning investors.' },
  'ashok-malhotra':  { title: 'Ashok Malhotra · Founder & Chairman · AMG Real Estate',               desc: 'Meet Ashok Malhotra — founder and chairman of Ashok Malhotra Group. 40+ years shaping Ludhiana\'s commercial and residential real estate landscape.' },
  'karan-malhotra':  { title: 'Karan Malhotra · Director · AMG Real Estate',                         desc: 'Meet Karan Malhotra — driving AMG\'s next chapter of commercial and residential excellence across Punjab.' },
  'brands':          { title: 'Partner Brands · AMG Real Estate Ludhiana',                           desc: '120+ national and regional brands that have chosen AMG commercial destinations across Ludhiana and Punjab.' },
  'news':            { title: 'News & Updates · AMG Real Estate',                                    desc: 'Latest news, project launches, and announcements from Ashok Malhotra Group — Ludhiana\'s premier real estate developer.' },
  'faq':             { title: 'FAQ · AMG Real Estate Ludhiana',                                      desc: 'Frequently asked questions about investing with AMG, RERA compliance, project locations, payment plans, and more.' },
  'florence':        { title: 'Florence · Residential Project · AMG Ludhiana',                    desc: 'Florence — an upcoming residential project by Ashok Malhotra Group, Ludhiana. Register your interest for early updates on plots, pricing, and site visits.' },
  'disclaimer':      { title: 'Disclaimer · AMG Real Estate',                                        desc: 'Important disclaimers regarding AMG real estate projects, pricing, and RERA compliance.' },
};

function updateMeta(pageId) {
  const m = PAGE_META[pageId] || PAGE_META['home'];
  document.title = m.title;
  const setMeta = (sel, val) => { const el = document.querySelector(sel); if (el) el.setAttribute('content', val); };
  setMeta('meta[name="description"]', m.desc);
  setMeta('meta[property="og:title"]', m.title);
  setMeta('meta[property="og:description"]', m.desc);
  setMeta('meta[name="twitter:title"]', m.title);
  setMeta('meta[name="twitter:description"]', m.desc);
}

const { useState: useStateApp, useEffect: useEffectApp } = React;
const { motion: motionApp, AnimatePresence: AP } = Motion;

function useColorMode() {
  const getInitial = () => {
    try {
      const s = localStorage.getItem('amg-color-mode');
      if (s === 'light' || s === 'dark') return s;
    } catch(e) {}
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  };
  const [mode, setMode] = useStateApp(getInitial);

  useEffectApp(() => {
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const onSys = (e) => {
      try { if (!localStorage.getItem('amg-color-mode')) setMode(e.matches ? 'dark' : 'light'); } catch(err) {}
    };
    mq.addEventListener('change', onSys);
    return () => mq.removeEventListener('change', onSys);
  }, []);

  const toggle = () => {
    setMode(m => {
      const next = m === 'dark' ? 'light' : 'dark';
      try { localStorage.setItem('amg-color-mode', next); } catch(e) {}
      return next;
    });
  };

  return [mode, toggle];
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/(window.SITE_CONFIG || {
  "theme":            "graphite",
  "displayFont":      "Cormorant Garamond",
  "heroFont":         "Italiana",
  "bodyFont":         "Jost",
  "displayTracking":  -2,
  "displayWeight":    400,
  "accent":           "#C8A86B"
})/*EDITMODE-END*/;

const THEMES = {
  midnight: { base: '#0A0A0B', elev: '#141416', card: 'rgba(20,20,22,0.55)', light: 'rgba(250,248,244,0.06)', fg: '#FAF8F4', faint: 'rgba(250,248,244,0.12)' },
  obsidian: { base: '#13130F', elev: '#1C1B16', card: 'rgba(28,27,22,0.55)', light: 'rgba(245,239,225,0.06)', fg: '#F5EFE1', faint: 'rgba(245,239,225,0.12)' },
  graphite: { base: '#1A1A1D', elev: '#23232A', card: 'rgba(35,35,42,0.55)', light: 'rgba(245,242,235,0.07)', fg: '#F5F2EB', faint: 'rgba(245,242,235,0.14)' },
  pewter:   { base: '#262428', elev: '#312E33', card: 'rgba(49,46,51,0.55)', light: 'rgba(247,242,232,0.08)', fg: '#F7F2E8', faint: 'rgba(247,242,232,0.16)' },
  porcelain:{ base: '#F4EFE4', elev: '#EAE3D2', card: 'rgba(255,253,247,0.65)', light: 'rgba(28,24,18,0.04)', fg: '#1C1812', faint: 'rgba(28,24,18,0.10)' },
  champagne:{ base: '#1F1A14', elev: '#2A241B', card: 'rgba(42,36,27,0.55)', light: 'rgba(245,228,193,0.07)', fg: '#F5E4C1', faint: 'rgba(245,228,193,0.14)' },
};

const DISPLAY_FONTS = ['Italiana', 'Bodoni Moda', 'Playfair Display', 'Cormorant Garamond', 'Cinzel', 'Marcellus', 'Libre Caslon Text', 'Instrument Serif'];
const BODY_FONTS = ['Jost', 'Outfit', 'Manrope', 'Tenor Sans', 'Cormorant', 'Geist'];

function applyTweaks(t) {
  const theme = THEMES[t.theme] || THEMES.midnight;
  const r = document.documentElement.style;
  r.setProperty('--bg-base', theme.base);
  r.setProperty('--bg-elev', theme.elev);
  r.setProperty('--bg-card', theme.card);
  r.setProperty('--bg-light', theme.light);
  r.setProperty('--ink-fg', theme.fg);
  r.setProperty('--ink-faint', theme.faint);
  r.setProperty('--accent', t.accent);
  r.setProperty('--font-display', `'${t.displayFont}', serif`);
  r.setProperty('--font-hero', `'${t.heroFont || t.displayFont}', serif`);
  r.setProperty('--font-sans', `'${t.bodyFont}', system-ui, sans-serif`);
  r.setProperty('--display-tracking', `${t.displayTracking / 100}em`);
  r.setProperty('--display-weight', String(t.displayWeight));
}

// Canonical URL for every page id — real paths, .htaccess rewrites all to index.html
const PAGE_PATHS = {
  'home':            '/',
  'commercial':      '/commercial',
  'residential':     '/residential',
  'about':           '/about',
  'leadership':      '/leadership',
  'contact':         '/contact',
  'disclaimer':      '/disclaimer',
  // Commercial projects
  'palm-marina':       '/commercial/palm-marina',
  'one-amg':           '/commercial/one-amg',
  'palm-city-ph-ii':   '/residential/palm-city-ph-ii',
  'palm-walk':         '/commercial/palm-heights',
  // Residential projects
  'palm-garden':       '/residential/palm-garden',
  'palm-city-2':       '/residential/palm-city-2',
  'palm-enclave':      '/residential/palm-enclave',
  'florence':          '/residential/florence',
  'maurya-greens':     '/residential/maurya-greens',
  // Leadership profiles
  'ashok-malhotra':    '/leadership/ashok-malhotra',
  'karan-malhotra':    '/leadership/karan-malhotra',
  // Info pages
  'brands':            '/brands',
  'faq':               '/faq',
  'news':              '/news',
  'config':            '/config',
};

// Map the last URL segment back to a page id
const SEG_TO_PAGE = {
  '':                'home',
  'commercial':      'commercial',
  'residential':     'residential',
  'about':           'about',
  'leadership':      'leadership',
  'contact':         'contact',
  'disclaimer':      'disclaimer',
  'palm-marina':      'palm-marina',
  'one-amg':          'one-amg',
  'palm-city-ph-ii':  'palm-city-ph-ii',
  'palm-heights':     'palm-walk',
  'palm-garden':      'palm-garden',
  'palm-city-2':      'palm-city-2',
  'palm-enclave':     'palm-enclave',
  'florence':          'florence',
  'maurya-greens':    'maurya-greens',
  'ashok-malhotra':   'ashok-malhotra',
  'karan-malhotra':   'karan-malhotra',
  'brands':           'brands',
  'faq':              'faq',
  'news':             'news',
  'config':           'config',
};

function pageFromPath() {
  const path = window.location.pathname.replace(/^\//, '');
  const segs = path.split('/').filter(Boolean);
  const last = segs[segs.length - 1] || '';
  return SEG_TO_PAGE[last] || 'home';
}

function App() {
  const [page, _setPage] = useStateApp(pageFromPath);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [colorMode, toggleColorMode] = useColorMode();

  // Wraps state update with History API so the browser back button works.
  const setPage = (id) => {
    const path = PAGE_PATHS[id] || `/${id}`;
    window.history.pushState({ page: id }, '', path);
    _setPage(id);
    updateMeta(id);
    window.scrollTo(0, 0);
  };

  useEffectApp(() => { window.__setPage = setPage; }, []);
  useEffectApp(() => {
    const effectiveTheme = colorMode === 'light' ? 'porcelain' : t.theme;
    applyTweaks({ ...t, theme: effectiveTheme });
    document.documentElement.classList.toggle('light', colorMode === 'light');
  }, [t, colorMode]);

  // Stamp the initial history entry so pressing back from the first page
  // returns to the browser's previous site rather than breaking the app.
  useEffectApp(() => {
    const id = pageFromPath();
    const path = PAGE_PATHS[id] || `/${id}`;
    window.history.replaceState({ page: id }, '', path);
    updateMeta(id);
  }, []);

  // Sync React state when the user presses browser back / forward.
  useEffectApp(() => {
    const onPop = (e) => {
      const id = (e.state && e.state.page) || pageFromPath();
      _setPage(id);
      updateMeta(id);
      window.scrollTo(0, 0);
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  useEffectApp(() => {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: 'page_view', page });
  }, [page]);

  let Page;
  if (page === 'home')               Page = <HomePage setPage={setPage}/>;
  else if (page === 'commercial')    Page = <CommercialPage setPage={setPage}/>;
  else if (page === 'residential')   Page = <ResidentialPage setPage={setPage}/>;
  else if (page === 'leadership')    Page = <LeadershipPage setPage={setPage}/>;
  else if (page === 'ashok-malhotra') Page = <AshokMalhotraPage setPage={setPage}/>;
  else if (page === 'karan-malhotra') Page = <KaranMalhotraPage setPage={setPage}/>;
  else if (page === 'brands')        Page = <BrandsPage setPage={setPage}/>;
  else if (page === 'faq')           Page = <FAQPage setPage={setPage}/>;
  else if (page === 'about')         Page = <AboutPage setPage={setPage}/>;
  else if (page === 'disclaimer')    Page = <DisclaimerPage/>;
  else if (page === 'contact')       Page = <ContactPage/>;
  else if (page === 'maurya-greens') Page = <MauryaGreensPage setPage={setPage}/>;
  else if (page === 'palm-enclave')  Page = <PalmEnclavePage setPage={setPage}/>;
  else if (page === 'florence')        Page = <FlorencePage setPage={setPage}/>;
  else if (page === 'palm-garden')   Page = <PalmGardenPage setPage={setPage}/>;
  else if (page === 'palm-city-2')   Page = <PalmCity2Page setPage={setPage}/>;
  else if (page === 'palm-marina')   Page = <PalmMarinaPage setPage={setPage}/>;
  else if (page === 'one-amg')       Page = <OneAMGPage setPage={setPage}/>;
  else if (page === 'palm-city-ph-ii') Page = <PalmCityPhIIPage setPage={setPage}/>;
  else if (page === 'palm-walk')     Page = <PalmWalkPage setPage={setPage}/>;
  else if (page === 'news')          Page = <NewsPage setPage={setPage}/>;
  else Page = <HomePage setPage={setPage}/>;

  return (
    <div data-screen-label={`AMG · ${page}`}>
      <Nav page={page} setPage={setPage} colorMode={colorMode} toggleColorMode={toggleColorMode}/>
      <AP mode="wait" initial={false}>
        <motionApp.div
          key={page}
          initial={{ opacity: 0, y: 14, filter: 'blur(6px)' }}
          animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
          exit={{ opacity: 0, y: -10, filter: 'blur(4px)' }}
          transition={{ duration: 0.38, ease: [0.22, 1, 0.36, 1] }}
        >
          {Page}
        </motionApp.div>
      </AP>
      <Footer setPage={setPage}/>
      <TweaksPanel title="Tweaks">
        <TweakSection label="Atmosphere"/>
        <TweakSelect label="Background" value={t.theme}
          options={[
            { value: 'midnight',  label: 'Midnight (current)' },
            { value: 'obsidian',  label: 'Obsidian — warm noir' },
            { value: 'graphite',  label: 'Graphite — softer dark' },
            { value: 'pewter',    label: 'Pewter — lifted dark' },
            { value: 'champagne', label: 'Champagne — warm bronze' },
            { value: 'porcelain', label: 'Porcelain — light luxe' },
          ]}
          onChange={(v) => setTweak('theme', v)} />
        <TweakColor label="Accent" value={t.accent} onChange={(v) => setTweak('accent', v)} />

        <TweakSection label="Display Type"/>
        <TweakSelect label="Display font" value={t.displayFont}
          options={DISPLAY_FONTS.map(f => ({ value: f, label: f }))}
          onChange={(v) => setTweak('displayFont', v)} />
        <TweakSlider label="Display tracking" value={t.displayTracking} min={-6} max={2} step={0.5} unit="·10⁻²em"
          onChange={(v) => setTweak('displayTracking', v)} />
        <TweakSlider label="Display weight" value={t.displayWeight} min={300} max={700} step={100}
          onChange={(v) => setTweak('displayWeight', v)} />

        <TweakSection label="Body Type"/>
        <TweakSelect label="Body font" value={t.bodyFont}
          options={BODY_FONTS.map(f => ({ value: f, label: f }))}
          onChange={(v) => setTweak('bodyFont', v)} />
      </TweaksPanel>
    </div>
  );
}

function __mountAMG() {
  const el = document.getElementById('root');
  if (!el) { requestAnimationFrame(__mountAMG); return; }
  const root = ReactDOM.createRoot(el);
  root.render(<App/>);
}
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', __mountAMG);
} else {
  __mountAMG();
}
