// app.jsx — Shell principal, navegación, routing por estado
const { useState: useStateApp, useEffect: useEffectApp } = React;

// Helper de fetch autenticado — agrega Bearer token automáticamente
async function apiFetch(path, options = {}) {
  const token = localStorage.getItem("ciecav_token");
  const headers = { "Content-Type": "application/json", ...(options.headers || {}) };
  if (token) headers["Authorization"] = `Bearer ${token}`;
  const res = await fetch(`${window.API_BASE}${path}`, { ...options, headers });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
  return json.data;
}
window.apiFetch = apiFetch;

// Mapea el usuario del API al formato interno de la UI
function mapApiUser(apiUser, token) {
  const ROLE_MAP = {
    superadmin:       { kind: "superadmin", label: "Superadministrador",        color: "#4f46e5" },
    admin:            { kind: "admin",       label: "Administrador del sistema", color: "#334155" },
    doctor:           { kind: "clinico",     label: "Médico tratante",           color: "#2563eb" },
    surgeon:          { kind: "clinico",     label: "Cirujano",                  color: "#be123c" },
    anesthesiologist: { kind: "clinico",     label: "Anestesiólogo",             color: "#7c3aed" },
    reception:        { kind: "clinico",     label: "Recepción / Admisión",      color: "#b45309" },
    nurse:            { kind: "clinico",     label: "Enfermería",                color: "#0891b2" },
    lab:              { kind: "clinico",     label: "Laboratorio clínico",       color: "#15803d" },
  };
  const rm = ROLE_MAP[apiUser.role] || { kind: "clinico", label: apiUser.role, color: "#2563eb" };
  const partes = (apiUser.name || "").trim().split(/\s+/).filter((p) => !/^(dr\.?a?\.?|dra\.?|lcdo?\.?|blgo?\.?)$/i.test(p));
  const iniciales = ((partes[0]?.[0] || "") + (partes[1]?.[0] || "")).toUpperCase() || "??";
  const corto = partes.length >= 2 ? `${partes[0][0]}. ${partes[partes.length - 1]}` : (apiUser.name || "Usuario");
  return {
    id: apiUser.id,
    kind: rm.kind,
    apiRole: apiUser.role || 'doctor',
    label: rm.label,
    token,
    user: {
      nombre: apiUser.name || "Usuario",
      corto,
      especialidad: apiUser.specialty || rm.label,
      registro: apiUser.license_number || "—",
      iniciales,
      color: rm.color,
    },
  };
}
window.mapApiUser = mapApiUser;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#a86a43",
  "density": "regular",
  "dark": false,
  "font": "IBM Plex Sans",
  "showAI": true
}/*EDITMODE-END*/;

const ACCENTS = {
  "#a86a43": { soft: "#f4ebe1", ink: "#7c4f2d" },
  "#2563eb": { soft: "#e8f0fe", ink: "#1d4ed8" },
  "#0d9488": { soft: "#d7f3ef", ink: "#0f766e" },
  "#4f46e5": { soft: "#e9e7fd", ink: "#4338ca" },
  "#0369a1": { soft: "#dcecf8", ink: "#075985" },
};

const NAV = [
  { id: "dashboard", label: "Inicio", icon: "dashboard" },
  { id: "pacientes", label: "Pacientes", icon: "patients" },
  { id: "agenda", label: "Agenda", icon: "agenda" },
  { id: "documentos", label: "Documentos", icon: "folder" },
  { id: "auditoria", label: "Auditoría", icon: "shield" },
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useStateApp({ screen: "dashboard" });
  const [auth, setAuth] = useStateApp(null);
  const [authLoading, setAuthLoading] = useStateApp(true);
  const [copilot, setCopilot] = useStateApp(false);
  const [copilotPac, setCopilotPac] = useStateApp(null);
  const [newAt, setNewAt] = useStateApp(null);
  const [exped, setExped] = useStateApp(null);
  const [injected, setInjected] = useStateApp(null);

  useEffectApp(() => {
    const token = localStorage.getItem("ciecav_token");
    if (!token) { setAuthLoading(false); return; }
    fetch(`${window.API_BASE}/api/auth/me`, {
      headers: { "Authorization": `Bearer ${token}` },
    })
      .then((r) => r.ok ? r.json() : Promise.reject())
      .then((json) => { setAuth(mapApiUser(json.data, token)); })
      .catch(() => { localStorage.removeItem("ciecav_token"); })
      .finally(() => setAuthLoading(false));
  }, []);

  useEffectApp(() => {
    const a = ACCENTS[t.accent] || ACCENTS["#2563eb"];
    const r = document.documentElement;
    r.style.setProperty("--accent", t.accent);
    r.style.setProperty("--accent-soft", a.soft);
    r.style.setProperty("--accent-ink", a.ink);
    r.dataset.theme = t.dark ? "dark" : "light";
    r.dataset.density = t.density;
    r.style.setProperty("--font", `'${t.font}', system-ui, sans-serif`);
  }, [t.accent, t.dark, t.density, t.font]);

  if (authLoading) return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)", flexDirection: "column", gap: 14 }}>
      <span className="g-spin" style={{ width: 32, height: 32, border: "3px solid var(--line-2)", borderTopColor: "var(--accent)", borderRadius: 99 }} />
      <span style={{ fontSize: 13, color: "var(--ink-3)" }}>Verificando sesión…</span>
    </div>
  );

  const doLogin = (r) => {
    setAuth(r);
    setView({ screen: (r.kind === "admin" || r.kind === "superadmin") ? "admin" : "dashboard" });
    window.scrollTo(0, 0);
  };
  const logout = () => {
    const token = auth?.token;
    if (token) fetch(`${window.API_BASE}/api/auth/logout`, { method: "POST", headers: { "Authorization": `Bearer ${token}` } }).catch(() => {});
    localStorage.removeItem("ciecav_token");
    setAuth(null);
    setView({ screen: "dashboard" });
    setCopilot(false);
  };

  if (!auth) return <Login onLogin={doLogin} />;

  const role = auth;
  const user = role.user;
  const isAdmin = role.kind === "admin" || role.kind === "superadmin";
  window.CURRENT_USER = user;

  const go = (screen, extra = {}) => { setView({ screen, ...extra }); window.scrollTo(0, 0); };
  const openPatient = (p) => go("paciente", { paciente: p });
  const openCopilot = (p) => { setCopilotPac(p || copilotPac || view.paciente); setCopilot(true); };
  const openExpediente = (p) => setExped(p);

  const FORM_SCREEN_MAP = {
    emergencia_08: "form008", evoluciones: "form005", epicrisis: "form005",
    pre_1: "anestesia", pre_2: "anestesia",
    trans_018a_anv: "anestesia", trans_018a_rev: "anestesia",
    "019_post_anv": "anestesia", "019_post_rev": "anestesia",
  };

  const openForm = (formType, paciente) => {
    setNewAt(null);
    const map = { "008": "form008", "005": "form005", "018": "anestesia", "018A": "anestesia", "024": "consent", "006": "form005" };
    go(map[formType.id] || "form008", { paciente, formType });
  };

  const editForm = (formType, record) => {
    const screen = FORM_SCREEN_MAP[formType] || "form-generic";
    go(screen, { paciente: view.paciente, record, formType });
  };

  return (
    <div data-density={t.density} style={{ display: "flex", minHeight: "100vh", background: "var(--bg)", color: "var(--ink)", fontFamily: "var(--font)" }}>
      {/* Sidebar */}
      <aside className="g-sidebar" style={{ width: 230, flexShrink: 0, background: "var(--surface)", borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", position: "sticky", top: 0, height: "100vh" }}>
        <div style={{ padding: "18px 16px 14px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ background: "#fff", borderRadius: 12, padding: "12px 10px", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "var(--shadow)" }}>
            <img src="assets/ciecav-logo.svg" alt="CIECAV" style={{ width: "100%", maxWidth: 168, height: "auto", display: "block" }} />
          </div>
          <div style={{ fontSize: 10, color: "var(--ink-3)", fontWeight: 700, letterSpacing: ".1em", textAlign: "center", marginTop: 9 }}>HISTORIA CLÍNICA ELECTRÓNICA</div>
        </div>
        <nav style={{ padding: "8px 12px", display: "flex", flexDirection: "column", gap: 2, flex: 1 }}>
          {(isAdmin ? window.ADMIN_NAV : NAV).map((n) => {
            const active = view.screen === n.id || (n.id === "pacientes" && (view.screen === "paciente" || view.screen === "nuevo-paciente" || view.screen === "atencion" || view.screen.startsWith("form") || view.screen === "anestesia" || view.screen === "consent" || view.screen === "form-generic"));
            return (
              <button key={n.id} onClick={() => go(n.id)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 13px", borderRadius: 10, border: "none", cursor: "pointer", fontFamily: "inherit", fontSize: 14, fontWeight: 600, textAlign: "left",
                background: active ? "var(--accent-soft)" : "transparent", color: active ? "var(--accent-ink)" : "var(--ink-2)" }}>
                <Icon name={n.icon} size={19} /> {n.label}
              </button>
            );
          })}
        </nav>
        {!isAdmin && (
          <div style={{ padding: 12 }}>
            <button onClick={() => openCopilot(view.paciente)} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "12px 13px", borderRadius: 12, border: "none", cursor: "pointer", fontFamily: "inherit", background: "linear-gradient(135deg, color-mix(in oklch,#7c3aed 12%,transparent), color-mix(in oklch,var(--accent) 12%,transparent))", color: "#6d28d9", fontWeight: 700, fontSize: 13.5 }}>
              <Icon name="ai" size={19} /> Copiloto clínico
            </button>
          </div>
        )}
        <div style={{ padding: "12px 14px", borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar text={user.iniciales} color={user.color} size={36} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user.corto}</div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{role.label}</div>
          </div>
          <button onClick={logout} title="Cerrar sesión" className="g-iconbtn" style={{ border: "1px solid var(--line)", background: "var(--surface)", borderRadius: 9, padding: 7, cursor: "pointer", color: "var(--ink-3)", display: "flex" }}><Icon name="logout" size={17} /></button>
        </div>
      </aside>

      {/* Main */}
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        <header className="g-topbar" style={{ position: "sticky", top: 0, zIndex: 40, background: "color-mix(in oklch, var(--surface) 85%, transparent)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line)", padding: "11px 28px", display: "flex", alignItems: "center", gap: 16 }}>
          <button className="g-mobnav g-iconbtn" onClick={() => go("dashboard")} style={{ display: "none", border: "none", background: "transparent", cursor: "pointer", color: "var(--accent-ink)", alignItems: "center", gap: 8, fontWeight: 800, fontFamily: "inherit", fontSize: 16, letterSpacing: ".02em" }}>
            <Icon name="heart" size={20} fill /> CIECAV
          </button>
          {!isAdmin ? (
            <button onClick={() => go("pacientes")} style={{ flex: 1, maxWidth: 440, display: "flex", alignItems: "center", gap: 10, padding: "9px 14px", borderRadius: 10, border: "1px solid var(--line)", background: "var(--field)", color: "var(--ink-3)", cursor: "pointer", fontFamily: "inherit", fontSize: 13.5 }}>
              <Icon name="search" size={17} /> Buscar paciente por cédula, HC o nombre…
            </button>
          ) : (
            <div className="g-hide-mobile" style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)" }}>
              {role.kind === "superadmin" ? "Superadministración del sistema" : "Administración del sistema"}
            </div>
          )}
          <div style={{ flex: 1 }} className="g-hide-mobile" />
          <div className="g-hide-mobile" style={{ display: "flex", alignItems: "center", gap: 9, padding: "5px 6px 5px 13px", borderRadius: 99, border: "1px solid var(--line)", background: "var(--surface)" }}>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)", lineHeight: 1.15 }}>{user.corto}</div>
              <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{role.label}</div>
            </div>
            <Avatar text={user.iniciales} color={user.color} size={30} />
          </div>
          <button onClick={logout} title="Cerrar sesión" className="g-iconbtn" style={{ border: "1px solid var(--line)", background: "var(--surface)", borderRadius: 10, padding: 9, cursor: "pointer", color: "var(--ink-2)", display: "flex" }}>
            <Icon name="logout" size={18} />
          </button>
          <button className="g-iconbtn" style={{ position: "relative", border: "1px solid var(--line)", background: "var(--surface)", borderRadius: 10, padding: 9, cursor: "pointer", color: "var(--ink-2)", display: "flex" }}>
            <Icon name="bell" size={18} />
            <span style={{ position: "absolute", top: 7, right: 8, width: 7, height: 7, borderRadius: 99, background: "var(--danger)", border: "1.5px solid var(--surface)" }} />
          </button>
        </header>

        <main style={{ flex: 1, padding: 28, maxWidth: 1320, width: "100%", margin: "0 auto", boxSizing: "border-box" }}>
          {view.screen === "dashboard" && <Dashboard user={user} onOpenPatient={openPatient} onNav={go} />}
          {view.screen === "pacientes" && <PatientSearch onOpen={openPatient} onNuevo={() => go("nuevo-paciente")} />}
          {view.screen === "nuevo-paciente" && <PatientCreate onBack={() => go("pacientes")} onCreated={(p) => go("paciente", { paciente: p })} />}
          {view.screen === "agenda" && <AgendaScreen onOpenPatient={openPatient} />}
          {view.screen === "documentos" && <DocsScreen />}
          {view.screen === "auditoria" && <AuditScreen />}
          {view.screen === "paciente" && <PatientDetail paciente={view.paciente} onBack={() => go("pacientes")} onOpenCopilot={() => openCopilot(view.paciente)} onNewAtencion={(p) => setNewAt(p)} onOpenExpediente={openExpediente} onOpenAtencion={(a) => go("atencion", { atencion: a, paciente: view.paciente })} />}
          {view.screen === "atencion" && <AtencionView atencion={view.atencion} paciente={view.paciente} role={role} onBack={() => go("paciente", { paciente: view.paciente })} onOpenExpediente={() => openExpediente(view.paciente)} onEditForm={editForm} />}
          {view.screen === "form008" && <FormEmergencia paciente={view.paciente} record={view.record} onBack={() => view.record ? go("atencion", { atencion: view.record, paciente: view.paciente }) : go("paciente", { paciente: view.paciente })} />}
          {view.screen === "form005" && <FormEvolucion paciente={view.paciente} record={view.record} onBack={() => view.record ? go("atencion", { atencion: view.record, paciente: view.paciente }) : go("paciente", { paciente: view.paciente })} onOpenCopilot={() => openCopilot(view.paciente)} injectedText={injected} onConsumeInjected={() => setInjected(null)} />}
          {view.screen === "form-generic" && <GenericFormScreen paciente={view.paciente} record={view.record} formType={view.formType} onBack={() => view.record ? go("atencion", { atencion: view.record, paciente: view.paciente }) : go("paciente", { paciente: view.paciente })} />}
          {view.screen === "anestesia" && <FormAnestesia paciente={view.paciente} onBack={() => go("paciente", { paciente: view.paciente })} faseInicial={view.formType && view.formType.id === "018A" ? "trans" : "pre"} />}
          {view.screen === "consent" && <FormConsentimiento paciente={view.paciente} onBack={() => go("paciente", { paciente: view.paciente })} />}
          {view.screen === "admin" && <AdminDashboard onNav={go} role={role} />}
          {view.screen === "usuarios" && <UserManagement role={role} />}
          {view.screen === "roles" && <RolesPermissions />}
          {view.screen === "establecimiento" && <Establecimiento />}
        </main>
      </div>

      {t.showAI && <AICopilot paciente={copilotPac} open={copilot} onClose={() => setCopilot(false)} onInsertText={(txt) => { setInjected(txt); setCopilot(false); if (view.screen !== "form005") go("form005", { paciente: copilotPac }); }} />}

      <NewAtencionModal open={!!newAt} onClose={() => setNewAt(null)} paciente={newAt}
        onSelect={(record) => { setNewAt(null); go("atencion", { atencion: record, paciente: newAt }); }} />
      <ExpedienteModal open={!!exped} onClose={() => setExped(null)} paciente={exped} />

      <TweaksPanel>
        <TweakSection label="Apariencia" />
        <TweakColor label="Color de acento" value={t.accent} options={Object.keys(ACCENTS)} onChange={(v) => setTweak("accent", v)} />
        <TweakToggle label="Modo oscuro" value={t.dark} onChange={(v) => setTweak("dark", v)} />
        <TweakRadio label="Densidad" value={t.density} options={["compact", "regular", "comfy"]} onChange={(v) => setTweak("density", v)} />
        <TweakSelect label="Tipografía" value={t.font} options={["IBM Plex Sans", "Public Sans", "Source Sans 3"]} onChange={(v) => setTweak("font", v)} />
        <TweakSection label="Funcionalidad" />
        <TweakToggle label="Panel de IA (copiloto)" value={t.showAI} onChange={(v) => setTweak("showAI", v)} />
      </TweaksPanel>
    </div>
  );
}

// ---- Pantalla Documentos — carga desde API ----
function DocsScreen() {
  const [records, setRecords] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    window.apiFetch("/api/records?limit=50")
      .then((data) => setRecords(Array.isArray(data) ? data : []))
      .catch(() => setRecords([]))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <div>
        <h1 style={{ margin: 0, fontSize: 23, fontWeight: 800, letterSpacing: "-.02em", color: "var(--ink)" }}>Gestión documental</h1>
        <p style={{ margin: "4px 0 0", fontSize: 14, color: "var(--ink-3)" }}>Formularios y expedientes clínicos del sistema</p>
      </div>
      {loading ? (
        <div style={{ textAlign: "center", padding: 48, color: "var(--ink-3)" }}>
          <span className="g-spin" style={{ width: 24, height: 24, border: "2px solid var(--line-2)", borderTopColor: "var(--accent)", borderRadius: 99, display: "inline-block" }} />
        </div>
      ) : records.length === 0 ? (
        <Card>
          <div style={{ textAlign: "center", padding: 40, color: "var(--ink-3)" }}>
            <Icon name="folder" size={36} style={{ opacity: .35, marginBottom: 12 }} />
            <div style={{ fontSize: 14, fontWeight: 600 }}>No hay documentos registrados aún.</div>
            <div style={{ fontSize: 12.5, marginTop: 4 }}>Los formularios firmados aparecerán aquí una vez que se creen atenciones.</div>
          </div>
        </Card>
      ) : (
        <Card pad={false}>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
              <thead><tr>{["Expediente", "Paciente", "Tipo", "Fecha", "Estado"].map((c) => <th key={c} style={{ textAlign: "left", padding: "12px 16px", fontSize: 11.5, fontWeight: 700, color: "var(--ink-3)", textTransform: "uppercase", borderBottom: "1px solid var(--line)" }}>{c}</th>)}</tr></thead>
              <tbody>
                {records.map((r) => (
                  <tr key={r.id} className="g-trow">
                    <td style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)" }}><div style={{ display: "flex", alignItems: "center", gap: 9 }}><Icon name="pdf" size={16} style={{ color: "var(--danger)" }} /><span style={{ fontFamily: "var(--mono)", fontWeight: 600, color: "var(--ink)" }}>{r.record_number}</span></div></td>
                    <td style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", color: "var(--ink-2)" }}>{r.apellidos} {r.nombres}</td>
                    <td style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)" }}><Badge tone="blue">{r.tipo_atencion}</Badge></td>
                    <td style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", color: "var(--ink-2)", fontFamily: "var(--mono)", fontSize: 12.5 }}>{r.fecha_ingreso?.slice(0, 10)}</td>
                    <td style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)" }}><Badge tone={r.estado === "activo" ? "amber" : "green"} dot>{r.estado}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  );
}

// ---- Auditoría ----
function AuditScreen() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <div>
        <h1 style={{ margin: 0, fontSize: 23, fontWeight: 800, letterSpacing: "-.02em", color: "var(--ink)" }}>Auditoría y trazabilidad</h1>
        <p style={{ margin: "4px 0 0", fontSize: 14, color: "var(--ink-3)" }}>Registro inmutable de accesos y acciones sobre la HCE</p>
      </div>
      <Card>
        <div style={{ textAlign: "center", padding: 40, color: "var(--ink-3)" }}>
          <Icon name="shield" size={36} style={{ opacity: .35, marginBottom: 12 }} />
          <div style={{ fontSize: 14, fontWeight: 600 }}>Los registros de auditoría se mostrarán aquí.</div>
          <div style={{ fontSize: 12.5, marginTop: 4 }}>Cada acción sobre pacientes, formularios y sesiones queda registrada en la base de datos.</div>
        </div>
      </Card>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
