// shared.jsx — composants partagés à toutes les pages
const { useState, useEffect, useRef } = React;

function Logo({ size = 30 }) {
  return (
    <a href="/index.html" className="logo">
      <span className="logo-mark" style={{ width: size, height: size }}>
        <span>2C</span>
      </span>
      <span>2C ITECH</span>
    </a>
  );
}

function UrgenceBar({ level = "high" }) {
  const [time, setTime] = useState(getCountdown());
  useEffect(() => {
    const t = setInterval(() => setTime(getCountdown()), 1000);
    return () => clearInterval(t);
  }, []);
  if (level === "off") return null;
  const messageByLevel = {
    high: "Facturation électronique obligatoire — entrée en vigueur",
    medium: "Échéance facturation électronique 2026",
    low: "Préparez votre passage à la facturation électronique",
  };
  return (
    <div className={`urgence-bar ${level === "high" ? "high" : ""}`}>
      <div className="urgence-inner">
        <span className="pulse" />
        <strong style={{ fontWeight: 600 }}>{messageByLevel[level]}</strong>
        {level !== "low" && (
          <span style={{ opacity: 0.85 }}>— diagnostic gratuit avant la fin du mois</span>
        )}
        <div className="urgence-countdown">
          <b>{time.d}j</b>
          <b>{time.h}h</b>
          <b>{time.m}m</b>
          {level === "high" && <b>{time.s}s</b>}
        </div>
      </div>
    </div>
  );
}

function getCountdown() {
  const target = new Date("2026-09-01T00:00:00").getTime();
  const now = Date.now();
  const diff = Math.max(0, target - now);
  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
  const m = Math.floor((diff / (1000 * 60)) % 60);
  const s = Math.floor((diff / 1000) % 60);
  return {
    d: String(d).padStart(3, "0"),
    h: String(h).padStart(2, "0"),
    m: String(m).padStart(2, "0"),
    s: String(s).padStart(2, "0"),
  };
}

function Header({ active = "home" }) {
  return (
    <header className="site-header">
      <div className="header-inner">
        <Logo />
        <nav className="nav">
          <a href="/index.html" className={active === "home" ? "active" : ""}>Accueil</a>
          <a href="/services.html" className={active === "services" ? "active" : ""}>Services</a>
          <a href="/rendez-vous.html" className={active === "rdv" ? "active" : ""}>Rendez-vous</a>
          <a href="/contact.html" className={active === "contact" ? "active" : ""}>Contact</a>
        </nav>
        <div className="header-cta">
          <a href="tel:+33500000000" className="header-phone">
            <PhoneIcon /> 05 00 00 00 00
          </a>
          <a href="/rendez-vous.html" className="btn btn-primary" style={{ padding: "10px 18px", fontSize: 14 }}>
            Prendre RDV <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </header>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="footer-inner">
        <div>
          <Logo />
          <p style={{ fontSize: 14, lineHeight: 1.6, marginTop: 16, color: "rgba(255,255,255,0.65)", maxWidth: 320 }}>
            Ingénieur informatique indépendant. Mise en conformité, automatisation et IA pour TPE/PME du Lot.
          </p>
          <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
            <a href="tel:+33500000000" className="footer-action"><PhoneIcon /> Appeler</a>
            <a href="https://wa.me/33000000000" className="footer-action"><WhatsAppIcon /> WhatsApp</a>
          </div>
        </div>
        <div>
          <h4>Services</h4>
          <ul>
            <li><a href="/services.html#conformite">Facturation 2026</a></li>
            <li><a href="/services.html#ia">Automatisation / IA</a></li>
            <li><a href="/services.html#depannage">Dépannage</a></li>
            <li><a href="/services.html#maintenance">Maintenance</a></li>
            <li><a href="/services.html#sauvegarde">Sauvegarde</a></li>
          </ul>
        </div>
        <div>
          <h4>Société</h4>
          <ul>
            <li><a href="/contact.html">Contact</a></li>
            <li><a href="/rendez-vous.html">Rendez-vous</a></li>
            <li><a href="/mentions-legales.html">Mentions légales</a></li>
            <li><a href="/confidentialite.html">Confidentialité</a></li>
          </ul>
        </div>
        <div>
          <h4>Zone d'intervention</h4>
          <ul>
            <li>Bretenoux (46130)</li>
            <li>Saint-Céré (46400)</li>
            <li>Vallée de la Dordogne</li>
            <li>Télé-assistance France</li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 2C ITECH — SIRET 000 000 000 00000</span>
        <span className="mono">Hostinger · Made in Lot 🌰</span>
      </div>
      <style>{`
        .footer-action {
          display: inline-flex; align-items: center; gap: 6px;
          padding: 8px 14px; border-radius: 999px;
          background: rgba(255,255,255,0.08);
          color: white; font-size: 13px; font-weight: 500;
        }
        .footer-action:hover { background: var(--accent); color: white; }
      `}</style>
    </footer>
  );
}

function ClientLogos() {
  const logos = [
    { name: "Boulangerie Lacaze", style: "serif" },
    { name: "GARAGE DUPONT", style: "stencil" },
    { name: "Cabinet Vidal & Associés", style: "thin" },
    { name: "MAÇONNERIE 46", style: "bold" },
    { name: "Domaine de Cère", style: "italic" },
    { name: "AUTO-ECOLE PUYBRUN", style: "condensed" },
  ];
  return (
    <div className="client-logos">
      {logos.map((l, i) => (
        <div key={i} className={`cl cl-${l.style}`}>{l.name}</div>
      ))}
      <style>{`
        .client-logos { display: grid; grid-template-columns: repeat(6, 1fr); gap: 32px; align-items: center; }
        @media (max-width: 820px) { .client-logos { grid-template-columns: repeat(3, 1fr); gap: 24px; } }
        .cl { opacity: 0.55; color: var(--ink); text-align: center; font-size: 14px; transition: opacity .2s; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .cl:hover { opacity: 1; }
        .cl-serif { font-family: var(--font-serif); font-size: 18px; font-style: italic; }
        .cl-stencil { font-family: var(--font-mono); font-weight: 700; letter-spacing: 0.15em; font-size: 12px; }
        .cl-thin { font-weight: 300; letter-spacing: 0.02em; }
        .cl-bold { font-weight: 800; letter-spacing: 0.06em; font-size: 13px; }
        .cl-italic { font-style: italic; font-family: var(--font-serif); font-size: 17px; }
        .cl-condensed { font-weight: 700; letter-spacing: 0.08em; font-size: 12px; }
      `}</style>
    </div>
  );
}

function ChatBubble() {
  const [open, setOpen] = useState(false);
  const [autoOpened, setAutoOpened] = useState(false);
  const [messages, setMessages] = useState([
    { role: "ai", text: "Bonjour 👋 Je suis l'assistant 2C ITECH. Quel est votre besoin ?" },
    { role: "ai", text: "Vous pouvez me parler librement, ou choisir une option ci-dessous.", chips: ["Facturation 2026", "Mon PC est lent", "Automatiser ma facturation", "Parler à un humain"] },
  ]);
  const [input, setInput] = useState("");
  const [typing, setTyping] = useState(false);
  const bodyRef = useRef(null);

  useEffect(() => {
    const onScroll = () => {
      if (autoOpened) return;
      if (window.scrollY > 600) { setOpen(true); setAutoOpened(true); }
    };
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, [autoOpened]);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing]);

  const send = (text) => {
    if (!text.trim()) return;
    setMessages(m => [...m, { role: "user", text }]);
    setInput("");
    setTyping(true);
    setTimeout(() => {
      const reply = scriptedReply(text);
      setTyping(false);
      setMessages(m => [...m, reply]);
    }, 900);
  };

  return (
    <div className={`chat-fab ${open ? "open" : ""}`}>
      {!open && (
        <button className="chat-toggle" onClick={() => setOpen(true)}>
          <ChatIcon /><span>Une question ?</span><span className="chat-dot" />
        </button>
      )}
      {open && (
        <div className="chat-window">
          <div className="chat-head">
            <div className="chat-avatar">2C</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Assistant 2C ITECH</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--success)" }} />
                Réponse en moins d'1 min
              </div>
            </div>
            <button className="chat-x" onClick={() => setOpen(false)} aria-label="Fermer">×</button>
          </div>
          <div className="chat-body" ref={bodyRef}>
            {messages.map((m, i) => (
              <div key={i} className={`bubble ${m.role}`}>
                <div className="bubble-text">{m.text}</div>
                {m.chips && (
                  <div className="bubble-chips">
                    {m.chips.map(c => <button key={c} onClick={() => send(c)}>{c}</button>)}
                  </div>
                )}
                {m.cta && (
                  <a href={m.cta.href} className="btn btn-primary" style={{ marginTop: 8, padding: "10px 16px", fontSize: 13 }}>
                    {m.cta.label} <span className="arrow">→</span>
                  </a>
                )}
              </div>
            ))}
            {typing && (
              <div className="bubble ai">
                <div className="bubble-text typing"><span /><span /><span /></div>
              </div>
            )}
          </div>
          <form className="chat-input" onSubmit={e => { e.preventDefault(); send(input); }}>
            <input value={input} onChange={e => setInput(e.target.value)} placeholder="Posez votre question…" />
            <button type="submit" aria-label="Envoyer"><SendIcon /></button>
          </form>
        </div>
      )}
      <style>{`
        .chat-fab { position: fixed; right: 24px; bottom: 24px; z-index: 40; font-family: var(--font-sans); }
        .chat-toggle { display: inline-flex; align-items: center; gap: 10px; padding: 14px 20px; border-radius: 999px; background: var(--bg-deep); color: white; border: 0; box-shadow: var(--shadow-lg); font-weight: 500; font-size: 14px; position: relative; }
        .chat-toggle:hover { background: var(--bg-deep-2); }
        .chat-dot { position: absolute; top: 8px; right: 12px; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); animation: pulse 1.8s infinite; }
        .chat-window { width: 380px; max-width: calc(100vw - 32px); height: 540px; max-height: calc(100vh - 80px); background: var(--bg-elev); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); border: 1px solid var(--line); display: flex; flex-direction: column; overflow: hidden; animation: chat-in .25s ease; }
        @keyframes chat-in { from { opacity: 0; transform: translateY(20px) scale(0.96); } }
        .chat-head { display: flex; align-items: center; gap: 12px; padding: 14px; border-bottom: 1px solid var(--line); }
        .chat-avatar { width: 36px; height: 36px; border-radius: 10px; background: var(--bg-deep); color: white; display: grid; place-items: center; font-weight: 600; font-family: var(--font-serif); font-size: 16px; }
        .chat-x { margin-left: auto; background: transparent; border: 0; font-size: 24px; color: var(--ink-3); width: 32px; height: 32px; border-radius: 8px; }
        .chat-x:hover { background: var(--line); color: var(--ink); }
        .chat-body { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 10px; background: var(--bg); }
        .bubble { max-width: 85%; }
        .bubble.ai { align-self: flex-start; }
        .bubble.user { align-self: flex-end; }
        .bubble-text { padding: 10px 14px; border-radius: 16px; font-size: 14px; line-height: 1.45; }
        .bubble.ai .bubble-text { background: var(--bg-elev); color: var(--ink); border: 1px solid var(--line); border-bottom-left-radius: 4px; }
        .bubble.user .bubble-text { background: var(--bg-deep); color: white; border-bottom-right-radius: 4px; }
        .bubble-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
        .bubble-chips button { background: transparent; border: 1px solid var(--line-strong); padding: 6px 11px; border-radius: 999px; font-size: 12px; color: var(--ink-2); }
        .bubble-chips button:hover { background: var(--bg-deep); color: white; border-color: var(--bg-deep); }
        .typing { display: inline-flex; gap: 4px; }
        .typing span { width: 6px; height: 6px; background: var(--ink-3); border-radius: 50%; animation: bounce 1.2s infinite; }
        .typing span:nth-child(2) { animation-delay: .15s; }
        .typing span:nth-child(3) { animation-delay: .3s; }
        @keyframes bounce { 0%, 60%, 100% { transform: translateY(0); opacity: .5; } 30% { transform: translateY(-4px); opacity: 1; } }
        .chat-input { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--line); background: var(--bg-elev); }
        .chat-input input { padding: 10px 12px; font-size: 14px; }
        .chat-input button { background: var(--accent); border: 0; color: white; width: 40px; border-radius: var(--radius); display: grid; place-items: center; }
        .chat-input button:hover { background: var(--accent-2); }
      `}</style>
    </div>
  );
}

function scriptedReply(input) {
  const lower = input.toLowerCase();
  if (/factur|conformit|2026/.test(lower)) {
    return { role: "ai", text: "La facturation électronique devient obligatoire en 2026. Je peux faire un diagnostic gratuit en 30 min pour évaluer votre logiciel et votre cycle de facturation.", cta: { label: "Réserver un diagnostic", href: "/rendez-vous.html?besoin=facturation" } };
  }
  if (/lent|bug|panne|virus|écran|imprimante|wifi|internet/.test(lower)) {
    return { role: "ai", text: "C'est probablement réparable rapidement. Pour un dépannage simple, je peux intervenir sous 24h (60€/h, devis avant intervention). Voulez-vous décrire le problème ?", chips: ["Décrire mon problème", "Demander un dépannage"] };
  }
  if (/automat|ia|gain|temps|relance|devis/.test(lower)) {
    return { role: "ai", text: "L'automatisation peut faire gagner 5h+ par semaine sur les tâches répétitives. On en parle ?", cta: { label: "Voir le Pack Automatisation", href: "/services.html#ia" } };
  }
  if (/humain|appeler|téléphone|parler/.test(lower)) {
    return { role: "ai", text: "Bien sûr. Vous pouvez m'appeler directement au 05 00 00 00 00, ou je vous rappelle dans la journée si vous laissez votre numéro.", chips: ["Me faire rappeler"] };
  }
  return { role: "ai", text: "Je note votre demande. Le plus simple est de réserver 15 min avec moi — c'est gratuit et sans engagement.", cta: { label: "Réserver 15 min", href: "/rendez-vous.html" } };
}

function PhoneIcon() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z"/></svg>; }
function WhatsAppIcon() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.6 6.32A7.85 7.85 0 0012.05 4a7.94 7.94 0 00-6.88 11.9L4 20l4.21-1.1a7.93 7.93 0 003.79.96h.01a7.94 7.94 0 005.59-13.54zM12.05 18.5h-.01a6.6 6.6 0 01-3.36-.92l-.24-.14-2.5.66.67-2.43-.16-.25a6.59 6.59 0 0110.21-8.13 6.55 6.55 0 011.93 4.66 6.6 6.6 0 01-6.54 6.55zm3.6-4.93c-.2-.1-1.16-.57-1.34-.64-.18-.07-.31-.1-.44.1s-.5.64-.62.78c-.11.13-.23.15-.43.05-.2-.1-.83-.31-1.59-.98-.59-.52-.98-1.17-1.1-1.37-.11-.2-.01-.31.09-.41.09-.09.2-.23.3-.35.1-.11.13-.2.2-.33.07-.13.03-.25-.02-.35-.05-.1-.44-1.07-.61-1.46-.16-.39-.32-.33-.44-.34h-.38c-.13 0-.34.05-.52.25s-.69.67-.69 1.65.71 1.91.81 2.05c.1.13 1.4 2.13 3.39 2.99.47.2.84.32 1.13.41.47.15.9.13 1.24.08.38-.06 1.16-.47 1.32-.93.16-.46.16-.85.11-.93-.05-.08-.18-.13-.38-.23z"/></svg>; }
function ChatIcon() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>; }
function SendIcon() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>; }

Object.assign(window, { Logo, Header, Footer, UrgenceBar, ChatBubble, ClientLogos, PhoneIcon, WhatsAppIcon, ChatIcon, SendIcon });
