// ROCA GOLF — Alerts dedicated screen + Course mini-viz (conectado a API)

function CourseHoles({ categories, thresholds }) {
  if (!categories || !categories.length) return null;
  return (
    <div className="rg-course">
      <svg viewBox="0 0 720 200" preserveAspectRatio="none">
        <defs>
          <linearGradient id="fairway" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#7fb389"/>
            <stop offset="1" stopColor="#4a8a63"/>
          </linearGradient>
          <pattern id="rough" width="6" height="6" patternUnits="userSpaceOnUse">
            <rect width="6" height="6" fill="#5a8064"/>
            <circle cx="3" cy="3" r="0.6" fill="#3d6b4a"/>
          </pattern>
        </defs>
        <rect width="720" height="200" fill="url(#rough)" opacity="0.4"/>
        <path d="M 0 120 C 80 60, 200 60, 280 110 S 460 180, 540 110 S 700 60, 720 90 L 720 200 L 0 200 Z"
          fill="url(#fairway)" opacity="0.85"/>
        <path d="M 0 120 C 80 60, 200 60, 280 110 S 460 180, 540 110 S 700 60, 720 90"
          stroke="#eef4ee" strokeWidth="1" strokeDasharray="3 6" fill="none" opacity="0.6"/>

        {categories.map((c, i) => {
          const x       = 50 + (i * Math.max(82, Math.floor(640 / categories.length)));
          const y       = 110 + Math.sin(i * 1.1) * 28;
          const budget  = c.budget || 0;
          const spent   = c.spent  || 0;
          const pct     = budget > 0 ? (spent / budget) * 100 : 0;
          const lv      = flagLevel(pct, thresholds);
          const codigo  = c.codigo || c.id || "?";
          const color   = { ok: "#2d6a44", warn: "#d4a017", alert: "#c8651b", over: "#b22222" }[lv];
          return (
            <g key={codigo} transform={`translate(${x},${y})`}>
              <ellipse cx="0" cy="6" rx="9" ry="2.5" fill="#1a3520" opacity="0.55"/>
              <line x1="0" y1="6" x2="0" y2="-22" stroke="#2a2520" strokeWidth="1.4" strokeLinecap="round"/>
              <path d="M 0 -22 L 14 -19 L 0 -16 Z" fill={color}/>
              {(lv === "alert" || lv === "over") && (
                <circle cx="14" cy="-19" r="0" fill={color} opacity="0.5">
                  <animate attributeName="r" values="0;6;0" dur="2s" repeatCount="indefinite"/>
                  <animate attributeName="opacity" values="0.5;0;0.5" dur="2s" repeatCount="indefinite"/>
                </circle>
              )}
              <text x="0" y="22" fontSize="9" textAnchor="middle" fill="#1a3520"
                fontFamily="JetBrains Mono, monospace" fontWeight="600">{codigo}</text>
              <text x="0" y="32" fontSize="8.5" textAnchor="middle" fill="#1a3520"
                fontFamily="JetBrains Mono, monospace" opacity="0.7">{pct.toFixed(0)}%</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function CategoryDonut({ categories, thresholds }) {
  const counts = { ok: 0, warn: 0, alert: 0, over: 0 };
  categories.forEach(c => {
    const budget = c.budget || 0;
    const spent  = c.spent  || 0;
    const pct    = budget > 0 ? (spent / budget) * 100 : 0;
    counts[flagLevel(pct, thresholds)]++;
  });
  const total = categories.length || 1;
  const segs = [
    { k: "ok",    color: "var(--rg-flag-ok)",    label: "Saludable"  },
    { k: "warn",  color: "var(--rg-flag-warn)",  label: "Aviso 80%"  },
    { k: "alert", color: "var(--rg-flag-alert)", label: "Alerta 90%" },
    { k: "over",  color: "var(--rg-flag-over)",  label: "Excedido"   }
  ];
  const r = 56, circ = 2 * Math.PI * r;
  let off = 0;
  const enAlerta = counts.warn + counts.alert + counts.over;

  return (
    <div className="rg-donut-wrap">
      <svg width="140" height="140" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={r} fill="none" stroke="var(--rg-line)" strokeWidth="14"/>
        {segs.map(s => {
          const v = counts[s.k] / total;
          if (!v) return null;
          const len  = v * circ;
          const dash = `${len} ${circ - len}`;
          const el   = (
            <circle key={s.k} cx="70" cy="70" r={r} fill="none"
              stroke={s.color} strokeWidth="14"
              strokeDasharray={dash} strokeDashoffset={-off}
              transform="rotate(-90 70 70)"/>
          );
          off += len;
          return el;
        })}
        <text x="70" y="68" textAnchor="middle" fontFamily="var(--rg-font-display)"
          fontSize="26" fontWeight="600" fill="var(--rg-ink)">{enAlerta}</text>
        <text x="70" y="84" textAnchor="middle" fontSize="10"
          fill="var(--rg-muted)" letterSpacing="0.1em">EN ALERTA</text>
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        {segs.map(s => (
          <div className="rg-row" key={s.k} style={{ justifyContent: "space-between" }}>
            <div className="rg-row" style={{ gap: 8 }}>
              <span className="rg-dot" style={{ background: s.color }}/>
              <span style={{ fontSize: 12 }}>{s.label}</span>
            </div>
            <span className="rg-mono" style={{ fontSize: 12, fontWeight: 600 }}>
              {counts[s.k]}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Vista de Alertas ─────────────────────────────────────────────────────────
function AlertsView({ thresholds, setThresholds, onNav }) {
  const { familias, alerts, loading } = useAppData();

  const [filter, setFilter] = useState("all");

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

  // Combinar alertas de API con alertas calculadas de familias
  const allAlerts = useMemo(() => {
    if (alerts.length) return alerts;
    return buildAlertsFromFamilias(familias, thresholds);
  }, [alerts, familias, thresholds]);

  const filtered = allAlerts.filter(a => filter === "all" ? true : a.level === filter);

  // Categorías para el gráfico de campo
  const courseCategories = familias.map(f => ({
    id:     f.codigo,
    codigo: f.codigo,
    budget: f.budget || 0,
    spent:  f.spent  || 0,
  }));

  return (
    <div className="rg-app">
      <Sidebar active="alerts" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar
          crumbs="Compras / Alertas"
          title="Centro de alertas"
          actions={<button className="rg-btn">{Icon.download()} Exportar</button>}
        />
        <div className="rg-content">

          {/* Vista del campo (banderas por familia) + donut */}
          <div className="rg-two-col" style={{ gridTemplateColumns: "minmax(0,1.2fr) minmax(0,1fr)" }}>
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Estado por familia</h3>
                  <div className="sub">
                    {courseCategories.length} familias · banderas indican nivel de utilización
                  </div>
                </div>
                <span className="rg-pill">
                  {loading ? "Cargando…" : "Vista en vivo"}
                </span>
              </div>
              <div style={{ padding: 18 }}>
                {courseCategories.length > 0
                  ? <CourseHoles categories={courseCategories} thresholds={thresholds}/>
                  : <div style={{ padding: "24px", textAlign: "center", color: "var(--rg-muted)" }}>
                      Sin datos de familias.
                    </div>
                }
              </div>
            </div>
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Distribución por nivel</h3>
                  <div className="sub">Por porcentaje de utilización</div>
                </div>
              </div>
              <CategoryDonut categories={courseCategories} thresholds={thresholds}/>
            </div>
          </div>

          {/* Lista de alertas filtrable */}
          <div className="rg-card">
            <div className="rg-card-header">
              <div>
                <h3>Alertas activas</h3>
                <div className="sub">Ordenadas por severidad</div>
              </div>
              <div className="rg-tabs">
                {[
                  ["all",   "Todas"],
                  ["over",  "Excedidos"],
                  ["alert", "90%+"],
                  ["warn",  "80%+"],
                  ["ok",    "OK"]
                ].map(([k, l]) => (
                  <button key={k}
                    className={"rg-tab" + (filter === k ? " active" : "")}
                    onClick={() => setFilter(k)}>{l}</button>
                ))}
              </div>
            </div>
            <div className="rg-alerts-list">
              {filtered.length === 0 ? (
                <div style={{
                  padding: 30, textAlign: "center",
                  color: "var(--rg-muted)", fontSize: 13
                }}>
                  {Icon.bell(24)}
                  <p style={{ marginTop: 12 }}>Sin alertas en este nivel de filtro.</p>
                </div>
              ) : filtered.map(a => (
                <AlertItem key={a.id} alert={a}/>
              ))}
            </div>
          </div>

          {/* Control de umbrales */}
          <ThresholdControl thresholds={thresholds} onChange={setThresholds}/>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { CourseHoles, CategoryDonut, AlertsView });
