// screens_dashboard.jsx — Dashboard + agenda médica (API-driven)
const { useState: useStateD, useEffect: useEffectD } = React;

const ESTADO_TONE = {
  "activo": "amber", "cerrado": "neutral", "alta": "green",
  "transferido": "blue", "fallecido": "red",
};

function calcEdad(fechaNacimiento) {
  if (!fechaNacimiento) return null;
  const hoy = new Date();
  const nac = new Date(fechaNacimiento);
  let edad = hoy.getFullYear() - nac.getFullYear();
  const m = hoy.getMonth() - nac.getMonth();
  if (m < 0 || (m === 0 && hoy.getDate() < nac.getDate())) edad--;
  return edad;
}

function avatarColor(id) {
  const colors = ["#2563eb", "#0d9488", "#7c3aed", "#b45309", "#be123c", "#0891b2", "#15803d", "#a86a43"];
  let hash = 0;
  for (const ch of (id || "")) hash = (hash * 31 + ch.charCodeAt(0)) | 0;
  return colors[Math.abs(hash) % colors.length];
}

function avatarText(nombres, apellidos) {
  const n = (nombres || "").trim().split(/\s+/)[0]?.[0] || "";
  const a = (apellidos || "").trim().split(/\s+/)[0]?.[0] || "";
  return (n + a).toUpperCase() || "?";
}

function AgendaRow({ item, onOpen }) {
  return (
    <button onClick={() => onOpen(item)} className="g-agendarow" style={{ display: "grid", gridTemplateColumns: "80px 40px 1fr auto", alignItems: "center", gap: 14, width: "100%", textAlign: "left", padding: "12px 14px", border: "none", borderRadius: 11, background: "transparent", cursor: "pointer", fontFamily: "inherit" }}>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)", fontFamily: "var(--mono)" }}>{(item.hora_ingreso || item.fecha_ingreso?.slice(0, 10) || "—")}</div>
        <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{item.tipo_atencion}</div>
      </div>
      <Avatar text={avatarText(item.nombres, item.apellidos)} color={avatarColor(item.patient_id)} size={38} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.apellidos} {item.nombres}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.motivo_consulta || item.diagnostico_principal || "—"}</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 5 }}>
        <Badge tone={ESTADO_TONE[item.estado] || "neutral"} dot>{item.estado}</Badge>
        <span style={{ fontSize: 11.5, color: "var(--ink-3)", fontFamily: "var(--mono)" }}>{item.record_number}</span>
      </div>
    </button>
  );
}

function Dashboard({ user, onOpenPatient, onNav }) {
  const [records, setRecords] = useStateD([]);
  const [patients, setPatients] = useStateD([]);
  const [loading, setLoading] = useStateD(true);
  const hora = new Date().getHours();
  const saludo = hora < 12 ? "Buenos días" : hora < 19 ? "Buenas tardes" : "Buenas noches";

  useEffectD(() => {
    Promise.all([
      window.apiFetch("/api/records?estado=activo&limit=20").catch(() => []),
      window.apiFetch("/api/patients?limit=5").catch(() => ({ patients: [] })),
    ]).then(([recs, pats]) => {
      setRecords(Array.isArray(recs) ? recs : []);
      setPatients(Array.isArray(pats?.patients) ? pats.patients : []);
    }).finally(() => setLoading(false));
  }, []);

  const activeRecs = records.filter((r) => r.estado === "activo");
  const closedToday = records.filter((r) => r.estado === "cerrado" || r.estado === "alta");

  const openRecord = (item) => {
    onOpenPatient({
      id: item.patient_id,
      nombres: item.nombres,
      apellidos: item.apellidos,
      cedula: item.cedula,
      _fromRecord: item,
    });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 14 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 25, fontWeight: 800, letterSpacing: "-.02em", color: "var(--ink)" }}>{saludo}, {user.corto.replace(/^(Dr\.?a?\.?\s)/i, "")}</h1>
          <p style={{ margin: "4px 0 0", fontSize: 14, color: "var(--ink-3)" }}>{new Date().toLocaleDateString("es-EC", { weekday: "long", year: "numeric", month: "long", day: "numeric" })} · {user.especialidad}</p>
        </div>
        <Btn icon="plus" size="lg" onClick={() => onNav("pacientes")}>Nueva atención</Btn>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: 14 }}>
        <Stat label="Atenciones activas" value={loading ? "…" : activeRecs.length} icon="patients" tone="blue" sub="Expedientes abiertos" />
        <Stat label="Atenciones cerradas" value={loading ? "…" : closedToday.length} icon="check" tone="green" sub="Completadas" />
        <Stat label="Total en sistema" value={loading ? "…" : records.length} icon="folder" tone="amber" sub="Expedientes totales" />
        <Stat label="Pacientes registrados" value={loading ? "…" : (patients.length > 0 ? patients.length + "+" : "0")} icon="heart" tone="neutral" sub="Ver en pacientes" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 22, alignItems: "start" }} className="g-dash-grid">
        <Card title="Atenciones activas" subtitle={loading ? "Cargando…" : `${activeRecs.length} expediente${activeRecs.length !== 1 ? "s" : ""} abierto${activeRecs.length !== 1 ? "s" : ""}`} icon="agenda" action={<Btn variant="ghost" size="sm" icon="agenda" onClick={() => onNav("agenda")}>Ver agenda</Btn>} pad={false}>
          {loading ? (
            <div style={{ padding: 32, textAlign: "center" }}>
              <span className="g-spin" style={{ width: 22, height: 22, border: "2px solid var(--line-2)", borderTopColor: "var(--accent)", borderRadius: 99, display: "inline-block" }} />
            </div>
          ) : activeRecs.length === 0 ? (
            <div style={{ padding: "28px 20px", textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
              <Icon name="agenda" size={28} style={{ opacity: .3, marginBottom: 8 }} />
              <div style={{ fontWeight: 600 }}>No hay atenciones activas</div>
              <div style={{ fontSize: 12, marginTop: 4 }}>Las atenciones abiertas aparecerán aquí.</div>
            </div>
          ) : (
            <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 2 }}>
              {activeRecs.slice(0, 8).map((it, i) => (
                <React.Fragment key={it.id}>
                  {i > 0 && <div style={{ height: 1, background: "var(--line)", margin: "0 14px" }} />}
                  <AgendaRow item={it} onOpen={openRecord} />
                </React.Fragment>
              ))}
            </div>
          )}
        </Card>

        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <Card title="Estado del sistema" icon="shield">
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <SysInfoRow label="API / Backend" val="Conectado" ok />
              <SysInfoRow label="Base de datos D1" val="Operativa" ok />
              <SysInfoRow label="Catálogo CIE-10" val="Cargado" ok />
              <SysInfoRow label="Firma digital" val="Disponible" ok />
            </div>
          </Card>

          <Card title="Pacientes recientes" icon="patients" pad={false}>
            {loading ? (
              <div style={{ padding: 24, textAlign: "center" }}>
                <span className="g-spin" style={{ width: 18, height: 18, border: "2px solid var(--line-2)", borderTopColor: "var(--accent)", borderRadius: 99, display: "inline-block" }} />
              </div>
            ) : patients.length === 0 ? (
              <div style={{ padding: "20px 16px", textAlign: "center", color: "var(--ink-3)", fontSize: 12.5 }}>No hay pacientes registrados aún.</div>
            ) : (
              <div style={{ padding: 8 }}>
                {patients.map((p) => (
                  <button key={p.id} onClick={() => onOpenPatient(p)} className="g-agendarow" style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "9px 12px", border: "none", borderRadius: 10, background: "transparent", cursor: "pointer", fontFamily: "inherit" }}>
                    <Avatar text={avatarText(p.nombres, p.apellidos)} color={avatarColor(p.id)} size={34} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{p.apellidos} {p.nombres}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{p.cedula || "Sin cédula"} · {calcEdad(p.fecha_nacimiento) !== null ? `${calcEdad(p.fecha_nacimiento)} años` : "—"}</div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}

function SysInfoRow({ label, val, ok }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
      <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{label}</span>
      <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 600, color: ok ? "var(--ok-ink)" : "var(--ink)" }}>
        {ok && <span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--ok)" }} />}{val}
      </span>
    </div>
  );
}

function AgendaScreen({ onOpenPatient }) {
  const [records, setRecords] = useStateD([]);
  const [loading, setLoading] = useStateD(true);
  const horas = ["08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00"];

  useEffectD(() => {
    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)" }}>Agenda médica</h1>
        <p style={{ margin: "4px 0 0", fontSize: 14, color: "var(--ink-3)" }}>{new Date().toLocaleDateString("es-EC", { weekday: "long", year: "numeric", month: "long", day: "numeric" })}</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="agenda" size={36} style={{ opacity: .3, marginBottom: 12 }} />
            <div style={{ fontSize: 14, fontWeight: 600 }}>No hay atenciones registradas</div>
            <div style={{ fontSize: 12.5, marginTop: 4 }}>Las atenciones creadas aparecerán en la agenda.</div>
          </div>
        </Card>
      ) : (
        <Card pad={false}>
          <div style={{ overflowX: "auto" }}>
            <div style={{ display: "grid", gridTemplateColumns: "70px 1fr" }}>
              {horas.map((h) => {
                const horaNum = h.slice(0, 2);
                const citas = records.filter((r) => (r.hora_ingreso || "").startsWith(horaNum));
                return (
                  <React.Fragment key={h}>
                    <div style={{ padding: "16px 12px", borderTop: "1px solid var(--line)", fontSize: 12, fontWeight: 600, color: "var(--ink-3)", fontFamily: "var(--mono)", textAlign: "right" }}>{h}</div>
                    <div style={{ borderTop: "1px solid var(--line)", borderLeft: "1px solid var(--line)", padding: 8, minHeight: 58, display: "flex", flexDirection: "column", gap: 6 }}>
                      {citas.map((c) => {
                        const col = avatarColor(c.patient_id);
                        return (
                          <button key={c.id} onClick={() => onOpenPatient({ id: c.patient_id, nombres: c.nombres, apellidos: c.apellidos, cedula: c.cedula })}
                            style={{ display: "flex", alignItems: "center", gap: 10, textAlign: "left", border: "none", borderRadius: 9, padding: "8px 11px", cursor: "pointer", fontFamily: "inherit", background: `color-mix(in oklch, ${col} 9%, var(--surface))`, borderLeft: `3px solid ${col}` }}>
                            <span style={{ fontFamily: "var(--mono)", fontSize: 12, fontWeight: 700, color: "var(--ink-2)" }}>{c.hora_ingreso || h}</span>
                            <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{c.apellidos} {c.nombres}</span>
                            <span style={{ fontSize: 12, color: "var(--ink-3)" }}>· {c.motivo_consulta || c.tipo_atencion}</span>
                            <span style={{ marginLeft: "auto" }}><Badge tone={ESTADO_TONE[c.estado] || "neutral"}>{c.estado}</Badge></span>
                          </button>
                        );
                      })}
                    </div>
                  </React.Fragment>
                );
              })}
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard, AgendaScreen, calcEdad, avatarColor, avatarText, ESTADO_TONE });
