// ROCA GOLF — Dashboard view (conectado a API)

function KpiCardFeatured({ totalBudget, totalSpent, thresholds }) {
  const pct = totalBudget > 0 ? (totalSpent / totalBudget) * 100 : 0;
  const level = flagLevel(pct, thresholds);
  return (
    <div className="rg-kpi featured">
      <div className="label">Presupuesto total · {new Date().getFullYear()}</div>
      <div className="value">
        <span className="currency">MXN</span>{fmtMoney(totalBudget)}
      </div>
      <div className="rg-budget-track">
        <div className="rg-budget-fill" style={{ width: Math.min(pct, 100) + "%" }}/>
      </div>
      <div className="rg-budget-meta">
        <span>Ejercido {fmtMoney(totalSpent)}</span>
        <span style={{
          color: flagColor(level) === "var(--rg-flag-ok)"
            ? "rgba(245,241,232,0.9)" : flagColor(level)
        }}>
          {pct.toFixed(1)}% · {levelLabel(level)}
        </span>
      </div>
    </div>
  );
}

function KpiCardSimple({ label, value, currency, delta, deltaDir = "up", trend }) {
  return (
    <div className="rg-kpi">
      <div className="label">{label}</div>
      <div className="value">
        {currency && <span className="currency">{currency}</span>}{value}
      </div>
      <div className="delta">
        {trend && <Sparkline data={trend} width={70} height={22}/>}
        <span className="rg-spacer"/>
        {delta && <span className="pill">
          {deltaDir === "up" ? Icon.arrowUp(10) : Icon.arrowDown(10)} {delta}
        </span>}
      </div>
    </div>
  );
}

function CategoryRow({ cat, thresholds, onClick }) {
  const pct   = cat.budget > 0 ? (cat.spent / cat.budget) * 100 : 0;
  const level = flagLevel(pct, thresholds);
  const nombre = cat.nombre || cat.name || "—";
  const codigo = cat.codigo || cat.id  || "?";
  return (
    <div className="rg-cat-row" onClick={() => onClick && onClick(cat)}>
      <GolfFlag level={level} size={26}/>
      <div>
        <div className="cat-name">{nombre}</div>
        <div className="cat-meta">{codigo}</div>
      </div>
      <div>
        <div className="rg-row" style={{
          justifyContent: "space-between", fontSize: 11,
          color: "var(--rg-muted)", fontFamily: "var(--rg-font-mono)"
        }}>
          <span>${fmtMoney(cat.spent)}</span>
          <span>de ${fmtMoney(cat.budget)}</span>
        </div>
        <div className="rg-track">
          <div className={"fill " + level} style={{ width: Math.min(pct, 100) + "%" }}/>
        </div>
      </div>
      <div className="cat-pct" style={{ color: flagColor(level) }}>{pct.toFixed(0)}%</div>
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <span className={"rg-alert-tag " + level}>{levelLabel(level)}</span>
      </div>
    </div>
  );
}

function AlertItem({ alert }) {
  return (
    <div className="rg-alert">
      <GolfFlag level={alert.level} size={22}/>
      <div className="body">
        <div className="rg-row" style={{ justifyContent: "space-between" }}>
          <span className="title">{alert.title}</span>
          <span className={"rg-alert-tag " + alert.level}>{levelLabel(alert.level)}</span>
        </div>
        <div className="desc">{alert.desc}</div>
        <div className="meta">{alert.time} · #{alert.cat}</div>
      </div>
    </div>
  );
}

function ThresholdControl({ thresholds, onChange }) {
  const rows = [
    { key: "warn",  color: "var(--rg-flag-warn)",  label: "Aviso",   desc: "Bandera amarilla" },
    { key: "alert", color: "var(--rg-flag-alert)", label: "Alerta",  desc: "Bandera naranja" },
    { key: "over",  color: "var(--rg-flag-over)",  label: "Excedido",desc: "Bandera roja · notifica gerencia" }
  ];
  return (
    <div className="rg-card">
      <div className="rg-card-header">
        <div>
          <h3>Umbrales de alerta</h3>
          <div className="sub">Aplican a todas las categorías</div>
        </div>
        <span className="rg-pill">% del presupuesto</span>
      </div>
      <div className="rg-threshold-card">
        {rows.map(r => (
          <div className="rg-threshold-row" key={r.key}>
            <GolfFlag
              level={r.key === "over" ? "over" : r.key === "alert" ? "alert" : "warn"}
              size={22} animate={false}
            />
            <div>
              <div className="rg-threshold-label">{r.label}
                <div className="desc">{r.desc}</div>
              </div>
              <div className="rg-slider-wrap" style={{ marginTop: 6 }}>
                <input
                  type="range"
                  min={r.key === "warn" ? 50 : r.key === "alert" ? 70 : 90}
                  max={r.key === "warn" ? 89 : r.key === "alert" ? 99 : 130}
                  value={thresholds[r.key]}
                  onChange={e => onChange({ ...thresholds, [r.key]: +e.target.value })}
                  className="rg-slider"
                />
              </div>
            </div>
            <input
              className="rg-threshold-input"
              type="number"
              value={thresholds[r.key]}
              onChange={e => onChange({ ...thresholds, [r.key]: +e.target.value })}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

function RecentOCsCard() {
  const { ordenes } = useAppData();

  const recent = ordenes.slice(0, 8).map(o => ({
    folio:   fmtFolio(o.folio),
    vendor:  o.proveedor_nombre || nombreProveedor(o.proveedorid),
    familia: o.familia || "—",
    amount:  o.total,
    moneda:  o.moneda || "MXN",
    status:  o.statuspago,
  }));

  return (
    <div className="rg-card">
      <div className="rg-card-header">
        <div>
          <h3>Órdenes de compra recientes</h3>
          <div className="sub">Últimas {recent.length} OCs</div>
        </div>
        <button className="rg-btn" style={{ padding: "5px 10px", fontSize: 11.5 }}>
          Ver todas {Icon.arrowRight(11)}
        </button>
      </div>
      {recent.length === 0 ? (
        <div style={{ padding: "32px 24px", textAlign: "center", color: "var(--rg-muted)", fontSize: 13 }}>
          Sin órdenes registradas.
        </div>
      ) : recent.map(oc => (
        <div className="rg-oc-row" key={oc.folio}>
          <div>
            <div className="vendor">{oc.vendor}</div>
            <div className="folio">{oc.folio}</div>
          </div>
          <StatusPagoBadge status={oc.status}/>
          <span className="amount">
            {oc.moneda === "USD" ? "USD " : "$"}{fmtMoney(oc.amount)}
          </span>
          <button className="rg-btn icon" title="Más">{Icon.more()}</button>
        </div>
      ))}
    </div>
  );
}

function CategoriesCard({ categories, thresholds, onCatClick }) {
  const [tab, setTab] = useState("all");
  const filtered = categories.filter(c => {
    if (tab === "all") return true;
    const pct = c.budget > 0 ? (c.spent / c.budget) * 100 : 0;
    const lv  = flagLevel(pct, thresholds);
    if (tab === "alerts") return lv === "warn" || lv === "alert" || lv === "over";
    if (tab === "ok")     return lv === "ok";
    return true;
  });

  return (
    <div className="rg-card">
      <div className="rg-card-header">
        <div>
          <h3>Familias de insumos</h3>
          <div className="sub">{categories.length} familias · por % de utilización</div>
        </div>
        <div className="rg-tabs">
          <button className={"rg-tab" + (tab === "all"    ? " active" : "")} onClick={() => setTab("all")}>Todas</button>
          <button className={"rg-tab" + (tab === "alerts" ? " active" : "")} onClick={() => setTab("alerts")}>En alerta</button>
          <button className={"rg-tab" + (tab === "ok"     ? " active" : "")} onClick={() => setTab("ok")}>Saludables</button>
        </div>
      </div>
      <div className="rg-categories">
        {filtered.length === 0 ? (
          <div style={{ padding: "32px 24px", textAlign: "center", color: "var(--rg-muted)", fontSize: 13 }}>
            Sin familias en esta categoría.
          </div>
        ) : filtered
          .slice()
          .sort((a, b) => {
            const pa = a.budget > 0 ? (a.spent / a.budget) : 0;
            const pb = b.budget > 0 ? (b.spent / b.budget) : 0;
            return pb - pa;
          })
          .map(c => (
            <CategoryRow
              key={c.codigo || c.id}
              cat={c}
              thresholds={thresholds}
              onClick={onCatClick}
            />
          ))}
      </div>
    </div>
  );
}

function OverBudgetBanner({ alerts }) {
  const over = alerts.filter(a => a.level === "over");
  if (!over.length) return null;
  return (
    <div className="rg-banner">
      <div className="ic-wrap"><GolfFlag level="over" size={32}/></div>
      <div className="body">
        <div className="ttl">
          {over.length} familia{over.length > 1 ? "s" : ""} excedió el presupuesto asignado
        </div>
        <div className="msg">
          Requiere autorización de gerencia para emitir nuevas órdenes en estas familias.
        </div>
      </div>
      <div className="actions">
        <button className="rg-btn">Ver detalle</button>
        <button className="rg-btn primary">{Icon.check()} Autorizar</button>
      </div>
    </div>
  );
}

// ── Dashboard compuesto ──────────────────────────────────────────────────────
function DashboardView({ thresholds, setThresholds, onNav }) {
  const { familias, alerts, loading } = useAppData();

  // Categorías en formato unificado para CategoryRow
  const categories = familias.map(f => ({
    id:     f.codigo,
    codigo: f.codigo,
    nombre: f.nombre,
    name:   f.nombre,
    meta:   "—",
    budget: f.budget || 0,
    spent:  f.spent  || 0,
    trend:  f.trend  || [0],
  }));

  const totalBudget = categories.reduce((a, c) => a + c.budget, 0);
  const totalSpent  = categories.reduce((a, c) => a + c.spent, 0);
  const inAlert     = categories.filter(c => {
    const pct = c.budget > 0 ? (c.spent / c.budget) * 100 : 0;
    return flagLevel(pct, thresholds) !== "ok";
  }).length;

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

  return (
    <div className="rg-app">
      <Sidebar active="dashboard" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Compras / Dashboard" title="Panel de presupuesto"/>
        <div className="rg-content">
          <OverBudgetBanner alerts={alerts}/>

          <div className="rg-kpi-grid">
            <KpiCardFeatured
              totalBudget={totalBudget}
              totalSpent={totalSpent}
              thresholds={thresholds}
            />
            <KpiCardSimple
              label="% utilización promedio"
              value={totalBudget > 0
                ? ((totalSpent / totalBudget) * 100).toFixed(1) + "%" : "—"}
              delta={undefined}
              trend={[0]}
            />
            <KpiCardSimple
              label="Familias en alerta"
              value={inAlert}
              currency=""
              delta={`${categories.length - inAlert} OK`}
              deltaDir="down"
              trend={[0]}
            />
          </div>

          <div className="rg-two-col">
            <CategoriesCard categories={categories} thresholds={thresholds}/>
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <ThresholdControl thresholds={thresholds} onChange={setThresholds}/>
              <div className="rg-card">
                <div className="rg-card-header">
                  <div>
                    <h3>Alertas activas</h3>
                    <div className="sub">
                      {alertCount} requieren atención
                    </div>
                  </div>
                  <button className="rg-btn icon">{Icon.more()}</button>
                </div>
                <div className="rg-alerts-list">
                  {alerts.length === 0 ? (
                    <div style={{
                      padding: "24px", textAlign: "center",
                      color: "var(--rg-muted)", fontSize: 13
                    }}>
                      Sin alertas activas.
                    </div>
                  ) : alerts.slice(0, 4).map(a => (
                    <AlertItem key={a.id} alert={a}/>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <RecentOCsCard/>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, {
  DashboardView, KpiCardFeatured, KpiCardSimple, CategoryRow, AlertItem,
  ThresholdControl, RecentOCsCard, CategoriesCard, OverBudgetBanner
});
