/* ============================================
   ELYSSA CALL · Composants partagés
   Nav + Footer + WhatsApp FAB + ChatBot IA
   ============================================ */
const { useState, useEffect, useRef } = React;

const _sub = window.location.pathname.includes('/services/');
const _r = _sub ? '../' : '';

/* ─── LOGO ─── */
const Logo = ({ width = 160 }) => (
  <svg viewBox="0 0 360 80" width={width} height={Math.round(width*80/360)} aria-label="Elyssa Call">
    <defs>
      <linearGradient id="nfG" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" stopColor="#D4A843"/><stop offset="50%" stopColor="#F0C96A"/><stop offset="100%" stopColor="#B8891E"/>
      </linearGradient>
      <linearGradient id="nfT" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" stopColor="#2AADA0"/><stop offset="100%" stopColor="#1A7A70"/>
      </linearGradient>
    </defs>
    <g transform="translate(4,12)">
      <rect x="2" y="30" width="4" height="22" rx="1" fill="white"/>
      <rect x="23" y="30" width="4" height="22" rx="1" fill="white"/>
      <path d="M2,30 A11,11 0 0,1 27,30" fill="none" stroke="white" strokeWidth="4" strokeLinecap="round"/>
      <rect x="1" y="50" width="27" height="2.5" rx="1" fill="white"/>
      <rect x="32" y="24" width="4.5" height="28" rx="1" fill="url(#nfG)"/>
      <rect x="55" y="24" width="4.5" height="28" rx="1" fill="url(#nfG)"/>
      <path d="M32,24 A12,12 0 0,1 59.5,24" fill="none" stroke="url(#nfG)" strokeWidth="4.5" strokeLinecap="round"/>
      <rect x="31" y="50" width="29.5" height="2.5" rx="1" fill="url(#nfG)"/>
      <rect x="65" y="30" width="4" height="22" rx="1" fill="url(#nfT)"/>
      <rect x="86" y="30" width="4" height="22" rx="1" fill="url(#nfT)"/>
      <path d="M65,30 A11,11 0 0,1 90,30" fill="none" stroke="url(#nfT)" strokeWidth="4" strokeLinecap="round"/>
      <rect x="64" y="50" width="27" height="2.5" rx="1" fill="url(#nfT)"/>
    </g>
    <rect x="104" y="20" width="1" height="40" rx="0.5" fill="white" opacity="0.2"/>
    <text x="118" y="42" fontFamily="'Cormorant Garamond',Georgia,serif" fontSize="26" fontWeight="700" letterSpacing="3" fill="white">ELYSSA</text>
    <text x="120" y="62" fontFamily="'Outfit',sans-serif" fontSize="11" fontWeight="300" letterSpacing="7" fill="white">CALL</text>
    <rect x="120" y="65" width="90" height="1" rx="0.5" fill="url(#nfG)" opacity="0.7"/>
  </svg>
);

/* ─── NAV ─── */
const Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  const links = [
    { href:`${_r}index.html#services`, label:'Services' },
    { href:`${_r}index.html#ia`, label:'IA & Formations' },
    { href:`${_r}index.html#methode`, label:'Méthode' },
    { href:`${_r}index.html#pourquoi`, label:'Pourquoi nous' },
    { href:`${_r}contact.html`, label:'Contact' },
  ];
  return (
    <header className={`nav${scrolled?' scrolled':''}`}>
      <div className="nav-inner">
        <a href={`${_r}index.html`} className="nav-logo"><Logo width={148}/></a>
        <nav className={`nav-links${open?' open':''}`}>
          {links.map((l,i) => <a key={i} href={l.href} onClick={()=>setOpen(false)}>{l.label}</a>)}
          <div className="nav-social">
            
            <a href="https://wa.me/33646185454" target="_blank" rel="noopener" className="nav-social-link wa" aria-label="WhatsApp">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.47 14.38c-.3-.15-1.77-.88-2.05-.98-.28-.1-.48-.15-.68.15-.2.3-.78.98-.96 1.18-.18.2-.35.23-.65.08-.3-.15-1.27-.47-2.42-1.5-.9-.8-1.5-1.78-1.67-2.08-.17-.3-.02-.46.13-.61.14-.13.3-.35.45-.53.15-.18.2-.3.3-.5.1-.2.05-.38-.02-.53-.08-.15-.68-1.63-.92-2.23-.24-.58-.49-.5-.68-.51-.18-.01-.38-.01-.58-.01-.2 0-.53.08-.8.38s-1.05 1.03-1.05 2.5 1.08 2.9 1.23 3.1c.15.2 2.12 3.24 5.14 4.54.72.31 1.28.5 1.71.63.72.23 1.37.2 1.89.12.58-.09 1.77-.72 2.02-1.42.25-.7.25-1.29.17-1.42-.08-.12-.28-.2-.58-.35zM12.05 21.8A9.7 9.7 0 016.6 20L3 21l1.02-3.5A9.74 9.74 0 1112.05 21.8z"/></svg>
            </a>
          </div>
          <a href={`${_r}index.html#contact`} className="cta" onClick={()=>setOpen(false)}>Devis gratuit →</a>
        </nav>
        <button className="burger" onClick={()=>setOpen(o=>!o)} aria-label="Menu">
          <span style={open?{transform:'rotate(45deg) translate(5px,5px)'}:{}}/>
          <span style={open?{opacity:0}:{}}/>
          <span style={open?{transform:'rotate(-45deg) translate(5px,-5px)'}:{}}/>
        </button>
      </div>
    </header>
  );
};

/* ─── FOOTER ─── */
const Footer = () => (
  <footer className="footer">
    <div className="wrap footer-inner">
      <Logo width={120}/>
      <div className="footer-links">
        <a href={`${_r}mentions-legales.html`}>Mentions légales</a>
        <a href={`${_r}politique-confidentialite.html`}>Confidentialité</a>
        <a href={`${_r}cgv.html`}>CGV</a>
        <a href="mailto:contact@elyssa-call.com">contact@elyssa-call.com</a>
      </div>
      <div className="footer-social">
        
        <a href="https://wa.me/33646185454" target="_blank" rel="noopener" aria-label="WhatsApp">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.47 14.38c-.3-.15-1.77-.88-2.05-.98-.28-.1-.48-.15-.68.15-.2.3-.78.98-.96 1.18-.18.2-.35.23-.65.08-.3-.15-1.27-.47-2.42-1.5-.9-.8-1.5-1.78-1.67-2.08-.17-.3-.02-.46.13-.61.14-.13.3-.35.45-.53.15-.18.2-.3.3-.5.1-.2.05-.38-.02-.53-.08-.15-.68-1.63-.92-2.23-.24-.58-.49-.5-.68-.51-.18-.01-.38-.01-.58-.01-.2 0-.53.08-.8.38s-1.05 1.03-1.05 2.5 1.08 2.9 1.23 3.1c.15.2 2.12 3.24 5.14 4.54.72.31 1.28.5 1.71.63.72.23 1.37.2 1.89.12.58-.09 1.77-.72 2.02-1.42.25-.7.25-1.29.17-1.42-.08-.12-.28-.2-.58-.35zM12.05 21.8A9.7 9.7 0 016.6 20L3 21l1.02-3.5A9.74 9.74 0 1112.05 21.8z"/></svg>
        </a>
      </div>
      <div className="footer-copy">© {new Date().getFullYear()} Elyssa Call · Tunis, Tunisie</div>
    </div>
  </footer>
);

/* ─── WHATSAPP FAB ─── */
const WhatsAppFAB = () => (
  <a href="https://wa.me/33646185454" target="_blank" rel="noopener" className="wa-fab" aria-label="WhatsApp">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="white"><path d="M17.47 14.38c-.3-.15-1.77-.88-2.05-.98-.28-.1-.48-.15-.68.15-.2.3-.78.98-.96 1.18-.18.2-.35.23-.65.08-.3-.15-1.27-.47-2.42-1.5-.9-.8-1.5-1.78-1.67-2.08-.17-.3-.02-.46.13-.61.14-.13.3-.35.45-.53.15-.18.2-.3.3-.5.1-.2.05-.38-.02-.53-.08-.15-.68-1.63-.92-2.23-.24-.58-.49-.5-.68-.51-.18-.01-.38-.01-.58-.01-.2 0-.53.08-.8.38s-1.05 1.03-1.05 2.5 1.08 2.9 1.23 3.1c.15.2 2.12 3.24 5.14 4.54.72.31 1.28.5 1.71.63.72.23 1.37.2 1.89.12.58-.09 1.77-.72 2.02-1.42.25-.7.25-1.29.17-1.42-.08-.12-.28-.2-.58-.35zM12.05 21.8A9.7 9.7 0 016.6 20L3 21l1.02-3.5A9.74 9.74 0 1112.05 21.8z"/></svg>
    <span>WhatsApp</span>
  </a>
);

/* ─── CHATBOT IA ─── */
const SYSTEM_PROMPT = `Tu es l'assistant virtuel d'Elyssa Call, un centre d'externalisation B2B francophone basé à Tunis, Tunisie.
Tu aides les prospects à comprendre les services et à obtenir des devis. Réponds en français, de façon concise (max 3-4 phrases), chaleureuse et professionnelle.

SERVICES ET TARIFS :
• Conseillers Clientèle : support multicanal (téléphone, email, chat, WhatsApp), SAV, fidélisation. Dès 1 100€/mois/agent.
• Téléprospecteurs B2B : prospection sortante, prise de RDV qualifiés BANT. Dès 1 100€/mois/agent.
• Closers : closing high-ticket B2B, rémunération hybride fixe+variable. Dès 1 300€/mois.
• Data Scientists : lead scoring, modèles prédictifs, dashboards KPI. Sur devis.
• Formations IA : 6 programmes (ChatGPT, Python, Data Science, Marketing IA, RGPD) avec licence de commercialisation.
• Agents IA métier : 8 agents déployables en 2-4 semaines (Commercial, Service Client, Marketing, RH, Comptabilité, Analyste, Juridique, Formation).

AVANTAGES :
• Démarrage en 14 jours (72h pour les urgences)
• Devis personnalisé sous 24h, gratuit
• Économies jusqu'à -60% vs équipe interne
• 100% conforme RGPD, DPA systématique
• Collaborateurs bac+3 minimum, accent neutre francophone
• Même fuseau horaire que l'Europe (CET/CEST)
• Chef de projet dédié + reporting hebdomadaire
• Scalabilité : 1 à 50 agents en quelques semaines

MARCHÉS : France, Belgique, Suisse, Luxembourg

CONTACT : contact@elyssa-call.com | +33 6 46 18 54 54 | WhatsApp : +33 6 46 18 54 54

Pour les devis personnalisés, oriente vers le formulaire de contact ou directement par email/WhatsApp. Reste concis.`;

const QUICK_REPLIES = ['Quels sont vos tarifs ?','Délai de démarrage ?','Conformité RGPD ?','Comment ça marche ?'];

const ChatBot = () => {
  const [open, setOpen] = useState(false);
  const [msgs, setMsgs] = useState([{role:'assistant', content:'Bonjour 👋 Je suis l\'assistant IA d\'Elyssa Call. Posez-moi vos questions sur nos services, tarifs ou délais !'}]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [showQuick, setShowQuick] = useState(true);
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, loading]);

  const send = async (text) => {
    const txt = (text || input).trim();
    if (!txt || loading) return;
    setShowQuick(false);
    const next = [...msgs, {role:'user', content:txt}];
    setMsgs(next);
    setInput('');
    setLoading(true);
    try {
      if (window.claude) {
        const res = await window.claude.complete({ messages: next.map(m=>({role:m.role,content:m.content})), system: SYSTEM_PROMPT });
        setMsgs(prev => [...prev, {role:'assistant', content:res}]);
      } else {
        // Fallback statique
        await new Promise(r => setTimeout(r, 800));
        setMsgs(prev => [...prev, {role:'assistant', content:'Pour toute question sur nos services, contactez-nous directement : contact@elyssa-call.com ou WhatsApp : +33 6 46 18 54 54. Nous répondons sous 24h ! 😊'}]);
      }
    } catch {
      setMsgs(prev => [...prev, {role:'assistant', content:'Une erreur est survenue. Contactez-nous : contact@elyssa-call.com ou +33 6 46 18 54 54.'}]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="cb-wrap">
      {open && (
        <div className="cb-window">
          <div className="cb-header">
            <div className="cb-header-left">
              <div className="cb-avatar">🤖</div>
              <div>
                <div className="cb-name">Assistant Elyssa Call</div>
                <div className="cb-status"><span className="cb-dot"/>IA · Répond instantanément</div>
              </div>
            </div>
            <button className="cb-close" onClick={()=>setOpen(false)}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
            </button>
          </div>
          <div className="cb-msgs" ref={scrollRef}>
            {msgs.map((m,i) => <div key={i} className={`cb-msg cb-msg-${m.role}`}>{m.content}</div>)}
            {loading && <div className="cb-msg cb-msg-assistant"><div className="cb-typing"><span/><span/><span/></div></div>}
          </div>
          {showQuick && (
            <div className="cb-quick">
              {QUICK_REPLIES.map((q,i) => <button key={i} className="cb-chip" onClick={()=>send(q)}>{q}</button>)}
            </div>
          )}
          <form className="cb-input-row" onSubmit={e=>{e.preventDefault();send();}}>
            <input className="cb-input" type="text" placeholder="Votre question…" value={input} onChange={e=>setInput(e.target.value)} disabled={loading} autoComplete="off"/>
            <button className="cb-send" type="submit" disabled={loading||!input.trim()}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 8h12M8 3l6 5-6 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          </form>
        </div>
      )}
      <button className={`cb-fab${open?' cb-fab-open':''}`} onClick={()=>setOpen(o=>!o)} aria-label="Ouvrir le chat">
        {open
          ? <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 3l12 12M15 3L3 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
          : <><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/><circle cx="8.5" cy="11" r="1" fill="currentColor"/><circle cx="12" cy="11" r="1" fill="currentColor"/><circle cx="15.5" cy="11" r="1" fill="currentColor"/></svg><span>Discussion IA</span></>
        }
      </button>
    </div>
  );
};

/* ─── SERVICE NAV ─── */
const SERVICE_PAGES = [
  { id:'conseillers', label:'👥 Conseillers Clientèle', href:'conseillers-clientele.html' },
  { id:'teleprospecteurs', label:'📞 Téléprospecteurs B2B', href:'teleprospecteurs.html' },
  { id:'closers', label:'⭐ Closers', href:'closers.html' },
  { id:'data', label:'📊 Data Scientists', href:'data-scientists.html' },
  { id:'ia', label:'🤖 Formations & Agents IA', href:'formations-ia.html' },
];

const ServiceNav = ({ current }) => (
  <nav className="svc-subnav" aria-label="Navigation entre les services">
    <div className="wrap svc-subnav-inner">
      <span className="svc-subnav-back">
        <a href={`${_r}index.html#services`}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M9 2L4 7l5 5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Tous les services
        </a>
      </span>
      <div className="svc-subnav-pills">
        {SERVICE_PAGES.map(s => (
          <a
            key={s.id}
            href={s.href}
            className={`svc-subnav-pill${current === s.id ? ' active' : ''}`}
            aria-current={current === s.id ? 'page' : undefined}
          >{s.label}</a>
        ))}
      </div>
    </div>
  </nav>
);

Object.assign(window, { Logo, Nav, Footer, WhatsAppFAB, ChatBot, ServiceNav, SERVICE_PAGES });