/* global React, NavIcon, MCP_RULES, MCP_THREAD, MCP_QUICK */

const { useState: useStateM, useRef: useRefM, useEffect: useEffectM } = React;

// ============ Widget renderer ============
const Widget = ({ w }) => {
  if (!w || !w.kind) return null;
  if (w.kind === "bars") {
    const data = w.data || [];
    const max = Math.max(1, ...data.map(d => Number(d.value) || 0));
    return (
      <div className="mcp-widget">
        <h5>{w.title || "Gráfico"}</h5>
        <div className="bar-chart">
          {data.map((d, i) => (
            <div key={i} className="bar">
              <span className="v">{d.value}</span>
              <i style={{height: `${(Number(d.value) / max) * 110}px`}}/>
              <span className="l">{d.label}</span>
            </div>
          ))}
        </div>
        {w.note && <p className="wnote">{w.note}</p>}
      </div>
    );
  }
  if (w.kind === "table") {
    return (
      <div className="mcp-widget">
        <h5>{w.title || "Tabla"}</h5>
        <table className="mcp-table">
          <thead>
            <tr>{(w.cols || []).map((c, i) => <th key={i} style={i > 0 ? {textAlign:"right"} : {}}>{c}</th>)}</tr>
          </thead>
          <tbody>
            {(w.rows || []).map((r, i) => (
              <tr key={i}>
                {r.map((cell, j) => <td key={j} className={j > 0 ? "num" : ""}>{cell}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
        {w.note && <p className="wnote">{w.note}</p>}
      </div>
    );
  }
  if (w.kind === "rank") {
    const data = w.data || [];
    const max = Math.max(1, ...data.map(d => Number(d.count) || 0));
    return (
      <div className="mcp-widget">
        <h5>{w.title || "Ranking"}</h5>
        <div className="rank-list">
          {data.map((d, i) => (
            <div key={i} className="rank-row">
              <span className="num">{i+1}</span>
              <span className="name">{d.name}</span>
              <span className="b"><i style={{width: `${(Number(d.count) / max) * 100}%`}}/></span>
              <span className="count">{d.count}</span>
            </div>
          ))}
        </div>
        {w.note && <p className="wnote">{w.note}</p>}
      </div>
    );
  }
  if (w.kind === "kpis") {
    const data = w.data || [];
    return (
      <div className="mcp-widget">
        <h5>{w.title || "Indicadores"}</h5>
        <div style={{display:"grid",gridTemplateColumns:`repeat(${Math.min(data.length,4)},1fr)`,gap:10}}>
          {data.map((d, i) => (
            <div key={i} style={{background:"#FFFFFF",border:"1px solid var(--line)",borderRadius:8,padding:"10px 12px"}}>
              <div style={{fontFamily:"var(--mono)",fontSize:9,letterSpacing:"0.08em",color:"var(--text-3)",textTransform:"uppercase"}}>{d.label}</div>
              <div style={{fontSize:18,fontWeight:600,marginTop:4,letterSpacing:"-0.01em",color:"var(--text)"}}>{d.value}{d.unit && <span style={{fontSize:11,color:"var(--text-3)",fontFamily:"var(--mono)",marginLeft:4}}>{d.unit}</span>}</div>
            </div>
          ))}
        </div>
        {w.note && <p className="wnote">{w.note}</p>}
      </div>
    );
  }
  return null;
};

const sourceLabel = {
  tickets: "Sistema de tickets",
  kb: "Knowledge Base",
  equipos: "BD de equipos",
  contratos: "BD de contratos",
  calendar: "Calendario técnicos",
  agenda: "Calendario técnicos",
  reglas: "Reglas MCP",
};

const Msg = ({ m }) => {
  return (
    <div className={`mcp-msg ${m.role}`}>
      <div className="av">{m.role === "sofia" ? "S" : "AC"}</div>
      <div className="body">
        <div className="meta">
          <b>{m.role === "sofia" ? "SOF.IA" : "Alejandra Carrillo"}</b>
          <span>· {m.time}</span>
          {m.role === "sofia" && <span className="auto-badge" style={{marginLeft:4}}>MCP</span>}
        </div>
        {m.loading ? (
          <div className="text" style={{color:"var(--text-3)",fontStyle:"italic",display:"flex",alignItems:"center",gap:8}}>
            <span className="thinking-dots"><i/><i/><i/></span>
            consultando sistemas conectados…
          </div>
        ) : (
          <>
            <div className="text" dangerouslySetInnerHTML={{__html: (m.text || "").replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>").replace(/\n/g,"<br/>")}}/>
            {m.widget && <Widget w={m.widget}/>}
            {m.sources && m.sources.length > 0 && (
              <div className="mcp-sources">
                {m.sources.map(s => <span key={s} className="mcp-source">↘ {sourceLabel[s] || s}</span>)}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

// ============ Prompt for SOF.IA ============
const SYSTEM_PROMPT = `Eres SOF.IA, una agente de IA omnicanal de Optipixel que automatiza el soporte técnico de impresoras para Canella (empresa guatemalteca). Estás respondiendo a Alejandra Carrillo, Dispatcher de Canella, en su consola interna "MCP Console". Hablas en español de Guatemala, profesional, conciso, técnico pero claro.

Tienes acceso vía MCP a:
- tickets: bandeja activa y resueltos (canales: WhatsApp, llamada, web chat, correo)
- equipos: BD de impresoras (HP LaserJet Pro M404dn, HP LaserJet M428fdw, HP Color LaserJet M283fdw, HP OfficeJet Pro 9015e, HP LaserJet M111w, Canon imageRUNNER 2630i, Canon LBP6230dw)
- contratos: arrendamiento (ARR-*) y mantenimiento (MANT-*)
- kb: Knowledge Base (artículos KB-HP-*, KB-CAN-*, KB-GEN-*)
- agenda: calendario técnicos (Eddy R. Marroquín zona 11, Walter A. Galindo zona 10)

Reglas activas que debes respetar al razonar:
- Si entra un HP sin serie → escalar a Dispatcher
- Arrendamiento → Conectividad
- Cliente facturado/cotización → "fuera de alcance fase 1"
- HW/SW con consulta técnica → KB o Taller
- Visita técnica → Dispatcher
- Equipos HP tienen series largas alfanuméricas (10 caracteres tipo VNB3K12089)

Datos contextuales que puedes usar libremente (inventa cifras realistas si te las piden):
- Volumen típico: ~128 tickets/día, 80% resueltos sin humano, ~17% escalados
- Canales dominantes: WhatsApp y llamada
- Falla más común: atascos de papel en HP M404dn (rodillo bandeja 2, ~80k impresiones)
- Tiempo medio captura: 42 segundos
- Operadores Canella: Alejandra Carrillo (Dispatcher), Marcos R. (Optipixel)

Responde SOLO con JSON válido en este formato exacto:
{
  "text": "tu respuesta en máximo 3 frases cortas, puede usar **negrita** y saltos de línea",
  "sources": ["tickets","kb","equipos","contratos","agenda","reglas"],
  "widget": null | { "kind": "bars"|"table"|"rank"|"kpis", ...campos }
}

Widgets:
- bars: { "kind":"bars", "title":"...", "data":[{"label":"L","value":4},...], "note":"breve insight" }
- table: { "kind":"table", "title":"...", "cols":["Col1","Col2"], "rows":[["a","b"],...], "note":"..." }
- rank: { "kind":"rank", "title":"...", "data":[{"name":"...","count":N},...], "note":"..." }
- kpis: { "kind":"kpis", "title":"...", "data":[{"label":"...","value":"...","unit":"..."},...], "note":"..." }

Usa widget cuando la pregunta pida datos cuantitativos o comparaciones. Para preguntas conceptuales o de proceso, devuelve "widget": null.
Incluye 1-3 sources relevantes. Sé directa, profesional, datos realistas. NUNCA salgas del JSON.`;

// ============ MAIN ============
const McpScreen = () => {
  const [rules, setRules] = useStateM(MCP_RULES);
  const [newRule, setNewRule] = useStateM("");
  const [input, setInput] = useStateM("");
  const [messages, setMessages] = useStateM(MCP_THREAD);
  const [busy, setBusy] = useStateM(false);
  const threadRef = useRefM(null);

  useEffectM(() => {
    if (threadRef.current) {
      threadRef.current.scrollTop = threadRef.current.scrollHeight;
    }
  }, [messages, busy]);

  const toggleRule = (id) => {
    setRules(rs => rs.map(r => r.id === id ? {...r, active: !r.active} : r));
  };

  const addRule = () => {
    if (!newRule.trim()) return;
    setRules(rs => [...rs, {
      id: `R-${String(rs.length + 1).padStart(3,"0")}`,
      text: newRule.trim(),
      author: "Alejandra Carrillo",
      created: "hoy",
      triggers: 0,
      active: true,
      category: "Custom",
    }]);
    setNewRule("");
  };

  const fmtTime = () => {
    const d = new Date();
    return `${String(d.getHours()).padStart(2,"0")}:${String(d.getMinutes()).padStart(2,"0")}`;
  };

  const send = async (text) => {
    const q = (text || input).trim();
    if (!q || busy) return;
    setInput("");
    setBusy(true);
    const userMsg = { role:"user", text:q, time:fmtTime() };
    const loadingMsg = { role:"sofia", loading:true, time:fmtTime() };
    setMessages(ms => [...ms, userMsg, loadingMsg]);

    try {
      const raw = await window.claude.complete({
        messages: [
          { role:"user", content: SYSTEM_PROMPT + "\n\nPregunta del operador:\n" + q }
        ],
      });
      // Try to parse JSON from response
      let parsed = null;
      try {
        // strip code fences if present
        let cleaned = raw.trim();
        const fence = cleaned.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
        if (fence) cleaned = fence[1];
        // find outermost JSON
        const first = cleaned.indexOf("{");
        const last = cleaned.lastIndexOf("}");
        if (first >= 0 && last > first) cleaned = cleaned.slice(first, last+1);
        parsed = JSON.parse(cleaned);
      } catch (e) {
        parsed = { text: raw, sources: ["tickets"], widget: null };
      }
      const sofiaMsg = {
        role: "sofia",
        text: parsed.text || "(sin respuesta)",
        sources: parsed.sources || [],
        widget: parsed.widget || null,
        time: fmtTime(),
      };
      setMessages(ms => [...ms.slice(0,-1), sofiaMsg]);
    } catch (err) {
      setMessages(ms => [...ms.slice(0,-1), {
        role: "sofia",
        text: "No pude consultar los sistemas en este momento. Intenta de nuevo en unos segundos.",
        sources: [],
        time: fmtTime(),
      }]);
    } finally {
      setBusy(false);
    }
  };

  const onKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  return (
    <div className="page" data-screen-label="05 Copilot MCP · Preguntar a SOF.IA">
      <div className="crumb"><a>SOF.IA</a><span className="sep">/</span><a>Copilot MCP</a></div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Preguntar a SOF.IA · Copilot MCP</h1>
          <div className="page-sub">Lenguaje natural sobre tickets, equipos, KB y agenda · conectado vía MCP</div>
        </div>
        <div style={{display:"flex",gap:8}}>
          <span className="status-pill"><span className="pulse"/> MCP · 4 SISTEMAS CONECTADOS</span>
        </div>
      </div>

      <div className="mcp">
        {/* Chat */}
        <div className="mcp-chat">
          <div className="mcp-thread" ref={threadRef}>
            {messages.map((m, i) => <Msg key={i} m={m}/>)}
          </div>

          <div className="mcp-input">
            <div className="chips">
              {MCP_QUICK.map(c => (
                <span key={c} className="chip" onClick={() => send(c)}>↳ {c}</span>
              ))}
            </div>
            <div className="field">
              <NavIcon name="bolt"/>
              <input
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={onKey}
                placeholder={busy ? "SOF.IA está respondiendo…" : "Pregúntale a SOF.IA, crea una regla, pide un reporte…"}
                disabled={busy}
              />
              <button className="btn primary sm" onClick={() => send()} disabled={busy || !input.trim()}>
                {busy ? "…" : "Enviar ⏎"}
              </button>
            </div>
            <div className="hint-row">
              <span>SOF.IA lee tickets, equipos, KB y calendario. Las consultas son auditadas.</span>
              <span>⏎ enviar · ⇧⏎ nueva línea</span>
            </div>
          </div>
        </div>

        {/* Side: rules + connected systems */}
        <div className="mcp-side">
          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="bolt"/>
              <h3>Reglas activas</h3>
              <span className="tag">{rules.filter(r => r.active).length}/{rules.length}</span>
            </div>
            <div className="mcp-rules" style={{maxHeight:340,overflowY:"auto"}}>
              {rules.map(r => (
                <div key={r.id} className={`rule-item ${r.active ? "on" : ""}`}>
                  <span className="toggle" onClick={() => toggleRule(r.id)}/>
                  <div className="info">
                    <div className="rt">{r.text}</div>
                    <div className="rm">
                      <span className="rule-cat">{r.category}</span>
                      <span>{r.author}</span>
                      <span>· {r.triggers} disparos</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="rule-new">
              <input
                placeholder='Ej. "Si el cliente menciona Notaría, prioridad alta"'
                value={newRule}
                onChange={e => setNewRule(e.target.value)}
                onKeyDown={e => e.key === "Enter" && addRule()}
              />
              <button className="btn primary sm" onClick={addRule}>+ Crear</button>
            </div>
          </div>

          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="routes"/>
              <h3>Sistemas conectados (MCP)</h3>
              <span className="tag">en vivo</span>
            </div>
            <div className="mcp-systems">
              <div className="sys-row"><span className="dot"/><span className="name">tickets.canella.gt</span><span className="ping">14 ms</span></div>
              <div className="sys-row"><span className="dot"/><span className="name">equipos.canella.gt</span><span className="ping">9 ms</span></div>
              <div className="sys-row"><span className="dot"/><span className="name">contratos.canella.gt</span><span className="ping">22 ms</span></div>
              <div className="sys-row"><span className="dot"/><span className="name">kb.canella.gt</span><span className="ping">7 ms</span></div>
              <div className="sys-row"><span className="dot" style={{background:"var(--yellow)"}}/><span className="name">calendar.dispatch.gt</span><span className="ping">38 ms</span></div>
            </div>
          </div>

          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="history"/>
              <h3>Reportes recientes</h3>
            </div>
            <div style={{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8,fontSize:12}}>
              <div style={{display:"flex",justifyContent:"space-between",color:"var(--text-2)"}}><span>Volumen omnicanal · mayo</span><span className="hint">hace 2h</span></div>
              <div style={{display:"flex",justifyContent:"space-between",color:"var(--text-2)"}}><span>Top fallas HP M404</span><span className="hint">ayer</span></div>
              <div style={{display:"flex",justifyContent:"space-between",color:"var(--text-2)"}}><span>SLA por canal · sem. 21</span><span className="hint">23 may</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.McpScreen = McpScreen;
