// ROCA GOLF — Lista de OCs, Insumos, Proveedores, Historial (conectado a API)

// ───── ORDENES DE COMPRA ─────
function OCListView({ onNav }) {
  const { ordenes, proyectos, familias, alerts, loading } = useAppData();

  const [filters, setFilters] = useState({
    folio: "", prov: "", proy: "", status: "", flujo: "", prior: ""
  });

  const alertCount = alerts.filter(a => a.level !== "ok").length;

  // Nombre de proveedor/proyecto: usa el campo del API si existe, si no busca en lista
  const getProv = (o) => o.proveedor_nombre || nombreProveedor(o.proveedorid);
  const getProy = (o) => o.proyecto_nombre  || nombreProyecto(o.proyectoid);

  const filtered = ordenes.filter(o => {
    if (filters.folio && !String(o.folio).includes(filters.folio)) return false;
    if (filters.prov) {
      if (!getProv(o).toLowerCase().includes(filters.prov.toLowerCase())) return false;
    }
    if (filters.proy && o.proyectoid !== +filters.proy) return false;
    if (filters.status && o.statuspago !== filters.status) return false;
    if (filters.flujo && o.statusflujo !== filters.flujo) return false;
    if (filters.prior && o.prioridad !== filters.prior) return false;
    return true;
  });

  return (
    <div className="rg-app">
      <Sidebar active="oc" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Compras / Órdenes de compra" title="Órdenes de compra"
          actions={<button className="rg-btn primary">{Icon.plus()} Nueva OC</button>}/>
        <div className="rg-content">
          <div className="rg-filter-bar">
            <div className="rg-field">
              <label>Folio</label>
              <input className="rg-input" placeholder="Número…"
                value={filters.folio} onChange={e => setFilters({...filters, folio: e.target.value})}/>
            </div>
            <div className="rg-field">
              <label>Proveedor</label>
              <input className="rg-input" placeholder="Nombre…"
                value={filters.prov} onChange={e => setFilters({...filters, prov: e.target.value})}/>
            </div>
            <div className="rg-field">
              <label>Proyecto</label>
              <select className="rg-select" value={filters.proy}
                onChange={e => setFilters({...filters, proy: e.target.value})}>
                <option value="">Todos</option>
                {proyectos.map(p => <option key={p.id} value={p.id}>{p.nombre}</option>)}
              </select>
            </div>
            <div className="rg-field">
              <label>Status pago</label>
              <select className="rg-select" value={filters.status}
                onChange={e => setFilters({...filters, status: e.target.value})}>
                <option value="">Todos</option>
                <option value="PAGADO">Pagado</option>
                <option value="PAGO_PARCIAL">Parcial</option>
                <option value="PENDIENTE">Pendiente</option>
              </select>
            </div>
            <div className="rg-field">
              <label>Flujo</label>
              <select className="rg-select" value={filters.flujo}
                onChange={e => setFilters({...filters, flujo: e.target.value})}>
                <option value="">Todos</option>
                <option value="NUEVO">Nuevo</option>
                <option value="CON_PRIORIDAD">Con prioridad</option>
                <option value="AUTORIZADA">Autorizada</option>
              </select>
            </div>
            <div className="rg-field">
              <label>Prioridad</label>
              <select className="rg-select" value={filters.prior}
                onChange={e => setFilters({...filters, prior: e.target.value})}>
                <option value="">Todas</option>
                <option value="NORMAL">Normal</option>
                <option value="URGENTE">Urgente</option>
                <option value="CRITICO">Crítico</option>
                <option value="AUTORIZADO">Autorizado</option>
              </select>
            </div>
            <button className="rg-btn primary" onClick={() => setFilters({folio:"",prov:"",proy:"",status:"",flujo:"",prior:""})}>
              Limpiar
            </button>
          </div>

          <div className="rg-card">
            <div className="rg-card-header">
              <div>
                <h3>{filtered.length} órdenes de compra</h3>
                <div className="sub">Total {filtered.length} de {ordenes.length}</div>
              </div>
              <div className="rg-row">
                <button className="rg-btn">{Icon.excel()} Exportar</button>
              </div>
            </div>
            {filtered.length === 0 && !loading ? (
              <div style={{
                padding: "48px 24px", textAlign: "center",
                color: "var(--rg-muted)", fontSize: 13
              }}>
                {Icon.oc(28)}
                <p style={{ marginTop: 12 }}>
                  No se encontraron órdenes con los filtros aplicados.
                </p>
              </div>
            ) : (
              <div style={{ overflowX: "auto" }}>
                <table className="rg-table">
                  <thead>
                    <tr>
                      <th>Folio</th><th>Fecha</th><th>Proyecto</th><th>Proveedor</th>
                      <th className="num">Total</th><th className="num">Pendiente</th>
                      <th>Status</th><th>Flujo</th><th>Prioridad</th><th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map(o => (
                      <tr key={o.id}>
                        <td><span className="folio">{fmtFolio(o.folio)}</span></td>
                        <td className="rg-mono" style={{ fontSize: 11.5, color: "var(--rg-muted)" }}>
                          {fmtFecha(o.fecha)}
                        </td>
                        <td title={getProy(o)}
                          style={{ maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {getProy(o)}
                        </td>
                        <td title={getProv(o)}
                          style={{ maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {getProv(o)}
                        </td>
                        <td className="num">
                          {o.moneda === "USD" ? "USD " : "$"}{fmtMoney(o.total)}
                        </td>
                        <td className="num" style={{
                          color: o.montopendiente > 0 ? "var(--rg-flag-over)" : "var(--rg-muted)"
                        }}>
                          {o.montopendiente > 0 ? "$" + fmtMoney(o.montopendiente) : "—"}
                        </td>
                        <td><StatusPagoBadge status={o.statuspago}/></td>
                        <td><FlujoBadge f={o.statusflujo}/></td>
                        <td><PrioridadBadge p={o.prioridad}/></td>
                        <td>
                          <div className="actions">
                            <button className="rg-icon-btn" title="Ver">{Icon.eye()}</button>
                            <button className="rg-icon-btn" title="Editar">{Icon.edit()}</button>
                            <button className="rg-icon-btn" title="Más">{Icon.more()}</button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
            <div className="rg-paginate">
              <span>Mostrando 1–{filtered.length} de {filtered.length}</span>
              <div className="pg">
                <button disabled>‹</button>
                <button className="active">1</button>
                <button disabled>›</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

// ───── INSUMOS ─────
function InsumosView({ onNav }) {
  const { insumos, familias, alerts, loading } = useAppData();

  const [familiaFiltro, setFamiliaFiltro] = useState("");
  const [q, setQ]                         = useState("");
  const [verInactivos, setVerInactivos]   = useState(false);

  const alertCount = alerts.filter(a => a.level !== "ok").length;

  const familiasUnicas = useMemo(() => {
    const map = {};
    insumos.forEach(i => { map[i.codigofamilia] = i.nombrefamilia; });
    return Object.entries(map).sort(([a], [b]) => a.localeCompare(b));
  }, [insumos]);

  const filtered = insumos.filter(i => {
    const esActivo = Boolean(i.activo);
    if (!verInactivos && !esActivo) return false;
    if (verInactivos  &&  esActivo) return false;
    if (familiaFiltro && i.codigofamilia !== familiaFiltro) return false;
    if (q) {
      const ql = q.toLowerCase();
      if (!i.clave.toLowerCase().includes(ql) && !i.descripcion.toLowerCase().includes(ql)) return false;
    }
    return true;
  });

  return (
    <div className="rg-app">
      <Sidebar active="catalog" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Catálogos / Insumos" title="Catálogo de insumos"
          actions={<button className="rg-btn primary">{Icon.plus()} Nuevo insumo</button>}/>
        <div className="rg-content">
          <div className="rg-filter-bar" style={{ gridTemplateColumns: "1.4fr 220px 220px auto" }}>
            <div className="rg-field">
              <label>Buscar</label>
              <input className="rg-input" placeholder="Clave o descripción…"
                value={q} onChange={e => setQ(e.target.value)}/>
            </div>
            <div className="rg-field">
              <label>Familia</label>
              <select className="rg-select" value={familiaFiltro}
                onChange={e => setFamiliaFiltro(e.target.value)}>
                <option value="">Todas</option>
                {familiasUnicas.map(([cod, nom]) =>
                  <option key={cod} value={cod}>{cod} · {nom}</option>
                )}
              </select>
            </div>
            <div className="rg-field">
              <label>Estado</label>
              <div className="rg-tabs">
                <button className={"rg-tab" + (!verInactivos ? " active" : "")}
                  onClick={() => setVerInactivos(false)}>Activos</button>
                <button className={"rg-tab" + (verInactivos ? " active" : "")}
                  onClick={() => setVerInactivos(true)}>Inactivos</button>
              </div>
            </div>
            <button className="rg-btn">{Icon.excel()} Exportar</button>
          </div>

          <div className="rg-card">
            <div className="rg-card-header">
              <div>
                <h3>{filtered.length} insumos</h3>
                <div className="sub">Catálogo {verInactivos ? "inactivo" : "activo"}</div>
              </div>
            </div>
            <div className="rg-ins-row" style={{
              background: "var(--rg-cream)", padding: "9px 18px",
              fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase",
              color: "var(--rg-muted)", fontWeight: 500
            }}>
              <span>Clave</span><span>Descripción</span><span>Familia</span>
              <span>Usos</span><span>Estado</span><span style={{ textAlign: "right" }}>Acciones</span>
            </div>

            {filtered.length === 0 && !loading ? (
              <div style={{
                padding: "40px 24px", textAlign: "center",
                color: "var(--rg-muted)", fontSize: 13
              }}>
                {Icon.catalog(28)}
                <p style={{ marginTop: 12 }}>Sin insumos que coincidan con la búsqueda.</p>
              </div>
            ) : filtered.map(i => (
              <div className="rg-ins-row" key={i.id}>
                <span className="clave">{i.clave}</span>
                <span title={i.descripcion} style={{
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
                }}>{i.descripcion}</span>
                <span className="rg-fam-chip">
                  <span className="swatch" style={{
                    background: FAMILY_COLORS[parseInt(i.codigofamilia, 10) % FAMILY_COLORS.length]
                  }}/>
                  {i.codigofamilia} · {i.nombrefamilia}
                </span>
                <span className="rg-mono" style={{ fontSize: 11, color: "var(--rg-muted)" }}>
                  {i.usos || 0} OCs
                </span>
                <span className="rg-pill" style={{
                  background: i.activo ? "rgba(45,106,68,0.12)" : "var(--rg-cream)",
                  color:      i.activo ? "var(--rg-flag-ok)"    : "var(--rg-muted)"
                }}>
                  <span className="rg-dot" style={{
                    background: i.activo ? "var(--rg-flag-ok)" : "var(--rg-muted)"
                  }}/>
                  {i.activo ? "Activo" : "Inactivo"}
                </span>
                <div className="actions">
                  <button className="rg-icon-btn" title="Editar">{Icon.edit()}</button>
                  <button className="rg-icon-btn danger" title="Desactivar">{Icon.x()}</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </main>
    </div>
  );
}

// ───── PROVEEDORES ─────
function ProveedoresView({ onNav }) {
  const { proveedores, alerts, loading } = useAppData();

  const [tab, setTab] = useState("activos");
  const [q, setQ]     = useState("");

  const alertCount = alerts.filter(a => a.level !== "ok").length;

  const activos   = proveedores.filter(p => p.activo);
  const inactivos = proveedores.filter(p => !p.activo);
  const base      = tab === "activos" ? activos : inactivos;

  const list = base.filter(p => {
    if (!q) return true;
    const ql = q.toLowerCase();
    return (
      p.nombre.toLowerCase().includes(ql) ||
      (p.rfc     || "").toLowerCase().includes(ql) ||
      (p.contacto|| "").toLowerCase().includes(ql) ||
      (p.email   || "").toLowerCase().includes(ql)
    );
  }).sort((a, b) => (b.monto || 0) - (a.monto || 0));

  return (
    <div className="rg-app">
      <Sidebar active="vendors" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Catálogos / Proveedores" title="Proveedores"
          actions={<button className="rg-btn primary">{Icon.plus()} Nuevo proveedor</button>}/>
        <div className="rg-content">
          <div className="rg-row" style={{ gap: 12 }}>
            <div className="rg-tabs">
              <button className={"rg-tab" + (tab === "activos" ? " active" : "")}
                onClick={() => setTab("activos")}>
                Activos ({activos.length})
              </button>
              <button className={"rg-tab" + (tab === "inactivos" ? " active" : "")}
                onClick={() => setTab("inactivos")}>
                Inactivos ({inactivos.length})
              </button>
            </div>
            <div className="rg-spacer"/>
            <div className="rg-search" style={{ width: 280 }}>
              {Icon.search()}
              <input
                placeholder="Buscar por nombre, RFC o contacto…"
                value={q} onChange={e => setQ(e.target.value)}
              />
            </div>
            <button className="rg-btn">{Icon.excel()} Exportar</button>
          </div>

          <div className="rg-card">
            <div className="rg-card-header">
              <div>
                <h3>Cartera de proveedores</h3>
                <div className="sub">
                  {list.length} {tab === "activos" ? "activos" : "inactivos"} · ordenados por monto ejercido
                </div>
              </div>
            </div>

            {list.length === 0 && !loading ? (
              <div style={{
                padding: "40px 24px", textAlign: "center",
                color: "var(--rg-muted)", fontSize: 13
              }}>
                {Icon.vendors(28)}
                <p style={{ marginTop: 12 }}>Sin proveedores que coincidan con la búsqueda.</p>
              </div>
            ) : (
              <div className="rg-vendor-grid">
                {list.map(p => (
                  <div className="rg-vendor-card" key={p.id}>
                    <div className="rg-vendor-init">
                      {p.nombre.split(" ").slice(0, 2).map(w => w[0]).join("").toUpperCase()}
                    </div>
                    <div className="rg-vendor-body">
                      <div className="rg-row" style={{ justifyContent: "space-between" }}>
                        <div style={{ minWidth: 0 }}>
                          <div className="nm" title={p.nombre}
                            style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 220 }}>
                            {p.nombre}
                          </div>
                          <div className="meta">
                            {p.rfc || "Sin RFC"} · {p.banco || "—"} · {p.moneda || "MXN"}
                          </div>
                        </div>
                        <div className="actions">
                          <button className="rg-icon-btn" title="Ver">{Icon.eye()}</button>
                          <button className="rg-icon-btn" title="Editar">{Icon.edit()}</button>
                        </div>
                      </div>
                      <div className="stats">
                        <span><span className="v">{p.ocs || 0}</span> <span className="l">OCs</span></span>
                        <span>
                          <span className="v">${fmtMoney(p.monto || 0)}</span>{" "}
                          <span className="l">{p.moneda || "MXN"}</span>
                        </span>
                        {p.contacto && <span className="l" title={p.email}>{p.contacto}</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}

// ───── HISTORIAL ─────
function HistorialView({ onNav }) {
  const { historial, alerts, loading } = useAppData();

  const [filter, setFilter] = useState({ accion: "", tabla: "" });

  const alertCount = alerts.filter(a => a.level !== "ok").length;

  // Normaliza el campo descripción (API usa 'descripcion', mock usaba 'desc')
  const getDesc = (h) => h.descripcion || h.desc || "—";

  const filtered = historial.filter(h => {
    if (filter.accion && !h.accion.startsWith(filter.accion)) return false;
    if (filter.tabla && (h.tabla || h.tablaafectada || "") !== filter.tabla) return false;
    return true;
  });

  const accionMeta = (a) => {
    if (a.startsWith("CREAR"))   return { c: "var(--rg-flag-ok)",   bg: "rgba(45,106,68,0.12)",  ic: Icon.plus   };
    if (a.startsWith("EDITAR"))  return { c: "#1976d2",             bg: "rgba(25,118,210,0.10)", ic: Icon.edit   };
    if (a.startsWith("ELIMINAR"))return { c: "var(--rg-flag-over)", bg: "rgba(178,34,34,0.10)",  ic: Icon.x      };
    if (a.startsWith("PAGO"))    return { c: "var(--rg-flag-ok)",   bg: "rgba(45,106,68,0.12)",  ic: Icon.budget };
    if (a.startsWith("LOGIN"))   return { c: "var(--rg-muted)",     bg: "var(--rg-cream)",       ic: Icon.eye    };
    if (a.startsWith("LOGOUT"))  return { c: "var(--rg-muted)",     bg: "var(--rg-cream)",       ic: Icon.history};
    if (a.startsWith("CAMBIO") || a.startsWith("CAMBIAR"))
                                  return { c: "var(--rg-flag-warn)", bg: "rgba(212,160,23,0.12)", ic: Icon.history};
    return { c: "var(--rg-muted)", bg: "var(--rg-cream)", ic: Icon.history };
  };

  return (
    <div className="rg-app">
      <Sidebar active="history" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Catálogos / Historial" title="Historial de acciones"
          actions={<button className="rg-btn">{Icon.excel()} Exportar</button>}/>
        <div className="rg-content">
          <div className="rg-filter-bar"
            style={{ gridTemplateColumns: "1.4fr 200px 200px 130px 130px auto" }}>
            <div className="rg-field">
              <label>Buscar</label>
              <input className="rg-input" placeholder="Descripción o acción…"/>
            </div>
            <div className="rg-field">
              <label>Acción</label>
              <select className="rg-select" value={filter.accion}
                onChange={e => setFilter({...filter, accion: e.target.value})}>
                <option value="">Todas</option>
                <option value="CREAR">CREAR</option>
                <option value="EDITAR">EDITAR</option>
                <option value="ELIMINAR">ELIMINAR</option>
                <option value="PAGO">PAGO</option>
                <option value="LOGIN">LOGIN</option>
                <option value="LOGOUT">LOGOUT</option>
                <option value="CAMBIAR">CAMBIAR</option>
              </select>
            </div>
            <div className="rg-field">
              <label>Tabla</label>
              <select className="rg-select" value={filter.tabla}
                onChange={e => setFilter({...filter, tabla: e.target.value})}>
                <option value="">Todas</option>
                <option value="ordenes_compra">ordenes_compra</option>
                <option value="oc_pagos">oc_pagos</option>
                <option value="catalogo_insumos">catalogo_insumos</option>
                <option value="proveedores">proveedores</option>
                <option value="usuarios">usuarios</option>
                <option value="rol_permisos">rol_permisos</option>
              </select>
            </div>
            <div className="rg-field">
              <label>Desde</label>
              <input className="rg-input" type="date"/>
            </div>
            <div className="rg-field">
              <label>Hasta</label>
              <input className="rg-input" type="date"/>
            </div>
            <button className="rg-btn primary"
              onClick={() => setFilter({ accion: "", tabla: "" })}>
              {Icon.search()} Limpiar
            </button>
          </div>

          <div className="rg-card">
            <div className="rg-card-header">
              <div>
                <h3>{filtered.length} eventos</h3>
                <div className="sub">Bitácora del sistema · ordenado por fecha desc</div>
              </div>
            </div>
            <div className="rg-hist-row" style={{
              background: "var(--rg-cream)", padding: "9px 18px",
              fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase",
              color: "var(--rg-muted)", fontWeight: 500, borderBottom: "1px solid var(--rg-line)"
            }}>
              <span></span><span>Fecha</span><span>Usuario</span>
              <span>Acción · descripción</span><span>Tabla</span>
            </div>

            {filtered.length === 0 && !loading ? (
              <div style={{
                padding: "40px 24px", textAlign: "center",
                color: "var(--rg-muted)", fontSize: 13
              }}>
                {Icon.history(28)}
                <p style={{ marginTop: 12 }}>Sin eventos que coincidan con el filtro.</p>
              </div>
            ) : filtered.map(h => {
              const m = accionMeta(h.accion);
              const tabla = h.tabla || h.tablaafectada || "";
              return (
                <div className="rg-hist-row" key={h.id}>
                  <div className="rg-hist-icon" style={{ background: m.bg, color: m.c }}>
                    {m.ic(13)}
                  </div>
                  <span className="ts">{h.fecha}</span>
                  <span className="usr">{h.usuario || "—"}</span>
                  <div>
                    <span className="rg-pill" style={{
                      background: m.bg, color: m.c, marginRight: 8, fontWeight: 600
                    }}>{h.accion}</span>
                    <span className="desc">{getDesc(h)}</span>
                  </div>
                  <span className="table-tag">{tabla || "—"}</span>
                </div>
              );
            })}

            <div className="rg-paginate">
              <span>Mostrando 1–{filtered.length} de {historial.length}</span>
              <div className="pg">
                <button disabled>‹</button>
                <button className="active">1</button>
                <button disabled>›</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { OCListView, InsumosView, ProveedoresView, HistorialView });
