// ─── shared.jsx — composants partagés ─────────────────────────────────────────
// Chargé via <script type="text/babel" src="assets/shared.jsx"> sur chaque page.
// Expose tout sur window pour que le script de page puisse l'utiliser.

const { useState, useEffect, useRef } = React;

// ─── Couleurs & Thèmes ────────────────────────────────────────────────────────
const C = {
  blue: '#5586be', gold: '#d4af37', blush: '#ebd9d8',
  ink: '#1c2340', inkMid: '#3d4a6b', inkSoft: '#7a86a1',
  white: '#fdfaf8', offwhite: '#f5f0ec'
};

const THEMES = {
  light: {
    bg: C.white, bgAlt: C.offwhite, bgBlush: C.blush,
    fg: C.ink, fgMid: C.inkMid, fgSoft: C.inkSoft,
    navBg: C.white, navBorder: 'rgba(85,134,190,0.12)', navFg: C.ink,
    cardBg: C.white, cardBorder: 'rgba(85,134,190,0.14)',
    footerBg: C.ink, footerFg: 'rgba(255,255,255,0.85)', footerSoft: 'rgba(255,255,255,0.4)'
  },
  dark: {
    bg: '#111827', bgAlt: '#1c2340', bgBlush: '#1f2b42',
    fg: '#e8eaf6', fgMid: '#a9b4cc', fgSoft: '#6b7a99',
    navBg: '#0d1221', navBorder: 'rgba(85,134,190,0.2)', navFg: '#e8eaf6',
    cardBg: '#1c2340', cardBorder: 'rgba(85,134,190,0.2)',
    footerBg: '#080d18', footerFg: 'rgba(255,255,255,0.8)', footerSoft: 'rgba(255,255,255,0.35)'
  }
};

function getTokens(tweaks) {
  const t = THEMES[tweaks.theme] || THEMES.light;
  const accent = tweaks.accentMode === 'blue' ? C.blue : C.gold;
  const accentFg = tweaks.accentMode === 'blue' ? '#fff' : C.ink;
  const accentSoft = tweaks.accentMode === 'blue' ? 'rgba(85,134,190,0.12)' : 'rgba(212,175,55,0.12)';
  return { ...t, accent, accentFg, accentSoft, blue: C.blue, gold: C.gold, blush: C.blush, ink: C.ink };
}

// ─── Hook Tweaks ─────────────────────────────────────────────────────────────
function useTweaks(defaults) {
  const [vals, setVals] = useState(defaults);
  function setTweak(key, value) {
    const update = typeof key === 'object' ? key : { [key]: value };
    setVals(prev => {
      const next = { ...prev, ...update };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
      return next;
    });
  }
  return [vals, setTweak];
}

// ─── Animation ───────────────────────────────────────────────────────────────
function useScrollAnim(direction = 'fadeUp', delay = 0) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    el.classList.add('anim-ready');
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setTimeout(() => { el.classList.remove('anim-ready'); el.classList.add('anim-' + direction); }, delay);
        obs.disconnect();
      }
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}

function A({ children, dir = 'fadeUp', delay = 0, style = {}, className = '' }) {
  const ref = useScrollAnim(dir, delay);
  return <div ref={ref} style={style} className={className}>{children}</div>;
}

// ─── UI de base ───────────────────────────────────────────────────────────────
function Btn({ children, href, onClick, variant = 'primary', t, style = {} }) {
  const [hover, setHover] = useState(false);
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    border: 'none', cursor: 'pointer', fontFamily: 'Raleway', fontWeight: 800,
    fontSize: 14, letterSpacing: 0.8, textTransform: 'uppercase',
    padding: '14px 32px', transition: 'all .2s', textDecoration: 'none', ...style
  };
  const handlers = { onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false) };
  if (variant === 'primary') {
    const s = { ...base, background: hover ? t.blue : t.accent, color: hover ? '#fff' : t.accentFg,
      transform: hover ? 'translateY(-2px)' : '', boxShadow: hover ? '0 8px 24px rgba(85,134,190,0.3)' : '' };
    return href ? <a href={href} style={s} {...handlers}>{children}</a>
                : <button onClick={onClick} style={s} {...handlers}>{children}</button>;
  }
  if (variant === 'outline') {
    const s = { ...base, background: hover ? t.accent : 'transparent', color: hover ? t.accentFg : t.fg, border: `2px solid ${t.accent}` };
    return href ? <a href={href} style={s} {...handlers}>{children}</a>
                : <button onClick={onClick} style={s} {...handlers}>{children}</button>;
  }
  if (variant === 'ghost') {
    const s = { ...base, background: hover ? t.accentSoft : 'transparent', color: t.accent, padding: '12px 24px', fontSize: 13 };
    return href ? <a href={href} style={s} {...handlers}>{children} →</a>
                : <button onClick={onClick} style={s} {...handlers}>{children} →</button>;
  }
}

function Tag({ children, t }) {
  return <span style={{ display: 'inline-block', background: t.accentSoft, color: t.accent,
    fontFamily: 'Raleway', fontWeight: 800, fontSize: 11, letterSpacing: 2,
    textTransform: 'uppercase', padding: '6px 14px', marginBottom: 16 }}>{children}</span>;
}

function Divider({ t }) {
  return <div style={{ width: 48, height: 3, background: t.accent, margin: '20px 0' }} />;
}

// ─── Navigation ───────────────────────────────────────────────────────────────
function Nav({ t }) {
  const [open, setOpen] = useState(false);
  const path = window.location.pathname;
  const currentId = path.includes('a-propos') ? 'about'
    : path.includes('livre') ? 'book'
    : path.includes('commander') ? 'order'
    : 'home';

  const links = [
    { id: 'home',    href: 'index.html',     label: 'Accueil' },
    { id: 'about',   href: 'a-propos.html',  label: 'À propos' },
    { id: 'book',    href: 'livre.html',      label: 'Le Livre' },
    { id: 'order',   href: 'commander.html',  label: 'Commander' },
  ];

  return (
    <nav style={{ position: 'sticky', top: 0, zIndex: 100, background: t.navBg,
      borderBottom: `1px solid ${t.navBorder}`, backdropFilter: 'blur(8px)' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 24px', height: 68,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        {/* Logo */}
        <a href="index.html" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <img src="assets/logo-mr.png" alt="Hasnae Bendriss" style={{ width: 38, height: 38, objectFit: 'cover', flexShrink: 0 }} />
          <div>
            <div style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 13, color: t.navFg, letterSpacing: 0.5, lineHeight: 1.2 }}>Hasnae Bendriss</div>
            <div style={{ fontFamily: 'Roboto', fontWeight: 300, fontSize: 11, color: t.fgSoft, letterSpacing: 1 }}>PERSONAL BRANDING · COPYWRITING MAROC</div>
          </div>
        </a>
        {/* Desktop links */}
        <div className="desktop-links" style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
          {links.map(l => (
            <a key={l.id} href={l.href} style={{
              fontFamily: 'Raleway', fontWeight: 700, fontSize: 13, letterSpacing: 0.8,
              textTransform: 'uppercase', color: currentId === l.id ? t.accent : t.navFg,
              borderBottom: `2px solid ${currentId === l.id ? t.accent : 'transparent'}`,
              paddingBottom: 3, transition: 'color .2s', textDecoration: 'none'
            }}>{l.label}</a>
          ))}
          <Btn href="commander.html" t={t} style={{ padding: '10px 24px', fontSize: 12 }}>Commander</Btn>
        </div>
        {/* Hamburger */}
        <button className="hamburger-btn" onClick={() => setOpen(o => !o)}
          style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer',
            alignItems: 'center', justifyContent: 'center', width: 40, height: 40 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            {[0,1,2].map(i => <div key={i} style={{ width: 22, height: 2, background: t.navFg, transition: 'all .2s',
              transform: open ? i===0 ? 'rotate(45deg) translateY(10px)' : i===2 ? 'rotate(-45deg) translateY(-10px)' : 'scaleX(0)' : '' }} />)}
          </div>
        </button>
      </div>
      {/* Mobile menu */}
      {open && (
        <div style={{ background: t.navBg, borderTop: `1px solid ${t.navBorder}`, padding: '16px 24px 24px' }}>
          {links.map(l => (
            <a key={l.id} href={l.href} style={{
              display: 'block', fontFamily: 'Raleway', fontWeight: 700, fontSize: 16,
              color: currentId === l.id ? t.accent : t.navFg, padding: '12px 0',
              borderBottom: `1px solid ${t.navBorder}`, textDecoration: 'none'
            }}>{l.label}</a>
          ))}
          <div style={{ marginTop: 20 }}>
            <Btn href="commander.html" t={t} style={{ width: '100%', padding: '14px', fontSize: 14 }}>Commander le livre</Btn>
          </div>
        </div>
      )}
    </nav>
  );
}

// ─── Footer ───────────────────────────────────────────────────────────────────
function Footer({ t }) {
  const navLinks = [
    { href: 'index.html',    label: 'Accueil' },
    { href: 'a-propos.html', label: 'À propos' },
    { href: 'livre.html',    label: 'Le Livre' },
    { href: 'commander.html',label: 'Commander' },
  ];
  return (
    <footer style={{ background: t.footerBg, padding: '60px 24px 32px' }}>
      <div className="footer-grid" style={{ maxWidth: 1200, margin: '0 auto',
        display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 40, marginBottom: 40 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
            <img src="assets/logo-mr.png" alt="MR" style={{ width: 38, height: 38, objectFit: 'cover', flexShrink: 0 }} />
            <span style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 13, color: t.footerFg, letterSpacing: 0.5 }}>HASNAE BENDRISS</span>
          </div>
          <p style={{ fontFamily: 'Roboto', fontStyle: 'italic', fontSize: 15, lineHeight: 1.8,
            color: t.footerSoft, maxWidth: 340, marginBottom: 8 }}>
            "On commence tous par une petite communauté, et celle-ci grandit avec du temps et de la persévérance."
          </p>
          <p style={{ fontFamily: 'Roboto', fontSize: 12, color: t.footerSoft }}>Auteure · Experte Personal Branding · Top 1 Copywriting Maroc</p>
        </div>
        <div>
          <div style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 11, letterSpacing: 2,
            color: C.gold, textTransform: 'uppercase', marginBottom: 20 }}>Navigation</div>
          {navLinks.map(l => (
            <div key={l.href} style={{ marginBottom: 10 }}>
              <a href={l.href} style={{ fontFamily: 'Roboto', fontSize: 14, color: t.footerFg, opacity: 0.8 }}>{l.label}</a>
            </div>
          ))}
        </div>
        <div>
          <div style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 11, letterSpacing: 2,
            color: C.gold, textTransform: 'uppercase', marginBottom: 20 }}>Contact</div>
          <p style={{ fontFamily: 'Roboto', fontSize: 14, color: t.footerFg, opacity: 0.8, lineHeight: 1.8 }}>
            <a href="mailto:marketing@hbendriss.com" style={{ color: t.footerFg, opacity: 0.8 }}>marketing@hbendriss.com</a>
          </p>
          <div style={{ marginTop: 16 }}>
            <a href="https://linkedin.com/in/hasnae-bendriss" target="_blank" rel="noopener noreferrer"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: t.footerFg,
                fontSize: 14, opacity: 0.8, fontFamily: 'Roboto' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
              LinkedIn
            </a>
          </div>
          <div style={{ marginTop: 12 }}>
            <a href="https://hbendriss.com" target="_blank" rel="noopener noreferrer"
              style={{ fontFamily: 'Roboto', fontSize: 14, color: C.gold, opacity: 0.9 }}>hbendriss.com →</a>
          </div>
        </div>
      </div>
      <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', paddingTop: 24,
        display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
        <span style={{ fontFamily: 'Roboto', fontSize: 12, color: t.footerSoft }}>© 2026 Hasnae Bendriss · Tous droits réservés.</span>
        <span style={{ fontFamily: 'Roboto', fontSize: 12, color: t.footerSoft }}>Personal Branding Maroc · livre.hbendriss.com</span>
      </div>
    </footer>
  );
}

// ─── Panneau Tweaks ───────────────────────────────────────────────────────────
function TweaksPanel({ tweaks, setTweak, onClose }) {
  return (
    <div style={{ position: 'fixed', bottom: 24, right: 24, width: 268, background: '#0d1221',
      borderRadius: 10, boxShadow: '0 12px 48px rgba(0,0,0,0.5)', padding: '20px 20px 24px',
      zIndex: 9999, border: '1px solid rgba(85,134,190,0.25)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <span style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 14, color: '#e8eaf6' }}>Tweaks</span>
        <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#6b7a99', cursor: 'pointer', fontSize: 18 }}>✕</button>
      </div>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontFamily: 'Raleway', fontWeight: 700, fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', color: '#6b7a99', marginBottom: 10 }}>Thème</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[['light','Clair'],['dark','Sombre']].map(([id, label]) => (
            <button key={id} onClick={() => setTweak('theme', id)} style={{
              background: tweaks.theme === id ? C.blue : 'rgba(255,255,255,0.06)',
              color: tweaks.theme === id ? '#fff' : '#a9b4cc',
              border: `1px solid ${tweaks.theme === id ? C.blue : 'rgba(255,255,255,0.08)'}`,
              cursor: 'pointer', padding: '9px 0', borderRadius: 5,
              fontFamily: 'Raleway', fontWeight: 700, fontSize: 12
            }}>{label}</button>
          ))}
        </div>
      </div>
      <div>
        <div style={{ fontFamily: 'Raleway', fontWeight: 700, fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', color: '#6b7a99', marginBottom: 10 }}>Couleur d'accent</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[['gold','Or'],['blue','Bleu']].map(([id, label]) => (
            <button key={id} onClick={() => setTweak('accentMode', id)} style={{
              background: tweaks.accentMode === id ? (id==='gold' ? C.gold : C.blue) : 'rgba(255,255,255,0.06)',
              color: tweaks.accentMode === id ? (id==='gold' ? C.ink : '#fff') : '#a9b4cc',
              border: `1px solid ${tweaks.accentMode === id ? (id==='gold' ? C.gold : C.blue) : 'rgba(255,255,255,0.08)'}`,
              cursor: 'pointer', padding: '9px 0', borderRadius: 5,
              fontFamily: 'Raleway', fontWeight: 700, fontSize: 11
            }}>{label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── OrderField (hors composant Order pour éviter remount) ────────────────────
function OrderField({ id, label, placeholder, type='text', required=false, form, errors, setForm, setErrors, accent }) {
  return (
    <div>
      <label style={{ display: 'block', fontFamily: 'Raleway', fontWeight: 700, fontSize: 12,
        color: '#000', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 8 }}>
        {label}{required && <span style={{ color: '#c00' }}> *</span>}
      </label>
      <input type={type} value={form[id]} placeholder={placeholder}
        onChange={e => { setForm(s => ({ ...s, [id]: e.target.value })); setErrors(er => ({ ...er, [id]: null })); }}
        style={{ width: '100%', padding: '13px 16px', background: '#fff',
          border: `2px solid ${errors[id] ? '#c00' : '#ccc'}`, color: '#000',
          fontSize: 15, outline: 'none', transition: 'border-color .2s', fontFamily: 'Roboto' }}
        onFocus={e => e.target.style.borderColor = accent}
        onBlur={e => e.target.style.borderColor = errors[id] ? '#c00' : '#ccc'}
      />
      {errors[id] && <div style={{ color: '#c00', fontSize: 12, marginTop: 4 }}>{errors[id]}</div>}
    </div>
  );
}

// ─── Bloc hbendriss.com réutilisable ──────────────────────────────────────────
function HbendrissBlock({ t, dark = false }) {
  const bg   = dark ? C.ink   : t.bgAlt;
  const fg   = dark ? '#fff'  : t.fg;
  const fgS  = dark ? 'rgba(255,255,255,0.6)' : t.fgMid;
  const btnBg= dark ? C.gold  : t.accent;
  const btnFg= dark ? C.ink   : t.accentFg;
  return (
    <section style={{ background: bg, padding: '48px 24px', borderTop: `4px solid ${C.gold}` }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', flexWrap: 'wrap',
        alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
        <div>
          <div style={{ fontFamily: 'Raleway', fontWeight: 800, fontSize: 11, letterSpacing: 2,
            textTransform: 'uppercase', color: C.gold, marginBottom: 8 }}>Conseil & Accompagnement</div>
          <div style={{ fontFamily: 'Anton', fontSize: 'clamp(18px,2.5vw,30px)', color: fg, marginBottom: 6 }}>
            ACCOMPAGNEMENT PERSONAL BRANDING — HBENDRISS.COM
          </div>
          <div style={{ fontFamily: 'Roboto', fontSize: 14, color: fgS }}>
            Stratégie LinkedIn, copywriting et personal branding pour professionnels et entreprises au Maroc.
          </div>
        </div>
        <a href="https://hbendriss.com" target="_blank" rel="noopener noreferrer"
          style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: btnBg,
            color: btnFg, fontFamily: 'Raleway', fontWeight: 800, fontSize: 13,
            letterSpacing: 0.8, textTransform: 'uppercase', padding: '14px 32px', whiteSpace: 'nowrap' }}>
          Visiter hbendriss.com →
        </a>
      </div>
    </section>
  );
}

// ─── Exporter vers window ─────────────────────────────────────────────────────
Object.assign(window, {
  C, THEMES, getTokens, useTweaks,
  useScrollAnim, A,
  Btn, Tag, Divider,
  Nav, Footer, TweaksPanel,
  OrderField, HbendrissBlock
});
