// Arbre de conversation guidée
const FLOW = {
  start: {
    agent: "Bonjour 👋 Je suis Léa, ton assistante Discover Studio. Comment puis-je t'aider aujourd'hui ?",
    choices: [
      { label: "🌐 Je veux un site internet", next: "type_site" },
      { label: "💼 Je cherche une solution IT", next: "solution_it" },
      { label: "💰 Connaître les tarifs", next: "budget" },
      { label: "❓ Autre question", next: "autre" },
    ]
  },
  type_site: {
    agent: "Super ! Quel type de site t'intéresse ?",
    choices: [
      { label: "🏪 Site vitrine / présentation", next: "timeline" },
      { label: "🛒 Boutique e-commerce", next: "timeline" },
      { label: "📋 Application web sur mesure", next: "timeline" },
      { label: "📝 Blog / Portfolio", next: "timeline" },
    ]
  },
  solution_it: {
    agent: "Parfait ! De quel type de solution as-tu besoin ?",
    choices: [
      { label: "🔧 Maintenance & support", next: "timeline" },
      { label: "☁️ Hébergement & déploiement", next: "timeline" },
      { label: "🔐 Sécurité & audit", next: "timeline" },
      { label: "📊 Tableau de bord / CRM", next: "timeline" },
    ]
  },
  timeline: {
    agent: "Excellent choix ! C'est pour quand ton projet ?",
    choices: [
      { label: "⚡ Le plus vite possible", next: "budget" },
      { label: "📅 Dans 1 à 3 mois", next: "budget" },
      { label: "🗓️ Dans 3 à 6 mois", next: "budget" },
      { label: "🔍 Je suis en exploration", next: "budget" },
    ]
  },
  budget: {
    agent: "Quel est ton budget approximatif ?",
    choices: [],
    awaitInput: true
  },
  contact: {
    agent: "Merci pour ces infos ! 🎉 Un expert Discover Studio va te contacter sous 24h.\n\nservice@discover-studio.com\n📞 +49 17687564448\n\nÀ très bientôt !",
    choices: [],
    whatsapp: true
  },
  autre: {
    agent: "Pas de souci ! Pose ta question ci-dessous 👇 Je te réponds dans les plus brefs délais 😊",
    choices: []
  }
};

const STEPS = ["start", "type_site|solution_it|budget|autre", "timeline", "budget", "contact"];

function nowTime() {
  return new Date().toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
}

function ChatWidget() {
  const [open, setOpen]       = React.useState(false);
  const [input, setInput]     = React.useState("");
  const [messages, setMessages] = React.useState([]);
  const [typing, setTyping]   = React.useState(false);
  const [step, setStep]       = React.useState(0); // 0-4 progress
  const [currentNode, setCurrentNode] = React.useState("start");
  const bottomRef  = React.useRef(null);
  const inputRef   = React.useRef(null);
  const agentPhoto = "https://images.pexels.com/photos/8866777/pexels-photo-8866777.jpeg?auto=compress&cs=tinysrgb&w=120&h=120&fit=crop";
  const pathRef      = React.useRef(["start"]);
  const choicesRef   = React.useRef([]);
  const freeTextsRef = React.useRef([]);
  const savedRef     = React.useRef(false);

  async function saveChatSession(lastNode) {
    if (savedRef.current) return;
    savedRef.current = true;
    const sb = window.DiscoverSupabase && typeof window.DiscoverSupabase.getClient === "function"
      ? window.DiscoverSupabase.getClient() : null;
    if (!sb) return;
    try {
      await sb.from("chat_sessions").insert({
        conversation_path: pathRef.current.join(" → "),
        choices_made: choicesRef.current.join(", ") || null,
        last_node: lastNode,
        free_text: freeTextsRef.current.join(" | ") || null,
        page_path: window.location.pathname
      });
    } catch (_) { /* silent */ }
  }

  React.useEffect(() => {
    setMessages([{ from: "agent", text: FLOW.start.agent, choices: FLOW.start.choices, time: nowTime() }]);
  }, []);

  React.useEffect(() => {
    const t = setTimeout(() => setOpen(true), 15000);
    return () => clearTimeout(t);
  }, []);

  React.useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, open, typing]);

  React.useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  function agentReply(nextStep) {
    const node = FLOW[nextStep];
    if (!node) return;
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setCurrentNode(nextStep);
      setMessages(prev => [...prev, { from: "agent", text: node.agent, choices: node.choices, whatsapp: !!node.whatsapp, time: nowTime() }]);
      if (node.awaitInput && inputRef.current) inputRef.current.focus();
    }, 850);
  }

  function handleChoice(choice) {
    choicesRef.current.push(choice.label);
    pathRef.current.push(choice.next);
    setStep(s => Math.min(s + 1, 4));
    setMessages(prev => {
      const updated = prev.map((m, i) => i === prev.length - 1 ? { ...m, choices: [] } : m);
      return [...updated, { from: "user", text: choice.label, time: nowTime() }];
    });
    agentReply(choice.next);
    if (choice.next === "contact" || choice.next === "autre") {
      saveChatSession(choice.next);
    }
  }

  function send() {
    const txt = input.trim();
    if (!txt) return;
    setInput("");

    // Budget step: treat as budget answer → go to contact
    if (currentNode === "budget") {
      choicesRef.current.push("Budget: " + txt);
      pathRef.current.push("contact");
      setStep(s => Math.min(s + 1, 4));
      setMessages(prev => {
        const updated = prev.map((m, i) => i === prev.length - 1 ? { ...m, choices: [] } : m);
        return [...updated, { from: "user", text: txt, time: nowTime() }];
      });
      saveChatSession("contact");
      agentReply("contact");
      return;
    }

    // Default free-text reply
    freeTextsRef.current.push(txt);
    saveChatSession("free_text");
    setMessages(prev => {
      const updated = prev.map((m, i) => i === prev.length - 1 ? { ...m, choices: [] } : m);
      return [...updated, { from: "user", text: txt, time: nowTime() }];
    });
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMessages(prev => [...prev, {
        from: "agent",
        text: "Merci pour ton message 🙏 Un membre de notre équipe te recontacte très vite !\n\n📧 info@discover.studio",
        choices: [],
        time: nowTime()
      }]);
    }, 900);
  }

  function handleKey(e) {
    if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }
  }

  function restart() {
    savedRef.current = false;
    pathRef.current = ["start"];
    choicesRef.current = [];
    freeTextsRef.current = [];
    setStep(0);
    setCurrentNode("start");
    setMessages([{ from: "agent", text: FLOW.start.agent, choices: FLOW.start.choices, time: nowTime() }]);
  }

  const progressPct = Math.round((step / 4) * 100);

  return (
    <div className="chat-widget">
      {!open && (
        <React.Fragment>
          <a
            href="https://wa.me/4917687564448"
            target="_blank"
            rel="noopener noreferrer"
            className="chat-bubble-wa"
          >
            <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            Contacter sur WhatsApp
          </a>
          <div className="chat-bubble-hint" onClick={() => setOpen(true)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><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>
            Besoin d'aide ?
          </div>
        </React.Fragment>
      )}

      {open && (
        <div className="chat-window">
          {/* Header */}
          <div className="chat-header">
            <div className="chat-header-left">
              <div className="chat-avatar-wrap">
                <img src={agentPhoto} alt="Léa" className="chat-agent-photo" />
                <span className="chat-online-dot" />
              </div>
              <div>
                <div className="chat-agent-name">Léa</div>
                <div className="chat-agent-role">Support · Discover Studio</div>
                <div className="chat-agent-status">
                  <span className="chat-status-dot" />
                  En ligne · répond en &lt;1 min
                </div>
              </div>
            </div>
            <div className="chat-header-actions">
              <button className="chat-icon-btn" onClick={restart} aria-label="Recommencer" title="Recommencer">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" width="14" height="14"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.5"/></svg>
              </button>
              <button className="chat-close" onClick={() => setOpen(false)} aria-label="Fermer">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" width="14" height="14"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
          </div>

          {/* Progress bar */}
          {step > 0 && step < 4 && (
            <div className="chat-progress-bar">
              <div className="chat-progress-fill" style={{ width: progressPct + "%" }} />
            </div>
          )}

          {/* Messages */}
          <div className="chat-messages">
            {messages.map((m, i) => (
              <div key={i} className="chat-msg-group">
                <div className={`chat-msg ${m.from}`}>
                  {m.from === "agent" && <img src={agentPhoto} alt="Léa" className="chat-msg-avatar" />}
                  <div className="chat-msg-inner">
                    <div className="chat-msg-bubble">{m.text}</div>
                    <div className="chat-msg-time">{m.time}</div>
                  </div>
                </div>
                {m.whatsapp && (
                  <div className="chat-wa-wrap">
                    <a
                      href="https://wa.me/4917687564448"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="chat-wa-btn"
                    >
                      <svg viewBox="0 0 24 24" fill="currentColor" width="17" height="17"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                      Contacter sur WhatsApp
                    </a>
                  </div>
                )}
                {m.choices && m.choices.length > 0 && (
                  <div className="chat-choices">
                    {m.choices.map((c, j) => (
                      <button key={j} className="chat-choice-btn" onClick={() => handleChoice(c)}>
                        {c.label}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}
            {typing && (
              <div className="chat-msg agent">
                <img src={agentPhoto} alt="Léa" className="chat-msg-avatar" />
                <div className="chat-msg-inner">
                  <div className="chat-msg-bubble chat-typing">
                    <span /><span /><span />
                  </div>
                </div>
              </div>
            )}
            <div ref={bottomRef} />
          </div>

          {/* Input */}
          <div className="chat-input-row">
            <input
              ref={inputRef}
              className="chat-input"
              placeholder={currentNode === "budget" ? "Ton budget…" : "Écris ton message…"}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKey}
            />
            <button className="chat-send" onClick={send} aria-label="Envoyer" disabled={!input.trim()}>
              <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
              </svg>
            </button>
          </div>

          {/* Footer */}
          <div className="chat-footer">
            Propulsé par <strong>Discover Studio</strong>
          </div>
        </div>
      )}

      <button className="chat-fab" onClick={() => setOpen(o => !o)} aria-label="Chat">
        {open
          ? <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
          : <img src={agentPhoto} alt="Chat" style={{ width: 64, height: 64, borderRadius: "50%", objectFit: "cover", display: "block" }} />
        }
        {!open && <span className="chat-fab-notif">1</span>}
      </button>
    </div>
  );
}

window.ChatWidget = ChatWidget;
