// Módulo 1 — Asistente IA (chat)

function AsistenteIA() {
  const [messages, setMessages] = React.useState([
    { role: "bot", text: "Hola, soy tu asistente comercial Quilosa. Puedo ayudar con stock, precios, clientes, pedidos y rutas. Los datos se sincronizan desde Dynamics AX. Pregunta lo que necesites." },
  ]);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const endRef = React.useRef(null);

  React.useEffect(() => {
    endRef.current?.scrollTo({ top: endRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, thinking]);

  const findResponse = (q) => {
    const ql = q.toLowerCase();
    for (const r of window.APP_DATA.assistantResponses) {
      if (r.match.some((k) => ql.includes(k))) return r;
    }
    return null;
  };

  const submit = (text) => {
    const t = (text ?? input).trim();
    if (!t) return;
    const user = { role: "user", text: t };
    setMessages((m) => [...m, user]);
    setInput("");
    setThinking(true);
    setTimeout(() => {
      const r = findResponse(t);
      const bot = r
        ? { role: "bot", text: r.title, body: r.body, data: r.data }
        : { role: "bot", text: "No encuentro información específica. Pruébalo con un SKU, nombre de producto o cliente (p.ej. 'stock Perfect Finish', 'precio Sintex MS-35', 'ficha OBRAMAT')." };
      setMessages((m) => [...m, bot]);
      setThinking(false);
    }, 650);
  };

  return (
    <>
      <div className="chip-row" style={{ marginBottom: 14 }}>
        {window.APP_DATA.suggestedQuestions.map((q) => (
          <button key={q} className="chip" onClick={() => submit(q)}>{q}</button>
        ))}
      </div>

      <div
        className="card"
        style={{ padding: 0, display: "flex", flexDirection: "column", minHeight: 520 }}
      >
        <div ref={endRef} style={{ padding: 22, flex: 1, overflowY: "auto", maxHeight: 560 }}>
          {messages.map((m, i) => <ChatBubble key={i} m={m} />)}
          {thinking && (
            <div style={{ display: "flex", gap: 6, padding: "6px 2px 12px" }}>
              <span className="typing-dot" /> <span className="typing-dot" /> <span className="typing-dot" />
            </div>
          )}
        </div>
        <div style={{ borderTop: "1px solid var(--border)", padding: 14, display: "flex", gap: 10, alignItems: "center" }}>
          <input
            className="input"
            placeholder="Escribe tu pregunta..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && submit()}
            style={{ flex: 1 }}
          />
          <button className="btn-ghost" style={{ padding: 9, borderRadius: 999, width: 38, height: 38, display: "grid", placeItems: "center" }} title="Voz">
            <div style={{ width: 16, height: 16 }}><Icon.Mic /></div>
          </button>
          <button className="btn" onClick={() => submit()}>
            <div style={{ width: 14, height: 14 }}><Icon.Send /></div> Enviar
          </button>
        </div>
      </div>

      <style>{`
        .typing-dot { width: 6px; height: 6px; border-radius: 999px; background: var(--ink-muted); animation: pulse 1.2s infinite; }
        .typing-dot:nth-child(2) { animation-delay: 0.15s; }
        .typing-dot:nth-child(3) { animation-delay: 0.3s; }
        @keyframes pulse { 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); } 40% { opacity: 1; transform: scale(1); } }
      `}</style>
    </>
  );
}

function ChatBubble({ m }) {
  const isBot = m.role === "bot";
  return (
    <div style={{ display: "flex", justifyContent: isBot ? "flex-start" : "flex-end", marginBottom: 14 }}>
      <div
        style={{
          maxWidth: "78%",
          background: isBot ? "var(--surface-2)" : "var(--accent)",
          color: isBot ? "var(--ink)" : "#fff",
          padding: "12px 16px",
          borderRadius: 12,
          fontSize: 13.5,
          lineHeight: 1.55,
        }}
      >
        <div style={{ fontWeight: isBot && m.body ? 600 : 400 }}>{m.text}</div>
        {m.body && <div style={{ fontSize: 12.5, color: "var(--ink-muted)", marginTop: 4 }}>{m.body}</div>}
        {m.data && <AssistantData data={m.data} />}
      </div>
    </div>
  );
}

function AssistantData({ data }) {
  const D = window.APP_DATA;
  if (data.type === "stock") {
    const p = D.products.find(x => x.sku === data.sku);
    if (!p) return null;
    return (
      <div style={{ marginTop: 10, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, padding: 12 }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13, color: "var(--ink)" }}>{p.name}</div>
            <div className="mono">{p.sku}</div>
          </div>
          <span className={"dot " + p.status}></span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 10 }}>
          <Stat label="TOTAL" value={p.stock} />
          <Stat label="RESERVADO" value={p.reserved} />
          <Stat label="LIBRE" value={p.free} accent />
        </div>
      </div>
    );
  }
  if (data.type === "pricing") {
    return (
      <table style={{ marginTop: 10, width: "100%", fontSize: 12.5, borderCollapse: "collapse", background: "var(--surface)", borderRadius: 8, overflow: "hidden", border: "1px solid var(--border)" }}>
        <thead><tr style={{ background: "var(--surface-2)" }}>
          <th style={{ padding: 8, textAlign: "left", color: "var(--ink-muted)" }}>Cliente</th>
          <th style={{ padding: 8, textAlign: "right", color: "var(--ink-muted)" }}>Precio</th>
          <th style={{ padding: 8, textAlign: "right", color: "var(--ink-muted)" }}>Descuento</th>
        </tr></thead>
        <tbody>
          <tr><td style={{ padding: 8 }}>OBRAMAT Rivas (Clase A)</td><td style={{ padding: 8, textAlign: "right" }}>4,85 €</td><td style={{ padding: 8, textAlign: "right", color: "var(--ok)" }}>−16%</td></tr>
          <tr><td style={{ padding: 8 }}>Leroy Merlin Getafe</td><td style={{ padding: 8, textAlign: "right" }}>5,10 €</td><td style={{ padding: 8, textAlign: "right", color: "var(--ok)" }}>−12%</td></tr>
          <tr><td style={{ padding: 8 }}>Materiales García</td><td style={{ padding: 8, textAlign: "right" }}>5,45 €</td><td style={{ padding: 8, textAlign: "right", color: "var(--ok)" }}>−6%</td></tr>
        </tbody>
      </table>
    );
  }
  if (data.type === "clients-zone") {
    const list = D.clients.filter(c => c.city.toLowerCase().includes("rivas"));
    return (
      <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 6 }}>
        {list.map(c => (
          <div key={c.code} style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, padding: "8px 12px", display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--ink)" }}>
            <div>{c.name} <span className="mono">· {c.code}</span></div>
            <div><Badge variant={c.class === "A" ? "ok" : c.class === "B" ? "info" : "neutral"}>Clase {c.class}</Badge></div>
          </div>
        ))}
      </div>
    );
  }
  if (data.type === "client") {
    const c = D.clients.find(x => x.code === data.code);
    if (!c) return null;
    return (
      <div style={{ marginTop: 10, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, padding: 12 }}>
        <div style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</div>
        <div className="mono">{c.cif} · {c.city}</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 10 }}>
          <Stat label="VOLUMEN" value={c.volume} />
          <Stat label="CLASE" value={c.class} />
          <Stat label="RAPPEL" value={c.rappel + "%"} accent />
        </div>
      </div>
    );
  }
  if (data.type === "reposition") {
    return (
      <div style={{ marginTop: 10, background: "var(--warn-soft)", border: "1px solid var(--warn)", borderRadius: 8, padding: 10, fontSize: 12.5, color: "oklch(0.35 0.14 75)" }}>
        ⚠ Próxima entrada: <b>25/05/2026</b> — Lote L-2026-112 (5.000 uds)
      </div>
    );
  }
  return null;
}

function Stat({ label, value, accent }) {
  return (
    <div style={{ background: "var(--surface-2)", padding: "8px 10px", borderRadius: 6, textAlign: "center" }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: accent ? "var(--accent)" : "var(--ink)" }}>{value}</div>
      <div style={{ fontSize: 10, color: "var(--ink-muted)", textTransform: "uppercase", letterSpacing: "0.05em", marginTop: 2 }}>{label}</div>
    </div>
  );
}

Object.assign(window, { AsistenteIA });
