// Pantalla: IA Asistente — conectado a API real (requiere API key configurada)

const IAAsistente = ({user}) => {
  const [msgs, setMsgs]   = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [iaStatus, setIaStatus] = useState(null); // null=checking, true=ok, false=no-key
  const feedRef = useRef(null);

  useEffect(()=>{
    // Verificar si la IA está configurada probando con un ping
    setIaStatus(null);
    window.API.ia.consulta("ping").then(()=>setIaStatus(true)).catch(e=>{
      if (e.message.includes("no configurada") || e.message.includes("503")) setIaStatus(false);
      else setIaStatus(true);
    });
  }, []);

  useEffect(()=>{
    if (iaStatus === true) {
      setMsgs([{role:"ai", text:`¡Hola **${user.nombre.split(" ")[0]}**! Soy el asistente de ALMACO con acceso a los datos del sistema.\n\nPuedo ayudarte con consultas sobre proyectos, gastos, planillas y transferencias en lenguaje natural. ¿Qué necesitas hoy?`}]);
    }
  }, [iaStatus]);

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

  const ask = async (text) => {
    if (!text?.trim() || loading) return;
    const t = text.trim();
    setMsgs(prev=>[...prev, {role:"user", text:t}]);
    setInput("");
    setLoading(true);
    try {
      const {respuesta} = await window.API.ia.consulta(t);
      setMsgs(prev=>[...prev, {role:"ai", text:respuesta}]);
    } catch(e) {
      setMsgs(prev=>[...prev, {role:"ai", text:`❌ Error: ${e.message}`, isError:true}]);
    } finally { setLoading(false); }
  };

  const sugerencias = [
    {icon:"📊", t:"¿Cuánto se ha gastado en total este mes?"},
    {icon:"🏗️", t:"¿Cuáles proyectos están en ejecución?"},
    {icon:"👷", t:"¿Cuál es el costo real de la última planilla?"},
    {icon:"💸", t:"¿Qué transferencias están pendientes?"},
    {icon:"🧮", t:"¿Cuánto cuesta un empleado con carga patronal incluida?"},
    {icon:"📈", t:"Resumen general del estado financiero de los proyectos"},
  ];

  // Render markdown básico
  const renderMsg = (text) => {
    if (typeof text !== "string") return text;
    const lines = text.split("\n");
    return lines.map((line, i) => {
      // Bold
      line = line.replace(/\*\*(.*?)\*\*/g, (_, t) => `<strong>${t}</strong>`);
      // Code inline
      line = line.replace(/`(.*?)`/g, (_, t) => `<code style="background:var(--bg-3);padding:1px 5px;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:12px">${t}</code>`);
      if (line.match(/^#{1,3} /)) {
        return <div key={i} style={{fontWeight:700,fontSize:15,marginBottom:4,marginTop:i>0?10:0}} dangerouslySetInnerHTML={{__html:line.replace(/^#+\s/,"")}}/>;
      }
      if (line.match(/^[-*] /)) {
        return <div key={i} style={{paddingLeft:16,marginBottom:3,display:"flex",gap:8}}><span style={{color:"var(--yellow)"}}>•</span><span dangerouslySetInnerHTML={{__html:line.replace(/^[-*] /,"")}}/></div>;
      }
      if (line.match(/^\d+\. /)) {
        return <div key={i} style={{paddingLeft:16,marginBottom:3}} dangerouslySetInnerHTML={{__html:line}}/>;
      }
      if (!line.trim()) return <div key={i} style={{height:8}}/>;
      return <div key={i} style={{marginBottom:2}} dangerouslySetInnerHTML={{__html:line}}/>;
    });
  };

  // Estado: verificando
  if (iaStatus === null) return (
    <div className="content" style={{display:"flex",alignItems:"center",justifyContent:"center",minHeight:300}}>
      <div style={{display:"flex",flexDirection:"column",alignItems:"center",gap:14}}>
        <Spinner size={28}/>
        <div style={{fontSize:13,color:"var(--text-3)"}}>Verificando conexión con IA…</div>
      </div>
    </div>
  );

  // Estado: IA no configurada
  if (iaStatus === false) return (
    <div className="content">
      <div className="page-title-row">
        <div>
          <div className="page-title">IA Asistente</div>
          <div className="page-sub">Asistente inteligente con acceso a datos del sistema</div>
        </div>
      </div>
      <div className="card">
        <div className="card-body" style={{display:"flex",flexDirection:"column",alignItems:"center",padding:"60px 20px",gap:20,textAlign:"center"}}>
          <div style={{width:64,height:64,borderRadius:14,background:"var(--yellow-dim)",border:"1px solid rgba(245,197,0,0.3)",display:"flex",alignItems:"center",justifyContent:"center"}}>
            <Icon name="sparkles" size={28} style={{color:"var(--yellow)"}}/>
          </div>
          <div>
            <div style={{fontWeight:700,fontSize:18,marginBottom:8}}>IA Asistente no configurada</div>
            <div style={{fontSize:13,color:"var(--text-3)",maxWidth:440,lineHeight:1.7}}>
              Para activar el asistente con IA de Claude necesitas configurar tu <strong style={{color:"var(--text)"}}>API Key de Anthropic</strong>.
            </div>
          </div>
          <div style={{background:"var(--bg-3)",border:"1px solid var(--border)",borderRadius:10,padding:"16px 24px",textAlign:"left",maxWidth:420}}>
            <div style={{fontWeight:600,fontSize:13,marginBottom:10,display:"flex",alignItems:"center",gap:8}}><Icon name="key" size={14}/> Pasos para activar</div>
            <ol style={{fontSize:13,color:"var(--text-2)",lineHeight:2,paddingLeft:18}}>
              <li>Ve a <strong>console.anthropic.com</strong></li>
              <li>Crea o copia tu API Key</li>
              <li>En este sistema: <strong>Configuración → IA Asistente</strong></li>
              <li>Pega la API Key y guarda</li>
            </ol>
          </div>
          {["admin","gerencia"].includes(user.rol) && (
            <button className="btn-primary" style={{width:"auto",padding:"12px 24px"}} onClick={()=>window.dispatchEvent(new CustomEvent("almaco:route",{detail:"config"}))}>
              <Icon name="settings" size={14}/> Ir a Configuración
            </button>
          )}
        </div>
      </div>
    </div>
  );

  // Estado: IA disponible
  return (
    <div className="content" style={{padding:0,display:"flex",flexDirection:"column",height:"calc(100vh - 56px)"}}>
      <div style={{padding:"18px 32px 14px",borderBottom:"1px solid var(--border)"}}>
        <div style={{display:"flex",alignItems:"center",gap:14}}>
          <div style={{width:42,height:42,borderRadius:10,background:"linear-gradient(135deg,var(--yellow),#FFD53D)",display:"flex",alignItems:"center",justifyContent:"center",color:"#0A0A0A"}}>
            <Icon name="sparkles" size={20}/>
          </div>
          <div style={{flex:1}}>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <div className="page-title" style={{fontSize:18}}>IA Asistente</div>
              <Pill color="green" dot>Conectada · Claude Sonnet 4</Pill>
              <Pill color="yellow">{user.rol === "admin" || user.rol === "gerencia" ? "Acceso completo" : "Acceso restringido"}</Pill>
            </div>
            <div className="page-sub" style={{margin:0,marginTop:2}}>Consultas en español · Acceso a proyectos, gastos y planillas</div>
          </div>
          <button className="btn-secondary" onClick={()=>setMsgs([{role:"ai",text:`¡Hola! Nueva conversación iniciada. ¿En qué puedo ayudarte?`}])}><Icon name="refresh" size={13}/> Nueva conversación</button>
        </div>
      </div>

      <div ref={feedRef} className="chat-feed" style={{flex:1,overflowY:"auto",padding:"20px 0"}}>
        {msgs.map((m,i)=>(
          <div key={i} className={`chat-msg ${m.role}`}>
            <div className={`chat-avatar ${m.role}`}>
              {m.role==="ai" ? <Icon name="sparkles" size={14}/> : user.iniciales}
            </div>
            <div className={`chat-bubble${m.isError?" error":""}`}>{renderMsg(m.text)}</div>
          </div>
        ))}
        {loading && (
          <div className="chat-msg ai">
            <div className="chat-avatar ai"><Icon name="sparkles" size={14}/></div>
            <div className="chat-bubble" style={{display:"flex",alignItems:"center",gap:10,color:"var(--text-3)"}}>
              <Spinner size={14}/> Consultando el sistema…
            </div>
          </div>
        )}

        {msgs.length === 1 && (
          <div style={{padding:"20px 28px 0",maxWidth:780}}>
            <div style={{fontSize:11,color:"var(--text-3)",textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:600,marginBottom:12}}>Preguntas sugeridas</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
              {sugerencias.map((s,i)=>(
                <button key={i} className="demo-user" onClick={()=>ask(s.t)} style={{padding:"12px 14px",borderRadius:10}}>
                  <div className="avatar" style={{background:"var(--bg-4)",fontSize:14,width:28,height:28}}>{s.icon}</div>
                  <div className="info">
                    <div className="name" style={{fontWeight:500,fontSize:12.5,color:"var(--text-2)"}}>{s.t}</div>
                  </div>
                  <span className="arrow"><Icon name="arrowright" size={13}/></span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      <div className="chat-input-wrap">
        <div className="chat-input">
          <input
            placeholder="Pregúntale a la IA sobre gastos, proyectos, planillas..."
            value={input}
            onChange={e=>setInput(e.target.value)}
            onKeyDown={e=>e.key==="Enter"&&!e.shiftKey&&ask(input)}
            disabled={loading}
          />
          <button className="chat-send" onClick={()=>ask(input)} disabled={!input||loading}>
            {loading ? <Spinner size={13}/> : <Icon name="send" size={13}/>}
          </button>
        </div>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:8,padding:"0 4px",fontSize:11,color:"var(--text-3)"}}>
          <span>La IA tiene acceso de lectura a proyectos, gastos, planillas y transferencias.</span>
          <span className="mono">{input.length} / 4000</span>
        </div>
      </div>
    </div>
  );
};

window.IAAsistente = IAAsistente;
