// D2 v2 — main shell: nav, router, page transitions

// --- URL routing: page state <-> clean URL ---------------------------------
const D2V2_PAGE_TO_SLUG = {
  about: 'qui-je-suis',
  approach: 'mon-approche',
  services: 'mon-accompagnement',
  process: 'process',
  projects: 'projets',
  contact: 'contact',
  legal: 'mentions-legales',
};
const D2V2_SLUG_TO_PAGE = Object.keys(D2V2_PAGE_TO_SLUG).reduce((acc, k) => {
  acc[D2V2_PAGE_TO_SLUG[k]] = k;
  return acc;
}, {});

function d2v2PageToPath(page) {
  if (!page || page === 'home') return '/';
  if (page.startsWith('project:')) return '/projets/' + page.split(':')[1];
  return '/' + (D2V2_PAGE_TO_SLUG[page] || '');
}

function d2v2PathToPage(pathname) {
  let p = (pathname || '/').replace(/\/+$/, '');
  if (p === '' ) return 'home';
  const seg = p.replace(/^\//, '');
  if (!seg) return 'home';
  const proj = seg.match(/^projets\/(.+)$/);
  if (proj) return 'project:' + proj[1];
  return D2V2_SLUG_TO_PAGE[seg] || 'home';
}

// --- SEO : titre et description par page (lus par Google après rendu JS) ----
const D2V2_SITE_NAME = 'Mathilde Lazzari';
const D2V2_DEFAULT_DESC = "Mathilde Lazzari, architecte et architecte d'intérieur à Rulles (Habay), province de Luxembourg. Rénovation, transformation et extension de maisons, du gros œuvre à l'aménagement intérieur.";
const D2V2_PAGE_META = {
  home: ["Mathilde Lazzari · Architecte et architecte d'intérieur · Habay, Arlon, Gaume", D2V2_DEFAULT_DESC],
  about: ["Qui je suis · Mathilde Lazzari, architecte", "Le parcours de Mathilde Lazzari, architecte diplômée de l'Université de Liège, spécialisée dans la rénovation, la transformation et l'extension de bâtiments existants."],
  approach: ["Mon approche · Mathilde Lazzari, architecte", "Un seul regard, du gros œuvre à l'aménagement intérieur : la méthode de Mathilde Lazzari pour transformer votre maison."],
  services: ["Mon accompagnement · Mathilde Lazzari, architecte", "Missions d'architecture et d'architecture d'intérieur : esquisse, permis d'urbanisme, suivi de chantier, aménagement. Province de Luxembourg."],
  process: ["Process · Les étapes de votre projet · Mathilde Lazzari", "Du premier rendez-vous à la réception des travaux : les étapes d'un projet de rénovation ou d'extension avec Mathilde Lazzari."],
  projects: ["Projets · Rénovations et extensions · Mathilde Lazzari", "Extensions, transformations et aménagements réalisés par Mathilde Lazzari, architecte en province de Luxembourg."],
  legal: ["Mentions légales et vie privée · Mathilde Lazzari", "Mentions légales, protection des données et cookies du site de Mathilde Lazzari, architecte à Rulles (Habay)."],
  contact: ["Contact · Mathilde Lazzari, architecte à Rulles (Habay)", "Contactez Mathilde Lazzari, architecte et architecte d'intérieur à Rulles (Habay) : téléphone, e-mail et questionnaire de projet."],
};

function d2v2SetMeta(title, desc) {
  if (typeof document === 'undefined') return;
  document.title = title;
  let m = document.querySelector('meta[name="description"]');
  if (!m) { m = document.createElement('meta'); m.setAttribute('name', 'description'); document.head.appendChild(m); }
  m.setAttribute('content', desc || D2V2_DEFAULT_DESC);
  if (window.mlAnalytics) window.mlAnalytics.page();
}

function D2V2Shell() {
  const { sb, T, IMG } = useStoryblokStory('config');
  const [page, setPage] = React.useState(() =>
    typeof window !== 'undefined' ? d2v2PathToPage(window.location.pathname) : 'home'
  );
  const [cfgOpen, setCfgOpen] = React.useState(false);
  const [prevPage, setPrevPage] = React.useState(null);
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [isNarrow, setIsNarrow] = React.useState(() => typeof window !== 'undefined' && window.matchMedia('(max-width: 1100px)').matches);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 400);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Detect narrow viewport for burger menu (matchMedia — cheaper than ResizeObserver)
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 1100px)');
    const on = (e) => setIsNarrow(e.matches);
    mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);

  // Lock body scroll when mobile menu or configurator is open
  React.useEffect(() => {
    const locked = menuOpen || cfgOpen;
    document.body.classList.toggle('scroll-locked', locked);
    return () => document.body.classList.remove('scroll-locked');
  }, [menuOpen, cfgOpen]);

  // Titre / description par page (les pages projet posent les leurs dans D2V2Project)
  React.useEffect(() => {
    if (page.startsWith('project:')) return;
    const meta = D2V2_PAGE_META[page] || D2V2_PAGE_META.home;
    d2v2SetMeta(meta[0], meta[1]);
  }, [page]);

  // Browser back/forward — sync page from the URL without re-pushing history
  React.useEffect(() => {
    const onPop = () => {
      setMenuOpen(false);
      setPage(d2v2PathToPage(window.location.pathname));
      window.scrollTo({ top: 0, behavior: 'auto' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const go = (p) => {
    if (p === page) return;
    setPrevPage(page);
    setMenuOpen(false);
    // Arch transition
    const el = document.getElementById('d2v2-transition');
    if (el) {
      el.style.animation = 'none';
      void el.offsetHeight;
      el.style.animation = 'd2v2ArchSweep 1.1s cubic-bezier(.76,0,.24,1) forwards';
    }
    setTimeout(() => {
      setPage(p);
      const path = d2v2PageToPath(p);
      if (typeof window !== 'undefined' && window.location.pathname !== path) {
        window.history.pushState({ page: p }, '', path);
      }
      window.scrollTo({ top: 0, behavior: 'auto' });
    }, 500);
  };

  const isProject = page.startsWith('project:');
  const currentPage = isProject ? 'project' : page;

  const nav = [
    ['about', T('nav_label_about', 'Qui je suis')],
    ['approach', T('nav_label_approach', 'Mon approche')],
    ['services', T('nav_label_services', 'Mon accompagnement')],
    ['process', T('nav_label_process', 'Process')],
    ['projects', T('nav_label_projects', 'Projets')],
    ['contact', T('nav_label_contact', 'Contact')],
  ];

  return (
    <div style={{position:'relative', width:'100%', minHeight:'100dvh', background:'var(--cream)'}}>
      {/* NAV — top fixed. On mobile the nav is always fully opaque to stay readable.
          On desktop home it's transparent over the hero until the user scrolls past 400px. */}
      <nav data-shell-nav style={{
        position:'fixed', top:0, left:0, right:0, height:70, zIndex:30,
        display:'grid', gridTemplateColumns: isNarrow ? '1fr auto' : '260px 1fr auto', alignItems:'center',
        padding: isNarrow ? '0 20px' : '0 56px',
        borderBottom:'1px solid ' + ((!isNarrow && page === 'home' && !scrolled && !menuOpen) ? 'rgba(249,240,233,0.2)' : 'var(--line)'),
        background: isNarrow
          ? 'var(--cream)'
          : ((page === 'home' && !scrolled && !menuOpen) ? 'transparent' : 'rgba(249,240,233,0.94)'),
        backdropFilter: (!isNarrow && !(page === 'home' && !scrolled && !menuOpen)) ? 'blur(14px)' : 'none',
        WebkitBackdropFilter: (!isNarrow && !(page === 'home' && !scrolled && !menuOpen)) ? 'blur(14px)' : 'none',
        color: (!isNarrow && page === 'home' && !scrolled && !menuOpen) ? 'var(--cream)' : 'var(--ink)',
        boxShadow: isNarrow || scrolled ? '0 2px 16px rgba(26,21,18,0.08)' : 'none',
        transition: isNarrow ? 'none' : 'background .4s ease, color .4s ease, border-color .4s ease, box-shadow .4s ease',
        willChange: 'transform',
        transform: 'translateZ(0)'
      }}>
        <button onClick={() => go('home')} data-cursor="Accueil" style={{display:'flex', alignItems:'center', gap:14, color:'inherit', minWidth:0}}>
          <img src={IMG('logo', 'shared/logo.svg')} alt="" width={32} height={24} style={{display:'block', flexShrink:0, height:24, width:'auto'}}/>
          <div style={{textAlign:'left', minWidth:0}}>
            <div style={{fontFamily:'var(--font-sans)', fontWeight:600, fontSize: isNarrow ? 11 : 13, letterSpacing:'0.14em', whiteSpace:'nowrap'}}>{T('nav_brand_name', 'MATHILDE LAZZARI')}</div>
            <div className="nav-subtitle" style={{fontFamily:'var(--font-sans)', fontSize: isNarrow ? 8 : 9, letterSpacing:'0.22em', opacity:.7, marginTop:3, fontWeight:400, whiteSpace:'nowrap'}}>{T('nav_brand_tagline', 'ARCHITECTE TRANSFORMATION')}</div>
          </div>
        </button>

        {!isNarrow && (
          <div style={{display:'flex', gap:4, justifyContent:'center'}}>
            {nav.map(([p, l]) => (
              <button key={p} onClick={() => go(p)} data-cursor={l}
                style={{padding:'8px 14px', fontSize:13, color:'inherit', opacity: currentPage === p ? 1 : 0.6, position:'relative', transition:'opacity .2s', whiteSpace:'nowrap'}}>
                {l}
                {currentPage === p && <span style={{position:'absolute', bottom:-2, left:14, right:14, height:1, background:'var(--terracotta)'}}/>}
              </button>
            ))}
          </div>
        )}

        <div style={{display:'flex', alignItems:'center', gap:12}}>
          {!isNarrow && (
            <button onClick={() => setCfgOpen(true)} data-cursor="Commencer" style={{padding:'10px 20px', background:'var(--terracotta)', color:'var(--cream)', borderRadius:999, fontSize:12, letterSpacing:'0.03em', display:'flex', alignItems:'center', gap:8, whiteSpace:'nowrap'}}>
              Votre projet <span>→</span>
            </button>
          )}
          {isNarrow && (
            <div style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.12em', color:'inherit', opacity:.7, textTransform:'uppercase'}}>{T('nav_role', 'Architecte')}</div>
          )}
        </div>
      </nav>

      {/* MOBILE MENU OVERLAY — only mounted when narrow */}
      {isNarrow && menuOpen && (
        <div role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()} style={{
          position:'fixed', top:70, left:0, right:0, bottom:0, zIndex:28,
          background:'var(--cream)', color:'var(--ink)',
          padding:'40px 24px 110px',
          display:'flex', flexDirection:'column', overflow:'auto', WebkitOverflowScrolling:'touch',
          animation: 'menuSlideDown .4s cubic-bezier(.76,0,.24,1)'
        }}>
          <div style={{display:'flex', flexDirection:'column', gap:4}}>
            {nav.map(([p, l], i) => (
              <button key={p} onClick={() => go(p)}
                style={{textAlign:'left', padding:'18px 0', fontSize:'clamp(24px, 6.5vw, 32px)', fontFamily:'var(--font-sans)', fontWeight:500, letterSpacing:'-0.02em',
                  color: currentPage === p ? 'var(--terracotta)' : 'var(--ink)',
                  borderBottom:'1px solid var(--line)',
                  animation: `menuItemIn .5s cubic-bezier(.2,.7,.2,1) ${80 + i*40}ms both`}}>
                <span style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--stone)', letterSpacing:'0.15em', marginRight:18}}>0{i+1}</span>
                {l}
              </button>
            ))}
          </div>
          <button onClick={() => { setMenuOpen(false); setCfgOpen(true); }}
            style={{marginTop:32, padding:'18px 28px', background:'var(--terracotta)', color:'var(--cream)', borderRadius:999, fontSize:14, letterSpacing:'0.04em', display:'flex', alignItems:'center', justifyContent:'center', gap:12,
              animation: 'menuItemIn .5s cubic-bezier(.2,.7,.2,1) 500ms both'}}>
            Lancer le questionnaire <span>→</span>
          </button>
          <div style={{marginTop:'auto', paddingTop:40, fontFamily:'var(--font-mono)', fontSize:10, color:'var(--stone)', letterSpacing:'0.12em',
              animation: 'menuItemIn .5s cubic-bezier(.2,.7,.2,1) 600ms both'}}>
            {T('nav_contact_email', 'BONJOUR@MATHILDELAZZARI.BE')}<br/>
            {T('nav_contact_phone', '+32 2 412 98 30')}
          </div>
        </div>
      )}

      {/* MOBILE BOTTOM BAR — thumb-reachable nav + CTA */}
      {isNarrow && (
        <div style={{position:'fixed', left:0, right:0, bottom:0, zIndex:35, display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--line)', boxShadow:'0 -2px 18px rgba(26,21,18,0.12)'}}>
          <button onClick={() => setMenuOpen(m => !m)} aria-label={menuOpen ? 'Fermer le menu' : 'Ouvrir le menu'} aria-expanded={menuOpen}
            style={{padding:'18px 16px', background:'var(--cream)', color:'var(--ink)', display:'flex', alignItems:'center', justifyContent:'center', gap:12, fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'0.1em', textTransform:'uppercase'}}>
            <span style={{display:'flex', flexDirection:'column', justifyContent:'center', gap:4, width:18}}>
              <span style={{height:1.5, background:'currentColor', transition:'transform .3s', transform: menuOpen ? 'translateY(2.75px) rotate(45deg)' : 'none'}}/>
              <span style={{height:1.5, background:'currentColor', transition:'opacity .2s', opacity: menuOpen ? 0 : 1}}/>
              <span style={{height:1.5, background:'currentColor', transition:'transform .3s', transform: menuOpen ? 'translateY(-2.75px) rotate(-45deg)' : 'none'}}/>
            </span>
            {menuOpen ? 'Fermer' : 'Menu'}
          </button>
          <button onClick={() => setCfgOpen(true)} data-cursor="Commencer"
            style={{padding:'18px 16px', background:'var(--terracotta)', color:'var(--cream)', display:'flex', alignItems:'center', justifyContent:'center', gap:10, fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'0.1em', textTransform:'uppercase'}}>
            Questionnaire <span>→</span>
          </button>
        </div>
      )}

      {/* PAGE CONTENT — on desktop home the hero slides under the transparent nav; on mobile the nav is opaque so we offset */}
      <div style={{paddingTop: (page === 'home' && !isNarrow) ? 0 : 70, paddingBottom: isNarrow ? 60 : 0}}>
        {page === 'home' && <D2V2Home go={go} openCfg={() => setCfgOpen(true)}/>}
        {page === 'projects' && <D2V2Projects go={go}/>}
        {isProject && <D2V2Project id={page.split(':')[1]} go={go}/>}
        {page === 'approach' && <D2V2Approach go={go}/>}
        {page === 'services' && <D2V2Services openCfg={() => setCfgOpen(true)}/>}
        {page === 'process' && <D2V2Process/>}
        {page === 'about' && <D2V2About/>}
        {page === 'contact' && <D2V2Contact openCfg={() => setCfgOpen(true)}/>}
        {page === 'legal' && <D2V2Legal/>}

        {/* Footer — present on every page */}
          <footer {...sbEditableAttr(sb)} style={{background:'var(--cream-deep)', color:'var(--ink)', padding:'72px 56px 28px', borderTop:'3px solid var(--terracotta)'}}>
            <div style={{display:'grid', gridTemplateColumns:'2fr 1fr 1fr 1fr', gap:48, paddingBottom:48, borderBottom:'1px solid var(--line)'}}>
              <div>
                <img src={IMG('logo', 'shared/logo.svg')} alt="Mathilde Lazzari" width={60} height={45} style={{display:'block', height:45, width:'auto'}}/>
                <div style={{fontFamily:'var(--font-display)', fontSize:'clamp(28px, 4vw, 36px)', fontWeight:300, marginTop:24, maxWidth:400, lineHeight:1.2, letterSpacing:'-0.015em'}}>
                  {T('footer_cta_title', 'Un projet à')} <em style={{fontStyle:'italic', color:'var(--terracotta)'}}>{T('footer_cta_emphasis', 'transformer')}</em> {T('footer_cta_suffix', '?')}
                </div>
                <button onClick={() => setCfgOpen(true)} data-cursor="Commencer" style={{marginTop:24, padding:'14px 24px', background:'var(--ink)', color:'var(--cream)', borderRadius:999, fontSize:13}}>{T('footer_cta_button', 'Lancer le questionnaire →')}</button>
              </div>
              {(() => {
                const email = T('footer_contact_email', 'bonjour@mathildelazzari.be');
                const phone = T('footer_contact_phone', '+32 2 412 98 30');
                const socials = [
                  [T('footer_social_1', 'Instagram'), T('footer_social_1_url', '')],
                  [T('footer_social_2', 'LinkedIn'), T('footer_social_2_url', '')],
                  [T('footer_social_3', ''), T('footer_social_3_url', '')],
                  [T('footer_social_4', ''), T('footer_social_4_url', '')],
                ].filter(([label]) => label);
                return [
                  [T('footer_nav_label', 'Navigation'), nav.map(([k,l]) => ({ label: l, href: null }))],
                  [T('footer_contact_label', 'Contact'), [
                    { label: email, href: 'mailto:' + email },
                    { label: phone, href: 'tel:' + phone.replace(/[^+\d]/g, '') },
                    { label: T('footer_contact_address1', 'Rue du Village 12'), href: null },
                    { label: T('footer_contact_address2', '6743 Rulles'), href: null },
                  ]],
                  [T('footer_social_label', 'Suivre'), socials.map(([label, url]) => ({ label, href: url || null }))],
                ];
              })().map(([t, items], ci) => (
                <div key={ci}>
                  <div style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.15em', color:'var(--terracotta)', marginBottom:20, textTransform:'uppercase'}}>{t}</div>
                  <div style={{display:'flex', flexDirection:'column', gap:10}}>
                    {items.map((it, ii) => it.href
                      ? <a key={ii} href={it.href} target={it.href.startsWith('http') ? '_blank' : undefined} rel="noopener" data-cursor="Ouvrir" style={{fontSize:13, color:'var(--ink-soft)'}}>{it.label}</a>
                      : <span key={ii} style={{fontSize:13, color:'var(--ink-soft)'}}>{it.label}</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
            <div style={{display:'flex', justifyContent:'space-between', paddingTop:24, fontFamily:'var(--font-mono)', fontSize:10, color:'var(--stone)', letterSpacing:'0.1em', flexWrap:'wrap', gap:12}}>
              <span>{T('footer_copyright_1', '© 2026 · MATHILDE LAZZARI · ARCHITECTE D.PLG')}</span>
              <span>{T('footer_copyright_2', 'RULLES — BELGIQUE')}</span>
              <a href="/mentions-legales" onClick={(e) => { e.preventDefault(); go('legal'); }} style={{color:'inherit'}}>{T('footer_copyright_3', 'MENTIONS LÉGALES · PRIVACY')}</a>
              <button type="button" onClick={() => window.mlAnalytics && window.mlAnalytics.openConsent()} style={{font:'inherit', letterSpacing:'inherit', color:'inherit', background:'none', border:0, padding:0, cursor:'pointer', textTransform:'uppercase'}}>Cookies</button>
            </div>
          </footer>
      </div>

      {/* ARCH TRANSITION overlay */}
      <div id="d2v2-transition" style={{position:'fixed', inset:0, pointerEvents:'none', zIndex:50, background:'var(--terracotta)', transform:'translateY(100%)'}}/>

      {/* CURSOR */}
      <CustomCursor/>

      {/* CONFIGURATOR */}
      {cfgOpen && <Configurator onClose={() => setCfgOpen(false)}/>}

      <style>{`
        @keyframes d2v2ArchSweep {
          0% { transform: translateY(100%); border-radius: 50% 50% 0 0 / 30% 30% 0 0; }
          50% { transform: translateY(0); border-radius: 0; }
          100% { transform: translateY(-100%); border-radius: 0 0 50% 50% / 0 0 30% 30%; }
        }
        @keyframes menuSlideDown {
          from { transform: translateY(-20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
        @keyframes menuItemIn {
          from { transform: translateY(16px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

window.D2V2Shell = D2V2Shell;
