// Theme & shared building blocks for the Vue360 site (V4 direction)
// Couleurs marque (tirées du logo): #0049e7 (bleu), #48d2b1 (aqua), #8d82f4 (mauve), #e19ffb (rose), + jaune #ffb84d

const v4Theme = {
  bg: '#fdf8f0',
  bg2: '#f5ede0',
  surface: '#ffffff',
  ink: '#0a1840',
  inkSoft: '#3a4868',
  muted: '#6b7794',
  blue: '#0049e7',
  teal: '#48d2b1',
  purple: '#8d82f4',
  pink: '#e19ffb',
  warm: '#ffb84d',
  border: 'rgba(10,24,64,0.1)',
  fontDisplay: '"Bricolage Grotesque", "Inter", system-ui, sans-serif',
  fontBody: '"Inter", system-ui, sans-serif',
};

// ── Adaptation mobile et tablette ─────────────────────────────────────────
// Les pages sont stylées en ligne pour le bureau; ces règles les réajustent
// sur petits écrans (les !important l'emportent sur les styles en ligne).
if (typeof document !== 'undefined' && !document.getElementById('v4-responsive')) {
  const css = document.createElement('style');
  css.id = 'v4-responsive';
  css.textContent = `
    html,body{overflow-x:hidden}
    #root img,#root svg,#root video{max-width:100%}
    .v4-burger,.v4-mnav{display:none}
    @media (max-width:1100px){
      .v4-nav{gap:18px!important;font-size:13px!important}
      #root [style*="grid-template-columns: repeat(3"],#root [style*="grid-template-columns: repeat(4"],
      #root [style*="grid-template-columns: 2fr 1fr 1fr 1fr"],#root [style*="grid-template-columns: 1fr 1fr 1fr"]{
        grid-template-columns:repeat(2,minmax(0,1fr))!important}
    }
    @media (max-width:900px){
      .v4-nav,.v4-cta{display:none!important}
      .v4-burger{display:inline-flex}
      .v4-mnav.open{display:flex}
      #root section[style*="56px"],#root footer[style*="56px"],#root header [style*="56px"],
      #root nav[style*="56px"],#root div[style*="padding: 0px 56px"],
      #root div[style*="max-width: 1440px"][style*="56px"]{padding-left:20px!important;padding-right:20px!important}
      #root section[style*="padding: 120px"],#root section[style*="padding: 140px"]{padding-top:64px!important;padding-bottom:64px!important}
      #root section[style*="padding: 80px"],#root footer[style*="padding: 80px"]{padding-top:48px!important}
      #root [style*="grid-template-columns"]:not([style*="8px 1fr"]):not([style*="44px 1fr"]){
        grid-template-columns:minmax(0,1fr)!important;gap:20px!important}
      #root [style*="position: sticky"]:not(header){position:static!important}
      #root [style*="display: flex"]:not([style*="flex-direction: column"]):not(header *):not(button){flex-wrap:wrap}
      #root h1{font-size:clamp(34px,10vw,52px)!important;letter-spacing:-1px!important;line-height:1.08!important}
      #root h1 *,#root h2 *{white-space:normal!important}
      #root h2{font-size:clamp(28px,8vw,40px)!important;letter-spacing:-0.8px!important;line-height:1.12!important}
      #root h3{font-size:clamp(20px,5.5vw,26px)!important}
      #root [style*="font-size: 64px"],#root [style*="font-size: 72px"],#root [style*="font-size: 80px"],
      #root [style*="font-size: 88px"],#root [style*="font-size: 96px"],#root [style*="font-size: 104px"],
      #root [style*="font-size: 128px"]{font-size:clamp(36px,11vw,52px)!important;letter-spacing:-1px!important}
      #root p[style*="font-size: 20px"],#root p[style*="font-size: 19px"]{font-size:17px!important}
      #root div[style*="padding: 56px 64px"],#root div[style*="padding: 48px;"],#root div[style*="padding: 40px 48px"],
      #root div[style*="padding: 52px 56px"],#root div[style*="padding: 36px;"],#root div[style*="padding: 40px;"],
      #root div[style*="padding: 32px;"]{padding:24px!important}
      #root [style*="max-width: 1440px"]{max-width:100%!important}
      .v4-hide-mobile{display:none!important}
      .v4-ski-layer{left:50%!important;right:auto!important;width:1533px!important;max-width:none!important;transform:translateX(-48%)}
      .v4-ski-lead{background:rgba(10,24,64,0.6);padding:16px 18px;border-radius:16px;backdrop-filter:blur(6px)}
    }
  `;
  document.head.appendChild(css);
  if (!document.querySelector('meta[name="viewport"]')) {
    const m = document.createElement('meta');
    m.name = 'viewport'; m.content = 'width=device-width,initial-scale=1';
    document.head.appendChild(m);
  }
}

// Préfixe de chemin pour les pages en sous-dossier (ex. tour-virtuel-360/hotels/).
// Une page en sous-dossier définit window.V4_BASE = '../../' avant de charger ce fichier.
const v4Base = () => (typeof window !== 'undefined' && window.V4_BASE) || '';
const v4Href = (h) => (/^(https?:|mailto:|tel:|#)/.test(h) ? h : v4Base() + h);

const V4LogoMark = ({size = 38} = {}) => (
  <a href={v4Href('index.html')} style={{display:'flex',alignItems:'center',gap:1,textDecoration:'none'}}>
    <img src={v4Href('assets/logo-vue360.png')} alt="Vue360"
      style={{height:size,width:size,objectFit:'contain',display:'block',
        marginRight:-Math.round(size*0.04)}}/>
    <span style={{fontFamily:v4Theme.fontDisplay,fontWeight:700,fontSize:Math.round(size*0.55),
      letterSpacing:-0.8,color:v4Theme.ink,lineHeight:1}}>
      ue360
    </span>
  </a>
);

const V4Nav = ({active}) => {
  const [open, setOpen] = React.useState(false);
  const items = [
    ['tour-virtuel-360/index.html','Tours virtuels 360°','tours'],
    ['services-fiche-google.html','Visibilité locale','fiche'],
    ['services-site-web.html','Sites web','site'],
    ['services-avis.html','Système d\'avis','avis'],
    ['ressources.html','Ressources','ressources'],
  ];
  const link = (href,label,key) => (
    <a href={v4Href(href)} style={{
      color: active===key ? v4Theme.ink : v4Theme.inkSoft,
      fontWeight: active===key ? 600 : 500,
      textDecoration:'none',
      borderBottom: active===key ? `2px solid ${v4Theme.teal}` : '2px solid transparent',
      paddingBottom:4,
    }}>{label}</a>
  );
  return (
    <header style={{
      position:'sticky',top:0,zIndex:50,
      background:'rgba(253,248,240,0.9)',backdropFilter:'blur(20px)',
      borderBottom:`1px solid ${v4Theme.border}`,
    }}>
    <div style={{maxWidth:1440,margin:'0 auto',padding:'20px 56px',
      display:'flex',alignItems:'center',justifyContent:'space-between'}}>
      <V4LogoMark/>
      <nav className="v4-nav" aria-label="Navigation principale" style={{display:'flex',gap:32,fontFamily:v4Theme.fontBody,fontSize:14}}>
        {items.map(([h,l,k])=>(<React.Fragment key={k}>{link(h,l,k)}</React.Fragment>))}
      </nav>
      <button type="button" className="v4-burger" aria-expanded={open} aria-controls="v4-mnav"
        aria-label={open ? 'Fermer le menu' : 'Ouvrir le menu'} onClick={()=>setOpen(!open)}
        style={{alignItems:'center',justifyContent:'center',width:44,height:44,borderRadius:12,
          border:`1px solid ${v4Theme.border}`,background:v4Theme.surface,cursor:'pointer',padding:0}}>
        <svg aria-hidden="true" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={v4Theme.ink}
          strokeWidth="2" strokeLinecap="round">
          {open ? <path d="M6 6l12 12M18 6L6 18"/> : <path d="M4 7h16M4 12h16M4 17h16"/>}
        </svg>
      </button>
      <a className="v4-cta" href={v4Href('contact.html')} style={{
        background:v4Theme.ink,color:v4Theme.bg,border:'none',borderRadius:999,
        padding:'12px 22px',fontFamily:v4Theme.fontBody,fontWeight:600,fontSize:14,cursor:'pointer',
        textDecoration:'none',display:'inline-flex',alignItems:'center',gap:8,
      }}>
        Demande de services <span>→</span>
      </a>
    </div>
    <nav id="v4-mnav" className={`v4-mnav${open ? ' open' : ''}`} aria-label="Menu mobile"
      style={{flexDirection:'column',padding:'8px 20px 20px',gap:4,borderTop:`1px solid ${v4Theme.border}`,
        background:v4Theme.bg}}>
      {items.map(([h,l,k])=>(
        <a key={k} href={v4Href(h)} style={{display:'block',padding:'14px 4px',fontFamily:v4Theme.fontBody,
          fontSize:17,fontWeight: active===k ? 700 : 500,color:v4Theme.ink,textDecoration:'none',
          borderBottom:`1px solid ${v4Theme.border}`}}>{l}</a>
      ))}
      <a href={v4Href('contact.html')} style={{marginTop:14,textAlign:'center',background:v4Theme.ink,
        color:v4Theme.bg,borderRadius:999,padding:'16px',fontFamily:v4Theme.fontBody,fontWeight:700,
        fontSize:16,textDecoration:'none'}}>Demande de services →</a>
    </nav>
    </header>
  );
};

const V4Footer = () => (
  <footer style={{padding:'80px 56px 40px',background:v4Theme.bg2,borderTop:`1px solid ${v4Theme.border}`}}>
    <div style={{maxWidth:1440,margin:'0 auto'}}>
      <div style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr',gap:48,marginBottom:48}}>
        <div>
          <V4LogoMark/>
          <p style={{fontFamily:v4Theme.fontBody,fontSize:15,color:v4Theme.inkSoft,
            marginTop:24,maxWidth:320,lineHeight:1.6}}>
            Tours virtuels 360°, visibilité sur les cartes et dans les recherches locales, et avis pour les commerces et lieux touristiques des Laurentides. On rend votre commerce visible là où les gens cherchent vraiment.
          </p>
        </div>
        {[
          {h:'Services',l:[['Tours virtuels 360°','tour-virtuel-360/index.html'],['Montagnes et ski','tour-virtuel-360/montagne-ski/index.html'],['Visibilité locale','services-fiche-google.html'],['Conception de site web','services-site-web.html'],['Système d\'avis','services-avis.html']]},
          {h:'En savoir plus',l:[['Pourquoi la fiche Google','pourquoi-fiche-google-ia.html'],['À propos','a-propos.html'],['Contact','contact.html']]},
          {h:'Contact',l:[['info@vue360.ca','mailto:info@vue360.ca'],['Laurentides seulement','#'],['Ski : partout au Québec','tour-virtuel-360/montagne-ski/index.html']]},
        ].map((c,i)=>(
          <div key={i}>
            <div style={{fontFamily:v4Theme.fontBody,fontSize:12,letterSpacing:1.5,
              color:v4Theme.muted,textTransform:'uppercase',marginBottom:16,fontWeight:600}}>{c.h}</div>
            {c.l.map(([t,h])=>(
              <a key={t} href={v4Href(h)} style={{display:'block',fontFamily:v4Theme.fontBody,fontSize:14,
                color:v4Theme.ink,marginBottom:10,textDecoration:'none'}}>{t}</a>
            ))}
          </div>
        ))}
      </div>
      <div style={{paddingTop:24,borderTop:`1px solid ${v4Theme.border}`,
        display:'flex',justifyContent:'space-between',
        fontFamily:v4Theme.fontBody,fontSize:12,color:v4Theme.muted,letterSpacing:0.5}}>
        <span>© 2026 VUE 360 · Spécialiste Google Local · <a href={v4Href('politique-confidentialite.html')} style={{color:v4Theme.muted}}>Confidentialité</a> · <a href={v4Href('conditions-utilisation.html')} style={{color:v4Theme.muted}}>Conditions</a></span>
        <span>Laurentides · 100 % québécois</span>
      </div>
    </div>
  </footer>
);

// Petit hero réutilisable pour pages internes
const V4PageHero = ({eyebrow, title, gradient, subtitle, accent = v4Theme.teal}) => (
  <section style={{padding:'80px 56px 60px',background:v4Theme.bg,position:'relative',overflow:'hidden'}}>
    <div style={{position:'absolute',top:-150,right:-100,width:500,height:500,borderRadius:'50%',
      background:`radial-gradient(circle, ${accent}30, transparent 65%)`,filter:'blur(40px)'}}/>
    <div style={{position:'absolute',top:100,left:-100,width:400,height:400,borderRadius:'50%',
      background:`radial-gradient(circle, ${v4Theme.warm}40, transparent 65%)`,filter:'blur(40px)'}}/>
    <div style={{maxWidth:1440,margin:'0 auto',position:'relative'}}>
      <div style={{display:'inline-flex',alignItems:'center',gap:8,
        padding:'8px 14px',borderRadius:999,
        background:'rgba(255,255,255,0.7)',border:`1px solid ${accent}40`,backdropFilter:'blur(10px)',
        fontFamily:v4Theme.fontBody,fontSize:13,color:v4Theme.ink,fontWeight:500,marginBottom:32}}>
        <span style={{width:6,height:6,borderRadius:'50%',background:accent,
          boxShadow:`0 0 0 4px ${accent}30`}}/>
        {eyebrow}
      </div>
      <h1 style={{fontFamily:v4Theme.fontDisplay,fontWeight:700,fontSize:88,lineHeight:1.05,
        letterSpacing:-3,color:v4Theme.ink,margin:0,maxWidth:980,textWrap:'balance'}}>
        {title}{' '}
        {gradient && (
          <span style={{
            background:`linear-gradient(135deg, ${v4Theme.blue} 0%, ${v4Theme.purple} 55%, ${v4Theme.pink} 100%)`,
            WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
            fontStyle:'italic',fontWeight:600,display:'inline-block',paddingRight:'0.08em',
          }}>{gradient}</span>
        )}
      </h1>
      {subtitle && (
        <p style={{fontFamily:v4Theme.fontBody,fontSize:20,lineHeight:1.6,color:v4Theme.inkSoft,
          maxWidth:680,marginTop:24,textWrap:'pretty'}}>{subtitle}</p>
      )}
    </div>
  </section>
);

const V4Button = ({children, primary, href = '#', style={}}) => (
  <a href={v4Href(href)} style={{
    display:'inline-flex',alignItems:'center',gap:8,
    background: primary ? v4Theme.ink : 'rgba(255,255,255,0.7)',
    color: primary ? v4Theme.bg : v4Theme.ink,
    border: primary ? 'none' : `1px solid ${v4Theme.border}`,
    borderRadius:999,
    padding:'16px 26px',fontFamily:v4Theme.fontBody,fontWeight:600,fontSize:15,cursor:'pointer',
    textDecoration:'none',
    backdropFilter:'blur(10px)',
    ...style
  }}>{children}</a>
);

// Section CTA finale réutilisable
const V4FinalCTA = ({title, gradientPart, body}) => (
  <section style={{padding:'120px 56px',position:'relative',overflow:'hidden',
    background:`linear-gradient(135deg, ${v4Theme.blue} 0%, ${v4Theme.purple} 60%, ${v4Theme.teal} 100%)`}}>
    <div style={{position:'absolute',top:-150,right:'15%',width:400,height:400,borderRadius:'50%',
      background:`radial-gradient(circle, ${v4Theme.warm}80, transparent 65%)`,filter:'blur(20px)'}}/>
    <div style={{maxWidth:1440,margin:'0 auto',textAlign:'center',position:'relative'}}>
      <div style={{display:'inline-flex',alignItems:'center',gap:8,
        padding:'10px 18px',borderRadius:999,
        background:'rgba(255,255,255,0.15)',border:'1px solid rgba(255,255,255,0.3)',backdropFilter:'blur(10px)',
        fontFamily:v4Theme.fontBody,fontSize:13,color:'#fff',fontWeight:600,marginBottom:32}}>
        ✓ Appel gratuit · Sans engagement
      </div>
      <h2 style={{fontFamily:v4Theme.fontDisplay,fontSize:88,fontWeight:700,letterSpacing:-3,
        color:'#fff',margin:0,lineHeight:1.05,marginBottom:32,textWrap:'balance'}}>
        {title}{' '}
        {gradientPart && <em style={{fontWeight:600,color:v4Theme.warm,fontStyle:'italic'}}>{gradientPart}</em>}
      </h2>
      <p style={{fontFamily:v4Theme.fontBody,fontSize:19,color:'rgba(255,255,255,0.85)',maxWidth:560,
        margin:'0 auto 40px',lineHeight:1.5}}>
        {body || "15 minutes au téléphone. On regarde votre fiche Google, on identifie ce qui manque, on vous donne un plan. Gratuit, sans engagement."}
      </p>
      <a href={v4Href('contact.html')} style={{display:'inline-flex',alignItems:'center',gap:10,
        background:'#fff',color:v4Theme.ink,border:'none',borderRadius:999,
        padding:'20px 36px',fontFamily:v4Theme.fontBody,fontWeight:700,fontSize:17,cursor:'pointer',
        textDecoration:'none'}}>
        Réserver mon appel découverte →
      </a>
    </div>
  </section>
);

// "À partir de" : affichage de prix consistant
const V4PriceBadge = ({price, note = 'tout inclus', accent = v4Theme.blue}) => (
  <div style={{display:'inline-flex',alignItems:'baseline',gap:14,
    padding:'20px 28px',background:v4Theme.surface,borderRadius:24,
    border:`1px solid ${v4Theme.border}`,boxShadow:'0 4px 20px rgba(10,24,64,0.05)'}}>
    <div>
      <div style={{fontFamily:v4Theme.fontBody,fontSize:11,color:v4Theme.muted,
        letterSpacing:1.5,textTransform:'uppercase',fontWeight:600}}>À partir de</div>
      <div style={{display:'flex',alignItems:'baseline',gap:6,marginTop:4}}>
        <div style={{fontFamily:v4Theme.fontDisplay,fontSize:56,fontWeight:700,
          letterSpacing:-1.5,color:accent,lineHeight:1}}>
          {price}<span style={{fontSize:24,color:v4Theme.muted,fontWeight:500}}>$</span>
        </div>
        <div style={{fontFamily:v4Theme.fontBody,fontSize:13,color:v4Theme.muted}}>{note}</div>
      </div>
    </div>
  </div>
);


// Champ « Nom du commerce » avec suggestions Google (Places Autocomplete via /api/places-autocomplete).
// Ajoute au formulaire les champs cachés place_id, adresse et session_token.
const v4NewSession = () => (window.crypto && crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + Math.random().toString(36).slice(2));
const V4PlaceInput = ({label='Nom du commerce', name='commerce', required, placeholder, span, onPick}) => {
  const [val, setVal] = React.useState('');
  const [items, setItems] = React.useState([]);
  const [open, setOpen] = React.useState(false);
  const [active, setActive] = React.useState(-1);
  const [picked, setPicked] = React.useState(null);
  const tok = React.useRef(v4NewSession());
  const timer = React.useRef(null);

  const search = (q) => {
    clearTimeout(timer.current);
    if (q.trim().length < 3) { setItems([]); setOpen(false); return; }
    timer.current = setTimeout(async () => {
      try {
        const r = await fetch(v4Href('api/places-autocomplete'), {method:'POST',
          headers:{'Content-Type':'application/json'}, body:JSON.stringify({input:q, sessionToken:tok.current})});
        const j = await r.json();
        setItems(j.suggestions || []); setOpen((j.suggestions || []).length > 0); setActive(-1);
      } catch (_) { setItems([]); setOpen(false); }
    }, 250);
  };
  const choose = (it) => {
    setVal(it.main); setPicked(it); setOpen(false); setItems([]);
    if (onPick) onPick(it);
  };
  const onKey = (e) => {
    if (!open) return;
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, items.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
    else if (e.key === 'Enter' && active >= 0) { e.preventDefault(); choose(items[active]); }
    else if (e.key === 'Escape') setOpen(false);
  };
  return (
    <label style={{display:'block', position:'relative', gridColumn: span ? '1 / -1' : undefined}}>
      <div style={{fontFamily:v4Theme.fontBody, fontSize:12.5, fontWeight:600, color:v4Theme.ink, marginBottom:7, letterSpacing:0.2}}>
        {label}{required && <span style={{color:v4Theme.purple, marginLeft:3}}>*</span>}
      </div>
      <input name={name} required={required} placeholder={placeholder} value={val} autoComplete="off"
        role="combobox" aria-expanded={open} aria-autocomplete="list"
        onChange={e => { setVal(e.target.value); setPicked(null); search(e.target.value); }}
        onKeyDown={onKey} onBlur={() => setTimeout(() => setOpen(false), 150)}
        onFocus={() => items.length && setOpen(true)}
        style={{width:'100%', padding:'13px 15px', borderRadius:11, border:`1.5px solid ${picked ? v4Theme.teal : v4Theme.border}`,
          background:v4Theme.bg, fontFamily:v4Theme.fontBody, fontSize:14.5, color:v4Theme.ink, boxSizing:'border-box', outline:'none'}}/>
      <input type="hidden" name="place_id" value={picked ? picked.placeId : ''}/>
      <input type="hidden" name="adresse" value={picked ? picked.secondary : ''}/>
      <input type="hidden" name="session_token" value={tok.current}/>
      {picked && <div style={{fontFamily:v4Theme.fontBody, fontSize:12, color:v4Theme.muted, marginTop:6}}>✓ {picked.secondary}</div>}
      {open && (
        <div role="listbox" style={{position:'absolute', zIndex:30, left:0, right:0, top:'100%', marginTop:4,
          background:v4Theme.surface, border:`1px solid ${v4Theme.border}`, borderRadius:12,
          boxShadow:'0 12px 32px rgba(10,24,64,0.14)', overflow:'hidden'}}>
          {items.map((it, i) => (
            <div key={it.placeId} role="option" aria-selected={i === active}
              onMouseDown={e => { e.preventDefault(); choose(it); }} onMouseEnter={() => setActive(i)}
              style={{padding:'11px 14px', cursor:'pointer', background: i === active ? v4Theme.bg2 : 'transparent',
                borderBottom: i < items.length - 1 ? `1px solid ${v4Theme.border}` : 'none'}}>
              <div style={{fontFamily:v4Theme.fontBody, fontSize:14, fontWeight:600, color:v4Theme.ink}}>{it.main}</div>
              {it.secondary && <div style={{fontFamily:v4Theme.fontBody, fontSize:12.5, color:v4Theme.muted}}>{it.secondary}</div>}
            </div>
          ))}
          <div style={{padding:'6px 14px', fontFamily:v4Theme.fontBody, fontSize:10.5, color:v4Theme.muted, textAlign:'right'}}>Suggestions Google</div>
        </div>
      )}
    </label>
  );
};
window.V4PlaceInput = V4PlaceInput;

window.v4Theme = v4Theme;
window.v4Href = v4Href;
window.V4LogoMark = V4LogoMark;
window.V4Nav = V4Nav;
window.V4Footer = V4Footer;
window.V4PageHero = V4PageHero;
window.V4Button = V4Button;
window.V4FinalCTA = V4FinalCTA;
window.V4PriceBadge = V4PriceBadge;
