// ai.jsx — Copiloto clínico IA (simulado)
const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI } = React;

function Typewriter({ text, speed = 12, onDone, style }) {
  const [shown, setShown] = useStateAI("");
  useEffectAI(() => {
    setShown("");
    let i = 0;
    const id = setInterval(() => {
      i += 2;
      setShown(text.slice(0, i));
      if (i >= text.length) { clearInterval(id); onDone && onDone(); }
    }, speed);
    return () => clearInterval(id);
  }, [text]);
  return <div style={style}>{shown}<span className="g-caret" style={{ opacity: shown.length < text.length ? 1 : 0 }}>▍</span></div>;
}

function AIChip({ children }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 700, color: "#6d28d9", background: "color-mix(in oklch, #7c3aed 11%, transparent)", padding: "3px 9px", borderRadius: 999, letterSpacing: ".02em" }}>
      <Icon name="ai" size={12} /> {children}
    </span>
  );
}

function AISummary({ paciente }) {
  const [state, setState] = useStateAI("idle");
  const resumen = `Mujer de ${paciente.edad} años, hipertensa conocida (I10), con alergia documentada a medio de contraste yodado. Atendida el 30/03/2026 por dolor precordial anginoso (EVA 9/10) con irradiación a miembro superior izquierdo, lipotimia y diaforesis. Se realizó cinecoronariografía por acceso radial derecho que descartó lesiones angiográficas significativas; ecocardiograma con FEVI conservada (59%) e hipertrofia concéntrica leve de VI. Egresó estable con alta médica el mismo día. Control actual (02/06/2026): asintomática, hemodinámicamente estable, herida de punción sin complicaciones.`;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <AIChip>Resumen automático</AIChip>
        {state === "done" && <span style={{ fontSize: 11, color: "var(--ink-3)" }}>Generado de 6 documentos</span>}
      </div>
      {state === "idle" && (
        <button onClick={() => { setState("loading"); setTimeout(() => setState("done"), 900); }} className="g-aibtn"
          style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "11px", borderRadius: 10, border: "1px dashed color-mix(in oklch, #7c3aed 40%, var(--line))", background: "color-mix(in oklch, #7c3aed 5%, transparent)", color: "#6d28d9", fontWeight: 600, fontSize: 13.5, cursor: "pointer", fontFamily: "inherit" }}>
          <Icon name="ai" size={16} /> Resumir historia clínica con IA
        </button>
      )}
      {state === "loading" && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px", color: "var(--ink-3)", fontSize: 13.5 }}>
          <span className="g-spin" style={{ width: 16, height: 16, border: "2px solid var(--line-2)", borderTopColor: "#7c3aed", borderRadius: 99, display: "inline-block" }} />
          Analizando documentos clínicos…
        </div>
      )}
      {state === "done" && (
        <div style={{ fontSize: 13.5, lineHeight: 1.62, color: "var(--ink-2)", background: "color-mix(in oklch, #7c3aed 4%, transparent)", border: "1px solid color-mix(in oklch, #7c3aed 16%, var(--line))", borderRadius: 11, padding: "13px 15px" }}>
          <Typewriter text={resumen} />
        </div>
      )}
    </div>
  );
}

function AIAlerts({ paciente }) {
  const alertas = [];
  if (!alertas.length) return null;
  const sevMap = { alta: { tone: "red", label: "Crítica" }, media: { tone: "amber", label: "Precaución" }, baja: { tone: "blue", label: "Aviso" } };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <AIChip>Alertas de seguridad</AIChip>
      {alertas.map((a, i) => {
        const s = sevMap[a.sev];
        const col = a.sev === "alta" ? "var(--danger)" : a.sev === "media" ? "var(--warn-ink)" : "var(--accent)";
        const bg = a.sev === "alta" ? "var(--danger-soft)" : a.sev === "media" ? "color-mix(in oklch, var(--warn) 16%, transparent)" : "var(--accent-soft)";
        return (
          <div key={i} style={{ display: "flex", gap: 11, padding: "12px 13px", borderRadius: 11, background: bg, border: `1px solid color-mix(in oklch, ${col} 25%, transparent)` }}>
            <span style={{ color: col, flexShrink: 0, marginTop: 1 }}><Icon name="alert" size={18} /></span>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", gap: 7, alignItems: "center", marginBottom: 3 }}>
                <Badge tone={s.tone}>{a.tipo}</Badge>
                <span style={{ fontSize: 11, fontWeight: 700, color: col }}>{s.label}</span>
              </div>
              <p style={{ margin: 0, fontSize: 12.8, lineHeight: 1.5, color: "var(--ink-2)" }}>{a.txt}</p>
            </div>
          </div>
        );
      })}
    </div>
  );
}

const TRANSCRIPCION_DEMO = [
  "Paciente acude para control posquirúrgico de cinecoronariografía realizada hace nueve semanas.",
  "Refiere encontrarse asintomática, sin dolor precordial ni disnea de esfuerzo.",
  "Niega palpitaciones. Buena tolerancia a la actividad física habitual.",
  "Al examen: ruidos cardíacos rítmicos, no soplos. Pulmones con murmullo vesicular conservado.",
  "Herida de punción en muñeca derecha cicatrizada, sin signos de complicación vascular.",
  "Tensión arterial 138/84, frecuencia cardíaca 72 por minuto, saturación 98%.",
];

function AITranscription({ onInsert }) {
  const [rec, setRec] = useStateAI(false);
  const [lines, setLines] = useStateAI([]);
  const idx = useRefAI(0);
  useEffectAI(() => {
    if (!rec) return;
    const id = setInterval(() => {
      if (idx.current >= TRANSCRIPCION_DEMO.length) { setRec(false); clearInterval(id); return; }
      setLines((l) => [...l, TRANSCRIPCION_DEMO[idx.current]]);
      idx.current += 1;
    }, 1100);
    return () => clearInterval(id);
  }, [rec]);
  const full = lines.join(" ");
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <AIChip>Transcripción de consulta</AIChip>
        {lines.length > 0 && !rec && <button onClick={() => { setLines([]); idx.current = 0; }} style={{ border: "none", background: "transparent", color: "var(--ink-3)", fontSize: 12, cursor: "pointer", fontFamily: "inherit" }}>Limpiar</button>}
      </div>
      <button onClick={() => { if (!rec) { setLines([]); idx.current = 0; } setRec(!rec); }}
        style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 9, padding: "11px", borderRadius: 10, border: "none", cursor: "pointer", fontFamily: "inherit", fontWeight: 600, fontSize: 13.5, background: rec ? "var(--danger-soft)" : "var(--accent-soft)", color: rec ? "var(--danger)" : "var(--accent-ink)" }}>
        {rec ? <><span className="g-pulse" style={{ width: 9, height: 9, borderRadius: 99, background: "var(--danger)" }} /> Detener dictado · grabando…</> : <><Icon name="mic" size={16} /> Iniciar dictado por voz</>}
      </button>
      {lines.length > 0 && (
        <div style={{ fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)", background: "var(--field)", border: "1px solid var(--line)", borderRadius: 11, padding: "12px 14px", maxHeight: 180, overflowY: "auto" }}>
          {full}{rec && <span className="g-caret">▍</span>}
        </div>
      )}
      {lines.length > 0 && !rec && <Btn variant="soft" size="sm" icon="plus" onClick={() => onInsert && onInsert(full)}>Insertar en la nota de evolución</Btn>}
    </div>
  );
}

function AICopilot({ paciente, open, onClose, onInsertText }) {
  return (
    <aside style={{ position: "fixed", top: 0, right: 0, bottom: 0, width: 380, maxWidth: "92vw", zIndex: 150, background: "var(--surface)", borderLeft: "1px solid var(--line)", boxShadow: "-12px 0 40px -16px rgba(0,0,0,.25)", transform: open ? "translateX(0)" : "translateX(105%)", transition: "transform .28s cubic-bezier(.4,0,.2,1)", display: "flex", flexDirection: "column" }}>
      <header style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px", borderBottom: "1px solid var(--line)" }}>
        <span style={{ width: 34, height: 34, borderRadius: 10, background: "linear-gradient(135deg,#7c3aed,#2563eb)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="ai" size={19} /></span>
        <div style={{ flex: 1 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>Copiloto clínico</h3>
          <p style={{ margin: 0, fontSize: 11.5, color: "var(--ink-3)" }}>Asistencia IA · {paciente ? paciente.apellidos : "—"}</p>
        </div>
        <button onClick={onClose} className="g-iconbtn" style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--ink-3)", padding: 5, borderRadius: 8, display: "flex" }}><Icon name="x" size={19} /></button>
      </header>
      <div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 22 }}>
        {paciente && <AIAlerts paciente={paciente} />}
        {paciente && <AISummary paciente={paciente} />}
        <AITranscription onInsert={onInsertText} />
        <div style={{ marginTop: "auto", paddingTop: 12, borderTop: "1px solid var(--line)", fontSize: 11, color: "var(--ink-3)", lineHeight: 1.5 }}>
          Las funciones de IA son asistivas y no reemplazan el criterio médico. Toda salida debe ser revisada y validada por el profesional responsable.
        </div>
      </div>
    </aside>
  );
}

Object.assign(window, { Typewriter, AIChip, AISummary, AIAlerts, AITranscription, AICopilot, TRANSCRIPCION_DEMO });
