/* global React */
// EXO7 ENERGY — Shared components (Header, Footer, Shell, Hero, hooks)

const EXO = {
  bg: '#faf8f3',
  bgAlt: '#f1eee5',
  ink: '#0B0B0B',
  inkMute: '#5a5854',
  cobalt: '#0047AB',
  cobaltDeep: '#00337a',
  steel: '#2f6fb0',
  line: '#d8d4ca',
  rose: '#F3D9DF',
};
window.EXO7_COLORS = EXO;

const LOGO = 'assets/logo-exo7.png';

// Hook: re-render on language change
function useLang() {
  const [lang, setLang] = React.useState(window.EXO7_LANG || 'FR');
  React.useEffect(() => {
    const handler = (e) => setLang(e.detail);
    window.addEventListener('exo7-lang-change', handler);
    return () => window.removeEventListener('exo7-lang-change', handler);
  }, []);
  const t = window.EXO7_I18N[lang];
  const tt = (map) => (map[lang] != null ? map[lang] : map.FR);
  return { lang, t, tt, setLang: (l) => window.EXO7_SET_LANG(l) };
}
window.useLang = useLang;

// Hook: viewport width
function useViewport() {
  const [w, setW] = React.useState(typeof window !== 'undefined' ? window.innerWidth : 1440);
  React.useEffect(() => {
    const onResize = () => setW(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return { w, isMobile: w < 900, isTablet: w >= 900 && w < 1200 };
}
window.useViewport = useViewport;

// ---- Site Header ----
function SiteHeader({ active }) {
  const { lang, t, tt, setLang } = useLang();
  const { isMobile } = useViewport();
  const [open, setOpen] = React.useState(false);
  const links = [
    { id: 'home', href: 'index.html', label: t.nav.home },
    { id: 'expertise', href: 'expertises.html', label: t.nav.expertise },
    { id: 'works', href: 'realisations.html', label: t.nav.works },
    { id: 'about', href: 'groupe.html', label: t.nav.about },
    { id: 'contact', href: 'contact.html', label: t.nav.contact },
  ];
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      backdropFilter: 'blur(12px)',
      background: 'rgba(250,248,243,0.97)',
      borderBottom: `3px solid ${EXO.cobalt}`,
    }}>
      <div style={{ background: EXO.cobalt, color: '#fff' }}>
        <div style={{
          maxWidth: 1440, margin: '0 auto',
          padding: isMobile ? '6px 20px' : '7px 48px',
          display: 'flex', alignItems: 'center',
          flexDirection: isMobile ? 'column' : 'row',
          justifyContent: 'space-between', gap: isMobile ? 3 : 16,
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: isMobile ? 10 : 12.5, letterSpacing: isMobile ? '0.12em' : '0.16em',
          textTransform: 'uppercase', fontWeight: 600, textAlign: 'center',
        }}>
          <span>{tt({ FR: 'HTA / BT — SOUS-TRAITANT HAUTE TENSION', EN: 'MV / LV — HIGH-VOLTAGE SUBCONTRACTOR' })}</span>
          <span style={{ whiteSpace: 'nowrap' }}>C13-100 · C13-200 · C15-100 · C15-400</span>
        </div>
      </div>
      <div style={{
        maxWidth: 1440, margin: '0 auto',
        padding: isMobile ? '8px 20px' : '10px 48px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: isMobile ? 16 : 48,
      }}>
        <a href="index.html" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', flexShrink: 0 }}>
          <img src={LOGO} alt="EXO7 ENERGY" style={{ height: isMobile ? 46 : 64, width: 'auto', display: 'block' }} />
        </a>
        {!isMobile && (
          <nav style={{ display: 'flex', gap: 32, fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 500, letterSpacing: '0.02em' }}>
            {links.map((l) => (
              <a key={l.id} href={l.href} style={{
                color: active === l.id ? EXO.cobalt : EXO.ink,
                textDecoration: 'none',
                borderBottom: active === l.id ? `1.5px solid ${EXO.cobalt}` : '1.5px solid transparent',
                paddingBottom: 4,
              }}>{l.label}</a>
            ))}
          </nav>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 12 : 20 }}>
          <div style={{ display: 'flex', gap: 2, fontSize: 12, fontFamily: 'Inter', fontWeight: 600, letterSpacing: '0.06em' }}>
            {(window.EXO7_LANGS || ['FR', 'EN']).map(l => (
              <button key={l} onClick={() => setLang(l)} style={{
                background: 'none', border: 'none', cursor: 'pointer',
                color: lang === l ? EXO.ink : EXO.inkMute,
                padding: isMobile ? '4px 4px' : '4px 6px',
                textDecoration: lang === l ? 'underline' : 'none',
                textUnderlineOffset: 4,
              }}>{l}</button>
            ))}
          </div>
          {!isMobile && (
            <button onClick={() => window.dispatchEvent(new CustomEvent('exo7-open-callback'))} style={{
              background: 'none', border: `1px solid ${EXO.cobalt}`, color: EXO.cobalt,
              padding: '9px 16px', fontSize: 13, fontWeight: 600,
              fontFamily: 'Inter', letterSpacing: '0.04em',
              cursor: 'pointer', borderRadius: 2,
              display: 'inline-flex', alignItems: 'center', gap: 8,
            }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 4h4l2 5-2.5 1.5a11 11 0 005 5L15 13l5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/></svg>
              {tt({ FR: 'Être rappelé', EN: 'Request a callback' })}
            </button>
          )}
          {!isMobile && (
            <a href="contact.html" style={{
              background: EXO.cobalt, color: '#fff',
              padding: '10px 18px', fontSize: 13, fontWeight: 600,
              fontFamily: 'Inter', letterSpacing: '0.04em',
              textDecoration: 'none', borderRadius: 2,
              display: 'inline-flex', alignItems: 'center', gap: 8,
            }}>
              {t.nav.cta}
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2 6h8m0 0L6 2m4 4L6 10" stroke="currentColor" strokeWidth="1.5"/></svg>
            </a>
          )}
          {isMobile && (
            <button onClick={() => setOpen(!open)} aria-label="Menu" style={{
              background: 'none', border: `1px solid ${EXO.line}`,
              padding: '10px 12px', cursor: 'pointer', borderRadius: 2,
            }}>
              <svg width="18" height="14" viewBox="0 0 18 14" fill="none">
                {open
                  ? <path d="M2 2l14 10M2 12L16 2" stroke={EXO.ink} strokeWidth="1.5"/>
                  : <path d="M0 1.5h18M0 7h18M0 12.5h18" stroke={EXO.ink} strokeWidth="1.5"/>}
              </svg>
            </button>
          )}
        </div>
      </div>
      {isMobile && open && (
        <nav style={{
          background: EXO.bg, borderTop: `1px solid ${EXO.line}`,
          padding: '12px 20px 24px',
        }}>
          {links.map((l) => (
            <a key={l.id} href={l.href} style={{
              display: 'block', padding: '14px 0',
              borderBottom: `1px solid ${EXO.line}`,
              fontFamily: 'Inter', fontSize: 16, fontWeight: 500,
              color: active === l.id ? EXO.cobalt : EXO.ink,
              textDecoration: 'none',
            }}>{l.label}</a>
          ))}
          <button onClick={() => { setOpen(false); window.dispatchEvent(new CustomEvent('exo7-open-callback')); }} style={{
            marginTop: 20, width: '100%', background: 'none',
            border: `1px solid ${EXO.cobalt}`, color: EXO.cobalt,
            padding: '14px 18px', fontSize: 14, fontWeight: 600,
            fontFamily: 'Inter', letterSpacing: '0.04em',
            borderRadius: 2, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            {tt({ FR: 'Être rappelé', EN: 'Request a callback' })}
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M5 4h4l2 5-2.5 1.5a11 11 0 005 5L15 13l5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/></svg>
          </button>
          <a href="contact.html" style={{
            marginTop: 12, background: EXO.cobalt, color: '#fff',
            padding: '14px 18px', fontSize: 14, fontWeight: 600,
            fontFamily: 'Inter', letterSpacing: '0.04em',
            textDecoration: 'none', borderRadius: 2,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            {t.nav.cta}
            <svg width="14" height="14" viewBox="0 0 12 12" fill="none"><path d="M2 6h8m0 0L6 2m4 4L6 10" stroke="currentColor" strokeWidth="1.5"/></svg>
          </a>
        </nav>
      )}
    </header>
  );
}
window.SiteHeader = SiteHeader;

// ---- Callback modal ----
function CallbackModal() {
  const { tt } = useLang();
  const [open, setOpen] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => {
    const h = () => setOpen(true);
    window.addEventListener('exo7-open-callback', h);
    return () => window.removeEventListener('exo7-open-callback', h);
  }, []);
  function close() { setOpen(false); setTimeout(() => setSent(false), 300); }
  function onSubmit(e) { e.preventDefault(); setSent(true); }
  if (!open) return null;

  const field = {
    width: '100%', padding: '12px 14px', boxSizing: 'border-box',
    border: `1px solid ${EXO.line}`, borderRadius: 0,
    fontFamily: 'Inter', fontSize: 14, color: EXO.ink, background: '#fff', outline: 'none',
  };
  const lbl = { display: 'block', fontFamily: 'Inter', fontSize: 12, color: '#5b5f6a', marginBottom: 6, fontWeight: 500, letterSpacing: '0.02em' };
  const star = <span style={{ color: '#e26b6b', fontWeight: 700 }}> *</span>;

  return (
    <div onClick={close} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,20,38,0.6)',
      zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20, animation: 'exoFadeIn .2s ease',
    }}>
      <style>{`@keyframes exoFadeIn{from{opacity:0}to{opacity:1}} @keyframes exoSlideUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:none}}`}</style>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', maxWidth: 480, width: '100%',
        maxHeight: '90vh', overflowY: 'auto',
        padding: '40px 44px', position: 'relative',
        boxShadow: '0 30px 80px rgba(0,0,0,0.35)', animation: 'exoSlideUp .3s ease',
      }}>
        <button onClick={close} aria-label="Fermer" style={{
          position: 'absolute', top: 16, right: 16,
          background: 'transparent', border: 0, cursor: 'pointer',
          width: 36, height: 36, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: EXO.inkMute, borderRadius: 4,
        }}>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 3l12 12M15 3L3 15" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
        </button>
        {!sent ? (
          <>
            <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 28, lineHeight: 1.1, letterSpacing: '-0.02em', fontWeight: 500, margin: '0 0 12px', color: EXO.ink }}>
              {tt({ FR: 'Être rappelé', EN: 'Request a callback' })}
            </h3>
            <p style={{ fontFamily: 'Inter', fontSize: 14, color: EXO.inkMute, margin: '0 0 28px', lineHeight: 1.5 }}>
              {tt({ FR: 'Laissez votre numéro, notre équipe technique vous rappelle sous 24h ouvrées.', EN: 'Leave your number, our technical team calls you back within 24 working hours.' })}
            </p>
            <form onSubmit={onSubmit} style={{ display: 'grid', gap: 14 }}>
              <label style={{ display: 'block' }}>
                <span style={lbl}>{tt({ FR: 'Nom complet', EN: 'Full name' })}{star}</span>
                <input name="nom" required style={field} />
              </label>
              <label style={{ display: 'block' }}>
                <span style={lbl}>{tt({ FR: 'Téléphone', EN: 'Phone' })}{star}</span>
                <input name="tel" type="tel" required style={field} />
              </label>
              <label style={{ display: 'block' }}>
                <span style={lbl}>{tt({ FR: 'Créneau souhaité (optionnel)', EN: 'Preferred time (optional)' })}</span>
                <select name="creneau" style={{ ...field, cursor: 'pointer' }}>
                  {tt({ FR: ['Peu importe', 'Matin (9h-12h)', 'Après-midi (14h-18h)'], EN: ['No preference', 'Morning (9-12)', 'Afternoon (2-6pm)'] }).map((o) => <option key={o}>{o}</option>)}
                </select>
              </label>
              <button type="submit" style={{
                background: EXO.cobalt, color: '#fff', border: 0, padding: '18px 28px', marginTop: 8,
                fontFamily: 'Inter', fontSize: 14, fontWeight: 600, letterSpacing: '0.04em', cursor: 'pointer',
              }}>
                {tt({ FR: 'Demander à être rappelé', EN: 'Request callback' })}
              </button>
              <p style={{ fontFamily: 'JetBrains Mono', fontSize: 10.5, color: EXO.inkMute, letterSpacing: '0.05em', margin: '6px 0 0', lineHeight: 1.5 }}>
                {tt({ FR: 'Ou écrivez-nous à contact@exo7-solutions.fr', EN: 'Or email us at contact@exo7-solutions.fr' })}
              </p>
            </form>
          </>
        ) : (
          <div style={{ padding: '20px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'rgba(62,192,122,0.15)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none"><path d="M4 12l5 5L20 7" stroke="#3ec07a" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 26, lineHeight: 1.1, letterSpacing: '-0.02em', fontWeight: 500, margin: '0 0 14px', color: EXO.ink }}>
              {tt({ FR: 'Demande envoyée.', EN: 'Request sent.' })}
            </h3>
            <p style={{ fontFamily: 'Inter', fontSize: 15, color: EXO.inkMute, margin: 0, lineHeight: 1.6 }}>
              {tt({ FR: 'Nous vous rappelons sous 24h ouvrées.', EN: 'We will call you back within 24 working hours.' })}
            </p>
            <button onClick={close} style={{ marginTop: 28, background: EXO.ink, color: '#fff', border: 0, padding: '14px 24px', fontFamily: 'Inter', fontSize: 13, fontWeight: 600, letterSpacing: '0.04em', cursor: 'pointer' }}>
              {tt({ FR: 'Fermer', EN: 'Close' })}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
window.CallbackModal = CallbackModal;

// ---- Site Footer ----
function SiteFooter() {
  const { t, tt } = useLang();
  const { isMobile } = useViewport();
  return (
    <footer style={{ background: EXO.ink, color: 'rgba(255,255,255,0.6)', padding: isMobile ? '48px 0 24px' : '64px 0 32px' }}>
      <div style={{ maxWidth: 1440, margin: '0 auto', padding: isMobile ? '0 20px' : '0 48px' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '2fr 1fr 1fr 1fr',
          gap: isMobile ? 40 : 64, marginBottom: isMobile ? 40 : 64,
        }}>
          <div>
            <div style={{ background: '#fff', display: 'inline-block', padding: '14px 18px', borderRadius: 3, marginBottom: 24 }}>
              <img src={LOGO} alt="EXO7 ENERGY" style={{ height: 64, display: 'block' }} />
            </div>
            <p style={{ fontFamily: 'Inter', fontSize: 13, lineHeight: 1.6, maxWidth: 340, margin: 0 }}>
              {t.footer.tagline}
            </p>
          </div>
          {[
            { t: t.footer.site, l: [
              { label: t.nav.home, href: 'index.html' },
              { label: t.nav.expertise, href: 'expertises.html' },
              { label: t.nav.works, href: 'realisations.html' },
              { label: t.nav.about, href: 'groupe.html' },
              { label: t.nav.contact, href: 'contact.html' },
            ]},
            { t: t.footer.expertise, l: [
              { label: tt({ FR: 'Travaux neufs', EN: 'New works' }), href: 'expertises.html' },
              { label: tt({ FR: 'Rénovations', EN: 'Retrofits' }), href: 'expertises.html' },
              { label: tt({ FR: 'Maintenance & SAV', EN: 'Maintenance & service' }), href: 'expertises.html' },
              { label: tt({ FR: 'Solutions & Services', EN: 'Solutions & services' }), href: 'expertises.html' },
            ]},
            { t: t.footer.contact, l: [
              { label: 'contact@exo7-solutions.fr', href: 'mailto:contact@exo7-solutions.fr' },
              { label: 'LinkedIn — EXO7 ENERGY', href: 'https://www.linkedin.com/company/exo7-energy/' },
              { label: 'ERYX PREFA', href: 'https://www.eryx-prefa.fr' },
            ]},
          ].map((col, i) => (
            <div key={i}>
              <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: EXO.rose, letterSpacing: '0.15em', marginBottom: 16 }}>{col.t}</div>
              {col.l.map(item => (
                <a key={item.label} href={item.href} style={{ display: 'block', fontFamily: 'Inter', fontSize: 13, marginBottom: 8, color: 'inherit', textDecoration: 'none' }}>{item.label}</a>
              ))}
            </div>
          ))}
        </div>
        <div style={{
          paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.15)',
          display: 'flex', justifyContent: 'space-between',
          fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.15em',
          flexWrap: 'wrap', gap: 16, alignItems: 'center',
        }}>
          <span>{t.footer.copy}</span>
          <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
            <a href="mentions-legales.html" style={{ color: 'inherit', textDecoration: 'none' }}>{t.footer.legalLink.toUpperCase()}</a>
            <a href="confidentialite.html" style={{ color: 'inherit', textDecoration: 'none' }}>{t.footer.privacyLink.toUpperCase()}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}
window.SiteFooter = SiteFooter;

// ---- Page wrapper ----
function PageShell({ active, children }) {
  const { isMobile } = useViewport();
  return (
    <div style={{
      background: EXO.bg, color: EXO.ink,
      fontFamily: 'Inter, sans-serif',
      width: '100%',
      minWidth: isMobile ? 320 : 'auto',
      overflowX: 'clip',
    }}>
      <SiteHeader active={active} />
      {children}
      <SiteFooter />
      <CallbackModal />
    </div>
  );
}
window.PageShell = PageShell;

// ---- Inner-page hero ----
function PageHero({ kicker, title, subtitle, photo, accent, photoPos }) {
  const { isMobile } = useViewport();
  return (
    <section style={{ position: 'relative', minHeight: isMobile ? 420 : 'clamp(480px, 36vw, 680px)', background: EXO.ink, overflow: 'hidden' }}>
      {photo && (
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url(${photo})`,
          backgroundSize: 'cover',
          backgroundPosition: photoPos || 'center',
          backgroundRepeat: 'no-repeat',
          filter: 'brightness(0.62) contrast(1.02)',
        }} />
      )}
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 8, background: EXO.cobalt }} />
      <div style={{
        position: 'relative', maxWidth: 1440, margin: '0 auto',
        padding: isMobile ? '24px 20px 0' : '32px 48px 0',
        display: 'flex', justifyContent: 'space-between',
        fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 10 : 11,
        color: 'rgba(255,255,255,0.6)', letterSpacing: '0.15em', gap: 12, flexWrap: 'wrap',
      }}>
        <span>{kicker}</span>
        {!isMobile && <span>EXO7 ENERGY / GROUPE ENERGY INVEST</span>}
      </div>
      <div style={{
        position: 'relative', maxWidth: 1440, margin: '0 auto',
        padding: isMobile ? '52px 20px 72px' : '92px 48px 96px', color: '#fff',
      }}>
        {accent && (
          <div style={{
            fontFamily: 'JetBrains Mono', fontSize: 12, color: EXO.rose, letterSpacing: '0.2em',
            marginBottom: 28, display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <span style={{ width: 32, height: 1, background: EXO.rose }} />
            {accent}
          </div>
        )}
        <h1 style={{
          fontFamily: 'Space Grotesk, sans-serif',
          fontSize: 'clamp(40px, 6vw, 84px)', lineHeight: 0.95, letterSpacing: '-0.03em',
          fontWeight: 500, margin: 0, maxWidth: 1100, textWrap: 'pretty',
          textShadow: '0 2px 12px rgba(0,0,0,0.45)',
        }}>{title}</h1>
        {subtitle && (
          <p style={{
            marginTop: 32, fontFamily: 'Inter, sans-serif', fontSize: isMobile ? 16 : 18, lineHeight: 1.55,
            color: 'rgba(255,255,255,0.95)', textShadow: '0 1px 4px rgba(0,0,0,0.4)', maxWidth: 720,
          }}>{subtitle}</p>
        )}
      </div>
    </section>
  );
}
window.PageHero = PageHero;
