/* global React */
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

/* ============ LANGUAGE SWITCHER ============ */
// Multilingue — charge les fichiers JSON i18n et traduit la page.
const FLAG_SVG = {
  fr: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'213.3',height:'480',fill:'#002654'}),React.createElement('rect',{x:'213.3',width:'213.3',height:'480',fill:'#fff'}),React.createElement('rect',{x:'426.6',width:'213.4',height:'480',fill:'#CE1126'})),
  en: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'640',height:'480',fill:'#012169'}),React.createElement('path',{d:'M75 0l244 181L562 0h78v62L400 241l240 178v61h-80L320 301 81 480H0v-60l239-178L0 64V0h75z',fill:'#fff'}),React.createElement('path',{d:'M424 281l216 159v40L369 281h55zm-184 20l6 35L54 480H0l240-179zM640 0v3L391 191l2-44L590 0h50zM0 0l239 176h-60L0 42V0z',fill:'#C8102E'}),React.createElement('path',{d:'M241 0v480h160V0H241zM0 160v160h640V160H0z',fill:'#fff'}),React.createElement('path',{d:'M0 193v96h640v-96H0zM273 0v480h96V0h-96z',fill:'#C8102E'})),
  de: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'640',height:'160',fill:'#000'}),React.createElement('rect',{y:'160',width:'640',height:'160',fill:'#D00'}),React.createElement('rect',{y:'320',width:'640',height:'160',fill:'#FFCE00'})),
  es: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'640',height:'480',fill:'#AA151B'}),React.createElement('rect',{y:'120',width:'640',height:'240',fill:'#F1BF00'})),
  it: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'213.3',height:'480',fill:'#009246'}),React.createElement('rect',{x:'213.3',width:'213.3',height:'480',fill:'#fff'}),React.createElement('rect',{x:'426.6',width:'213.4',height:'480',fill:'#CE2B37'})),
  pt: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'640',height:'480',fill:'#006600'}),React.createElement('rect',{x:'256',width:'384',height:'480',fill:'#FF0000'}),React.createElement('circle',{cx:'256',cy:'240',r:'64',fill:'#FFCC00'})),
  ru: React.createElement('svg',{xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 640 480',width:'20',height:'15',style:{borderRadius:2,display:'block'}},React.createElement('rect',{width:'640',height:'160',fill:'#fff'}),React.createElement('rect',{y:'160',width:'640',height:'160',fill:'#0039A6'}),React.createElement('rect',{y:'320',width:'640',height:'160',fill:'#D52B1E'})),
};
const LANGUAGES = [
  { code: 'fr', label: 'Français' },
  { code: 'en', label: 'English' },
  { code: 'de', label: 'Deutsch' },
  { code: 'es', label: 'Español' },
  { code: 'it', label: 'Italiano' },
  { code: 'pt', label: 'Português' },
  { code: 'ru', label: 'Русский' },
];
function getLang() { try { return localStorage.getItem('yo-lang') || 'fr'; } catch (e) { return 'fr'; } }
function setLang(code) { try { localStorage.setItem('yo-lang', code); } catch(e) {} document.documentElement.setAttribute('lang', code); window.dispatchEvent(new CustomEvent('yo-lang-change', { detail: code })); }

function LangSwitcher({ variant = 'header' }) {
  const [lang, setLangState] = useStateS(getLang());
  const [open, setOpen] = useStateS(false);
  const ref = useRefS(null);
  useEffectS(() => {
    document.documentElement.setAttribute('lang', lang);
    const onClick = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [lang]);
  const current = LANGUAGES.find(l => l.code === lang) || LANGUAGES[0];
  const choose = code => { setLang(code); setLangState(code); setOpen(false); };
  return (
    <div className={'lang-switcher lang-' + variant} ref={ref}>
      <button className="lang-btn" onClick={() => setOpen(v => !v)} aria-haspopup="listbox" aria-expanded={open} aria-label={'Langue actuelle : ' + current.label}>
        <span className="lang-flag" aria-hidden="true">{FLAG_SVG[current.code]}</span>
        <span className="lang-code">{current.code.toUpperCase()}</span>
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ transition: 'transform .25s', transform: open ? 'rotate(180deg)' : 'none' }}><polyline points="6 9 12 15 18 9"/></svg>
      </button>
      {open && (
        <ul className="lang-menu" role="listbox">
          {LANGUAGES.map(l => (
            <li key={l.code}>
              <button type="button" onClick={() => choose(l.code)} className={l.code === lang ? 'active' : ''} role="option" aria-selected={l.code === lang}>
                <span className="lang-flag" aria-hidden="true">{FLAG_SVG[l.code]}</span>
                <span>{l.label}</span>
                {l.code === lang && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 'auto' }}><polyline points="20 6 9 17 4 12"/></svg>}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function Header({ currentPage = 'home' }) {
  const t = useI18n();
  const [scrolled, setScrolled] = useStateS(false);
  const [menuOpen, setMenuOpen] = useStateS(false);
  const [dropOpen, setDropOpen] = useStateS(false);
  const dropRef = useRefS(null);
  useEffectS(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll); onScroll();
    const onClick = e => { if (dropRef.current && !dropRef.current.contains(e.target)) setDropOpen(false); };
    document.addEventListener('click', onClick);
    return () => { window.removeEventListener('scroll', onScroll); document.removeEventListener('click', onClick); };
  }, []);

  const isServices = ['sites', 'surmesure', 'heberg'].includes(currentPage);
  const servicesItems = [
    { href: 'sites.html', id: 'sites', label: t('common.nav.services_sites_label', 'Sites web'), desc: t('common.nav.services_sites_desc', 'Vitrine, e-commerce, WordPress') },
    { href: 'surmesure.html', id: 'surmesure', label: t('common.nav.services_surmesure_label', 'Sur-mesure & IA'), desc: t('common.nav.services_surmesure_desc', 'Apps, CRM, ERP, chatbots, automatisation') },
    { href: 'hebergement.html', id: 'heberg', label: t('common.nav.services_heberg_label', 'Hébergement'), desc: t('common.nav.services_heberg_desc', 'Serveurs, domaines, maintenance') },
  ];
  const links = [
    { href: 'index.html', id: 'home', label: t('common.nav.home', 'Accueil') },
    { href: 'realisations.html', id: 'work', label: t('common.nav.realisations', 'Réalisations') },
    { href: 'apropos.html', id: 'about', label: t('common.nav.about', 'À propos') },
    { href: 'contact.html', id: 'contact', label: t('common.nav.contact', 'Contact') },
  ];
  return (
    <>
      <header className={"site" + (scrolled ? " scrolled" : "")}>
        <div className="container nav-inner">
          <a href="index.html" className="brand" aria-label="YouOnline">
            <img src="assets/logo-full.png" alt="YouOnline" style={{ height: 40, width: 'auto' }} />
          </a>
          <nav className="nav-links" aria-label="Navigation principale">
            <a href="index.html" className={currentPage === 'home' ? 'active' : ''}>{t('common.nav.home', 'Accueil')}</a>
            <div className="nav-dropdown" ref={dropRef} style={{ position: 'relative' }}>
              <button onClick={() => setDropOpen(v => !v)} className={'nav-drop-btn' + (isServices ? ' active' : '')} style={{ padding: '10px 16px', borderRadius: 999, fontSize: 14, fontWeight: 500, color: isServices ? 'var(--bg)' : 'var(--ink-2)', background: isServices ? 'var(--ink)' : 'transparent', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'inherit', transition: 'all .25s' }}>
                {t('common.nav.services', 'Services')}
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" style={{ transition: 'transform .25s', transform: dropOpen ? 'rotate(180deg)' : 'none' }}><polyline points="6 9 12 15 18 9"/></svg>
              </button>
              {dropOpen && (
                <div className="nav-drop-menu" style={{ position: 'absolute', top: 'calc(100% + 8px)', left: '50%', transform: 'translateX(-50%)', background: 'var(--card)', border: '1px solid var(--line)', borderRadius: 16, padding: 8, minWidth: 280, boxShadow: '0 16px 40px -10px rgba(14,17,22,0.2)', zIndex: 100, animation: 'fadeInDown .2s ease' }}>
                  {servicesItems.map(s => (
                    <a key={s.id} href={s.href} style={{ display: 'flex', flexDirection: 'column', padding: '12px 16px', borderRadius: 10, textDecoration: 'none', transition: 'background .2s', color: 'var(--ink)' }} onMouseOver={e => e.currentTarget.style.background='var(--bg-2)'} onMouseOut={e => e.currentTarget.style.background='transparent'}>
                      <span style={{ fontWeight: 600, fontSize: 14 }}>{s.label}</span>
                      <span style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{s.desc}</span>
                    </a>
                  ))}
                </div>
              )}
            </div>
            {links.slice(1).map(l => <a key={l.id} href={l.href} className={currentPage === l.id ? 'active' : ''}>{l.label}</a>)}
          </nav>
          <div className="nav-right">
            <a href="/client/" className="btn ghost">{t('common.nav.client_area', 'Espace client')}</a>
            <a href="contact.html" className="btn accent">{t('common.nav.cta', 'Devis gratuit')}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
            <button className="menu-toggle" onClick={() => setMenuOpen(true)} aria-label={t('common.nav.home', 'Ouvrir le menu')}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
            </button>
          </div>
        </div>
      </header>
      <div className={"mobile-menu" + (menuOpen ? " open" : "")}>
        <button className="a11y-close" onClick={() => setMenuOpen(false)} style={{ position: 'absolute', top: 24, right: 24, width: 44, height: 44 }}><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
        <a href="index.html" onClick={() => setMenuOpen(false)}>{t('common.nav.home', 'Accueil')}</a>
        <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', padding: '16px 0 4px' }}>{t('common.nav.services', 'Services')}</span>
        {servicesItems.map(s => <a key={s.id} href={s.href} onClick={() => setMenuOpen(false)}>{s.label}</a>)}
        <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', padding: '16px 0 4px' }}>&nbsp;</span>
        {links.slice(1).map(l => <a key={l.id} href={l.href} onClick={() => setMenuOpen(false)}>{l.label}</a>)}
      </div>
    </>
  );
}

function Footer() {
  const t = useI18n();
  return (
    <footer className="site">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <a href="index.html" className="brand" aria-label="YouOnline" style={{ marginBottom: 20, display: 'block' }}>
              <img src="assets/logo-full.png" alt="YouOnline" style={{ height: 44, width: 'auto' }} />
            </a>
            <p>{t('common.footer.tagline', 'Agence web indépendante à Fuveau. Je crée, héberge et maintiens des sites web pour les entrepreneurs et TPE d\'Aix-en-Provence et partout en France.')}</p>
            <div style={{ marginTop: 24, display: 'flex', gap: 10 }}>
              <a href="https://www.facebook.com/YouOnlineFr" target="_blank" rel="noopener" style={{ padding: '8px 14px', borderRadius: 999, border: '1px solid var(--line)', fontSize: 13 }}>Facebook</a>
              <a href="https://www.linkedin.com/in/yann-goguet-8a37b52b/" target="_blank" rel="noopener" style={{ padding: '8px 14px', borderRadius: 999, border: '1px solid var(--line)', fontSize: 13 }}>LinkedIn</a>
            </div>
          </div>
          <div className="footer-col">
            <h4>{t('common.footer.col_services_title', 'Services')}</h4>
            <ul>
              <li><a href="sites.html">{t('common.footer.col_services_creation', 'Création de sites')}</a></li>
              <li><a href="hebergement.html">{t('common.footer.col_services_hebergement', 'Hébergement')}</a></li>
              <li><a href="#">{t('common.footer.col_services_maintenance', 'Maintenance')}</a></li>
              <li><a href="#">{t('common.footer.col_services_seo', 'Référencement SEO')}</a></li>
              <li><a href="#">{t('common.footer.col_services_domaines', 'Noms de domaine')}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t('common.footer.col_agency_title', "L'agence")}</h4>
            <ul>
              <li><a href="apropos.html">{t('common.footer.col_agency_about', 'À propos')}</a></li>
              <li><a href="realisations.html">{t('common.footer.col_agency_realisations', 'Réalisations')}</a></li>
              <li><a href="blog.html">{t('common.footer.col_agency_blog', 'Blog')}</a></li>
              <li><a href="#">{t('common.footer.col_agency_parrainage', 'Parrainage')}</a></li>
              <li><a href="contact.html">{t('common.footer.col_agency_contact', 'Contact')}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t('common.footer.col_contact_title', 'Contact')}</h4>
            <ul>
              <li>{t('common.footer.col_contact_city', 'Fuveau, 13710')}</li>
              <li>{t('common.footer.col_contact_region', 'Aix-en-Provence')}</li>
              <li><a href="tel:+33624997171">06 24 99 71 71</a></li>
              <li><a href="mailto:contact@youonline.fr">contact@youonline.fr</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>{t('common.footer.copyright', '© 2012–2026 YouOnline · Yann, votre artisan du web')}</div>
          <div className="footer-bottom-right">
            <div className="footer-legal">
              <a href="mentions.html">{t('common.footer.legal_mentions', 'Mentions légales')}</a>
              <a href="confidentialite.html">{t('common.footer.legal_confidentialite', 'Confidentialité')}</a>
              <a href="conditions.html">{t('common.footer.legal_cgv', 'CGV')}</a>
            </div>
            <LangSwitcher variant="footer" />
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ============ CURSOR ============ */
function CustomCursor() {
  useEffectS(() => {
    if (matchMedia('(pointer: coarse)').matches) return;
    const dot = document.createElement('div'); dot.className = 'cursor'; document.body.appendChild(dot);
    const ring = document.createElement('div'); ring.className = 'cursor-ring'; document.body.appendChild(ring);
    let mx = 0, my = 0, rx = 0, ry = 0;
    const onMove = e => { mx = e.clientX; my = e.clientY; dot.style.transform = `translate(${mx}px, ${my}px) translate(-50%,-50%)`;
      const guide = document.getElementById('reading-guide');
      if (guide && document.documentElement.getAttribute('data-a11y-guide') === 'true') {
        guide.style.top = (my - 40) + 'px';
      }
    };
    const onOver = e => { if (e.target.closest('a, button, .service-card, .work-card, .testi-card, .post, .plan')) ring.classList.add('hover'); };
    const onOut = e => { if (e.target.closest('a, button, .service-card, .work-card, .testi-card, .post, .plan')) ring.classList.remove('hover'); };
    const loop = () => {
      rx += (mx - rx) * 0.15; ry += (my - ry) * 0.15;
      ring.style.transform = `translate(${rx}px, ${ry}px) translate(-50%,-50%)`;
      requestAnimationFrame(loop);
    };
    window.addEventListener('mousemove', onMove);
    document.addEventListener('mouseover', onOver);
    document.addEventListener('mouseout', onOut);
    loop();
    return () => { dot.remove(); ring.remove(); window.removeEventListener('mousemove', onMove); document.removeEventListener('mouseover', onOver); document.removeEventListener('mouseout', onOut); };
  }, []);
  return null;
}

/* ============ REVEAL ============ */
function useReveal() {
  useEffectS(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.1 });
    els.forEach(e => io.observe(e));
    return () => io.disconnect();
  });
  return null;
}

/* ============ CHATBOT IA ============ */
function ChatBot() {
  const t = useI18n();
  const [open, setOpen] = useStateS(false);
  const [messages, setMessages] = useStateS([
    { role: 'assistant', text: t('common.chatbot.initial_message', "Bonjour ! Je suis l'assistant IA de YouOnline. Comment puis-je vous aider aujourd'hui ? Création de site, hébergement, maintenance, nom de domaine... je suis là pour vous conseiller !") }
  ]);
  const [input, setInput] = useStateS('');
  const [typing, setTyping] = useStateS(false);
  const [notif, setNotif] = useStateS(false);
  const [notifDismissed, setNotifDismissed] = useStateS(false);
  const logsRef = useRefS(null);

  // Update welcome message when language changes
  useEffectS(() => {
    const welcomeText = t('common.chatbot.initial_message', "Bonjour ! Je suis l'assistant IA de YouOnline. Comment puis-je vous aider aujourd'hui ?");
    setMessages(prev => {
      if (prev.length >= 1 && prev[0].role === 'assistant') {
        return [{ role: 'assistant', text: welcomeText }, ...prev.slice(1)];
      }
      return prev;
    });
  }, [t('common.chatbot.initial_message')]);

  // Auto-show notification after 8s
  useEffectS(() => {
    const timer = setTimeout(() => { if (!open && !notifDismissed) setNotif(true); }, 8000);
    return () => clearTimeout(timer);
  }, []);

  // Auto-scroll
  useEffectS(() => {
    if (logsRef.current) logsRef.current.scrollTop = logsRef.current.scrollHeight;
  }, [messages, typing]);

  const dismiss = () => { setNotif(false); setNotifDismissed(true); };
  const openChat = () => { dismiss(); setOpen(true); };
  const closeChat = () => setOpen(false);

  const formatMsg = (text) => text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
    .replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener" style="color:#eb9222;">$1</a>');

  // Detect current language for API
  const getLang = () => { try { return localStorage.getItem('yo-lang') || 'fr'; } catch(e) { return 'fr'; } };

  const send = async (e) => {
    e.preventDefault();
    const q = input.trim();
    if (!q || typing) return;
    setInput('');
    const newMsgs = [...messages, { role: 'user', text: q }];
    setMessages(newMsgs);
    setTyping(true);
    try {
      const history = newMsgs.slice(0, -1).map(m => ({ role: m.role === 'assistant' ? 'assistant' : 'user', content: m.text }));
      const res = await fetch('/chatbot-api.php', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'send_message', message: q, history, lang: getLang() })
      });
      const json = await res.json();
      if (json.success) {
        setMessages(prev => [...prev, { role: 'assistant', text: json.message }]);
      } else {
        setMessages(prev => [...prev, { role: 'assistant', text: t('common.chatbot.error_generic', "Désolé, une erreur est survenue. N'hésitez pas à nous contacter au 06 24 99 71 71.") }]);
      }
    } catch {
      setMessages(prev => [...prev, { role: 'assistant', text: t('common.chatbot.error_network', "Erreur de connexion. Vous pouvez nous joindre au 06 24 99 71 71 ou par email à contact@youonline.fr.") }]);
    }
    setTyping(false);
  };

  const avatarStyle = { width: 28, height: 28, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 };
  const bubbleBase = { padding: '10px 14px', maxWidth: '80%', fontSize: 14, lineHeight: 1.5, borderRadius: 14 };

  return (
    <>
      {/* Notification */}
      {notif && (
        <div onClick={openChat} style={{ position: 'fixed', bottom: 108, right: 30, zIndex: 9999, maxWidth: 280, cursor: 'pointer', animation: 'fadeInUp .4s ease' }}>
          <div style={{ background: '#fff', borderRadius: 14, padding: '14px 18px', boxShadow: '0 8px 32px rgba(0,0,0,0.12)', borderLeft: '4px solid #eb9222', position: 'relative' }}>
            <button onClick={e => { e.stopPropagation(); dismiss(); }} style={{ position: 'absolute', top: 6, right: 10, background: 'none', border: 'none', color: '#999', cursor: 'pointer', fontSize: 16 }}>&times;</button>
            <p style={{ margin: 0, fontSize: 14, color: '#1a1c2e', lineHeight: 1.45 }}><strong style={{ color: '#eb9222' }}>{t('common.chatbot.notif_greeting', 'Bonjour !')}</strong> {t('common.chatbot.notif_body', "Besoin d'aide pour votre projet web ?")}</p>
          </div>
          <div style={{ width: 0, height: 0, borderLeft: '10px solid transparent', borderRight: '10px solid transparent', borderTop: '10px solid #fff', marginLeft: 'auto', marginRight: 28 }} />
        </div>
      )}

      {/* FAB */}
      {!open && (
        <button onClick={openChat} aria-label={t('common.chatbot.open_label', 'Ouvrir le chat')} style={{ position: 'fixed', bottom: 30, right: 30, width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg, #407696, #2d5a73)', color: '#fff', border: 'none', cursor: 'pointer', boxShadow: '0 4px 20px rgba(64,118,150,0.35)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'transform .3s', fontSize: 24 }} onMouseOver={e => e.currentTarget.style.transform='scale(1.08)'} onMouseOut={e => e.currentTarget.style.transform='scale(1)'}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
          {notif && <span style={{ position: 'absolute', top: -2, right: -2, width: 14, height: 14, background: '#eb9222', borderRadius: '50%', border: '2px solid #fff' }} />}
        </button>
      )}

      {/* Chat Box */}
      {open && (
        <div style={{ position: 'fixed', right: 30, bottom: 30, width: 380, maxWidth: '90vw', maxHeight: 520, borderRadius: 16, boxShadow: '0 8px 40px rgba(0,0,0,0.15)', zIndex: 1000, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: '#fff', animation: 'fadeInUp .25s ease' }}>
          {/* Header */}
          <div style={{ background: 'linear-gradient(135deg, #1a2a3a, #407696)', height: 56, borderRadius: '16px 16px 0 0', color: '#fff', fontSize: 15, fontWeight: 600, padding: '0 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, background: '#1cc88a', borderRadius: '50%' }} />
              {t('common.chatbot.header_title', 'Assistant YouOnline')}
            </div>
            <button onClick={closeChat} style={{ background: 'none', border: 'none', color: '#fff', cursor: 'pointer', fontSize: 20, padding: 4 }}>&times;</button>
          </div>

          {/* Messages */}
          <div ref={logsRef} style={{ flex: 1, padding: 16, overflowY: 'auto', background: '#f8f9fc', maxHeight: 360 }}>
            {messages.map((m, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 12, flexDirection: m.role === 'user' ? 'row-reverse' : 'row', alignItems: 'flex-end' }}>
                <img src={m.role === 'user' ? '/assets/img/users/default.jpg' : '/assets/img/users/1.jpg'} alt="" style={avatarStyle} />
                <div style={{ ...bubbleBase, background: m.role === 'user' ? 'linear-gradient(135deg, #407696, #2d5a73)' : '#fff', color: m.role === 'user' ? '#fff' : '#333', border: m.role === 'user' ? 'none' : '1px solid #eef1f5', borderRadius: m.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }} dangerouslySetInnerHTML={{ __html: formatMsg(m.text) }} />
              </div>
            ))}
            {typing && (
              <div style={{ display: 'flex', gap: 8, marginBottom: 12, alignItems: 'flex-end' }}>
                <img src="/assets/img/users/1.jpg" alt="" style={avatarStyle} />
                <div style={{ ...bubbleBase, background: '#fff', border: '1px solid #eef1f5', borderRadius: '14px 14px 14px 4px', color: '#999', letterSpacing: 2 }}>...</div>
              </div>
            )}
          </div>

          {/* Input */}
          <form onSubmit={send} style={{ display: 'flex', borderTop: '1px solid #eef1f5' }}>
            <input value={input} onChange={e => setInput(e.target.value)} placeholder={t('common.chatbot.input_placeholder', 'Posez votre question...')} style={{ flex: 1, padding: '14px 16px', border: 'none', outline: 'none', fontSize: 14, fontFamily: 'inherit', borderRadius: '0 0 0 16px' }} />
            <button type="submit" style={{ background: 'none', border: 'none', color: '#407696', padding: '0 16px', cursor: 'pointer', fontSize: 18, borderRadius: '0 0 16px 0' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
            </button>
          </form>
        </div>
      )}
    </>
  );
}

Object.assign(window, { Header, Footer, CustomCursor, useReveal, LangSwitcher, ChatBot });
