/* eslint-disable */
// ApiBalanceMonitor — LLM provider balance + usage cards
// Props (TS): { providers?: Provider[]; intervalMs?: number }

const PROVIDERS = [
  {
    id: "deepseek",
    name: "DeepSeek",
    glyph: "DS",
    glyphBg: "linear-gradient(135deg, oklch(0.42 0.16 250), oklch(0.32 0.14 270))",
    balance: 4.82,  limit: 60,  used: 37.18,  hue: 145, // green
    callsRemaining: 8120,
    status: "Healthy", tone: "good",
    lastChecked: "10:31:24",
  },
  {
    id: "moonshot",
    name: "Moonshot",
    glyph: "M",
    glyphBg: "radial-gradient(circle at 30% 30%, oklch(0.85 0.04 80), oklch(0.45 0.02 80))",
    balance: 12.50, limit: 30,  used: 17.50,  hue: 145,
    callsRemaining: 15300,
    status: "Healthy", tone: "good",
    lastChecked: "10:31:24",
  },
  {
    id: "xai",
    name: "xAI / Grok",
    glyph: "𝕏",
    glyphBg: "linear-gradient(135deg, oklch(0.20 0 0), oklch(0.30 0 0))",
    balance: 0.85,  limit: 20,  used: 19.15,  hue: 75, // amber
    callsRemaining: 430,
    status: "Low Balance", tone: "warn",
    lastChecked: "10:31:24",
    warning: "Low balance alert: below $1.00 — auto-fallback armed",
  },
  {
    id: "openrouter",
    name: "OpenRouter",
    glyph: "⌁",
    glyphBg: "linear-gradient(135deg, oklch(0.45 0.12 320), oklch(0.30 0.10 260))",
    balance: 8.20,  limit: 20,  used: 10.80,  hue: 145,
    callsRemaining: 6800,
    status: "Healthy", tone: "good",
    lastChecked: "10:31:24",
  },
];

// generate a plausible 7d trend for each provider — descending if low, slightly noisy
function trendFor(p) {
  const start = p.balance + p.used / 6;
  const slope = -(p.used / 6) / 28;
  const arr = [];
  let v = start;
  for (let i = 0; i < 28; i++) {
    v += slope + (Math.sin(i * 0.7 + p.id.length) * 0.18) - (Math.random() * 0.18);
    arr.push(Math.max(0.1, v));
  }
  arr[arr.length - 1] = p.balance;
  return arr;
}

function ApiBalanceMonitor() {
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [interval, setIntervalSec] = useState(30);
  const [tick, setTick] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const trends = useMemo(() => Object.fromEntries(PROVIDERS.map((p) => [p.id, trendFor(p)])), []);

  useEffect(() => {
    if (!autoRefresh) return;
    const id = setInterval(() => {
      setRefreshing(true);
      setTimeout(() => { setRefreshing(false); setTick((t) => t + 1); }, 700);
    }, interval * 1000);
    return () => clearInterval(id);
  }, [autoRefresh, interval]);

  const totalBalance = PROVIDERS.reduce((a, p) => a + p.balance, 0);
  const totalLimit   = PROVIDERS.reduce((a, p) => a + p.limit,   0);
  const totalUsed    = PROVIDERS.reduce((a, p) => a + p.used,    0);

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18, minHeight: 0 }}>
      <header style={{
        display: "flex", alignItems: "center", gap: 12,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, letterSpacing: "-0.015em" }}>
            API Balance Monitor
          </h2>
          <p style={{ margin: "2px 0 0", fontSize: 13, color: "var(--text-3)" }}>
            Real-time balance and usage monitoring for LLM providers.
          </p>
        </div>
        <Toggle on={autoRefresh} onChange={setAutoRefresh} label="Auto-refresh"/>
        <IntervalSelect value={interval} onChange={setIntervalSec}/>
        <IconButton title="Refresh now"
          onClick={() => { setRefreshing(true); setTimeout(() => { setRefreshing(false); setTick(t=>t+1); }, 500); }}>
          <I.Refresh size={14} style={{
            animation: refreshing ? "spin 700ms linear" : "none"
          }}/>
        </IconButton>
        <style>{`@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }`}</style>
      </header>

      {/* provider grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {PROVIDERS.map((p) => (
          <ProviderCard key={p.id} p={p} trend={trends[p.id]}/>
        ))}
      </div>

      {/* totals strip */}
      <Card padding={20} style={{ background: "var(--bg-1)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, alignItems: "center" }}>
          <TotalsTile icon={<I.Wallet/>} label="Total Balance" value={`$${totalBalance.toFixed(2)}`} unit="USD"/>
          <TotalsTile icon={<I.Activity/>} label="Total Credit Limit" value={`$${totalLimit.toFixed(2)}`} unit="USD"/>
          <TotalsTile
            icon={<I.Activity/>}
            label="Total Usage"
            value={`${Math.round(totalUsed / totalLimit * 100)}%`}
            unit={`$${totalUsed.toFixed(2)} / $${totalLimit.toFixed(2)}`}
          />
          <TotalsTile icon={<I.Sparkles/>} label="Default Provider" value="DeepSeek" unit="Priority: 1" highlight/>
        </div>
      </Card>
    </div>
  );
}

function ProviderCard({ p, trend }) {
  const usePct = Math.round((p.used / p.limit) * 100);
  const barColor = usePct >= 90 ? "var(--warn)" : usePct >= 75 ? "var(--info)" : "var(--accent)";
  const trendColor = p.tone === "warn" ? "var(--warn)" : "var(--accent)";

  return (
    <article style={{
      position: "relative",
      background: "var(--bg-1)",
      borderRadius: "var(--r-lg)",
      boxShadow: "var(--shadow-1)",
      overflow: "hidden",
    }}>
      {/* subtle hue stripe along the top */}
      <div style={{
        position: "absolute", left: 0, right: 0, top: 0, height: 2,
        background: p.tone === "warn"
          ? "linear-gradient(90deg, transparent, var(--warn), transparent)"
          : "linear-gradient(90deg, transparent, var(--accent), transparent)",
        opacity: 0.6,
      }}/>
      <div style={{ padding: "18px 20px", display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10,
          background: p.glyphBg,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: "white", fontWeight: 700, fontSize: 18,
          boxShadow: "inset 0 0 0 1px oklch(1 0 0 / 0.08)",
        }} className="mono">{p.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h4 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: "-0.01em" }}>{p.name}</h4>
            <Pill tone={p.tone}>{p.status}</Pill>
          </div>
          <div style={{ fontSize: 11.5, color: "var(--text-4)", marginTop: 2 }}>
            Last checked {p.lastChecked}
          </div>
        </div>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--good)" }}>
          <StatusDot tone="good" size={7}/> Online
        </span>
      </div>

      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1fr",
        gap: 18,
        padding: "0 20px 18px",
      }}>
        {/* balance + remaining calls */}
        <div>
          <Label>Current Balance</Label>
          <div className="mono" style={{
            fontSize: 30, fontWeight: 700,
            color: p.tone === "warn" ? "var(--warn)" : "var(--good)",
            letterSpacing: "-0.02em",
            lineHeight: 1.1,
            marginTop: 2,
          }}>
            ${p.balance.toFixed(2)}
            <span style={{ fontSize: 12, color: "var(--text-4)", fontWeight: 500, marginLeft: 6 }}>USD</span>
          </div>

          <div style={{ height: 14 }}/>

          <Label>Est. Remaining Calls</Label>
          <div className="mono" style={{
            fontSize: 18, fontWeight: 600,
            color: "var(--text-1)",
            marginTop: 2,
          }}>
            ~{p.callsRemaining.toLocaleString()} <span style={{ fontSize: 12, color: "var(--text-4)", fontWeight: 500 }}>calls</span>
          </div>
          <div style={{ fontSize: 11, color: "var(--text-4)", marginTop: 2 }}>Based on current usage</div>
        </div>

        {/* usage + sparkline */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <Label>Usage (this month)</Label>
            <span className="mono" style={{ fontSize: 11, color: "var(--text-4)" }}>
              ${p.used.toFixed(2)} / ${p.limit.toFixed(2)}
            </span>
          </div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "var(--text-1)", marginTop: 2 }}>
            {usePct}%
          </div>
          <div style={{
            height: 6, background: "var(--bg-2)", borderRadius: 999,
            marginTop: 4, overflow: "hidden",
          }}>
            <div style={{
              height: "100%",
              width: usePct + "%",
              background: `linear-gradient(90deg, ${barColor}, oklch(from ${barColor} l c h / 0.7))`,
              transition: "width 800ms cubic-bezier(.2,.7,.2,1)",
            }}/>
          </div>

          <div style={{ height: 14 }}/>

          <Label>Balance Trend (7d)</Label>
          <Sparkline data={trend} color={trendColor} height={34}/>
        </div>
      </div>

      {p.warning && (
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "10px 20px",
          background: "var(--warn-soft)",
          color: "var(--warn)",
          fontSize: 12.5, fontWeight: 500,
          borderTop: "1px solid oklch(0.820 0.155 80 / 0.25)",
        }}>
          <I.Warn size={14}/> {p.warning}
          <span style={{ flex: 1 }}/>
          <Btn kind="ghost" size="sm" style={{
            color: "var(--warn)", borderColor: "oklch(0.820 0.155 80 / 0.4)"
          }}>Top up</Btn>
        </div>
      )}
    </article>
  );
}

function Label({ children }) {
  return (
    <div style={{
      fontSize: 10.5, letterSpacing: "0.12em",
      textTransform: "uppercase",
      color: "var(--text-4)",
      fontWeight: 600,
    }}>{children}</div>
  );
}

function Toggle({ on, onChange, label }) {
  return (
    <label style={{
      display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer",
      fontSize: 12.5, color: "var(--text-2)",
    }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
        <StatusDot tone={on ? "good" : "muted"} size={6}/>{label}
      </span>
      <button onClick={() => onChange(!on)} aria-pressed={on}
        style={{
          position: "relative",
          width: 34, height: 18,
          background: on ? "var(--accent)" : "var(--bg-3)",
          borderRadius: 999,
          border: "none",
          transition: "background 160ms ease",
        }}>
        <span style={{
          position: "absolute", top: 2, left: on ? 18 : 2,
          width: 14, height: 14, borderRadius: 999,
          background: on ? "oklch(0.18 0.04 170)" : "var(--text-2)",
          transition: "left 160ms ease",
        }}/>
      </button>
    </label>
  );
}

function IntervalSelect({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const opts = [10, 30, 60, 120, 300];
  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen((o) => !o)}
        style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: "5px 10px",
          background: "var(--bg-1)",
          border: "1px solid var(--border-m)",
          borderRadius: "var(--r-sm)",
          color: "var(--text-2)", fontSize: 12,
        }} className="mono">
        {value}s <I.Down size={11}/>
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", right: 0,
          background: "var(--bg-1)", border: "1px solid var(--border-m)",
          borderRadius: "var(--r-sm)", minWidth: 80,
          padding: 4, zIndex: 5,
          boxShadow: "0 10px 30px -10px oklch(0 0 0 / 0.6)",
        }}>
          {opts.map((o) => (
            <button key={o} onClick={() => { onChange(o); setOpen(false); }}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "5px 10px",
                background: o === value ? "var(--bg-2)" : "transparent",
                color: "var(--text-2)", fontSize: 12, border: "none",
                borderRadius: 4,
              }} className="mono">{o}s</button>
          ))}
        </div>
      )}
    </div>
  );
}

function TotalsTile({ icon, label, value, unit, highlight }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
      <div style={{
        width: 42, height: 42, borderRadius: 12,
        background: highlight ? "var(--accent-soft)" : "var(--bg-2)",
        color: highlight ? "var(--accent)" : "var(--text-3)",
        display: "flex", alignItems: "center", justifyContent: "center",
        border: "1px solid " + (highlight ? "oklch(0.820 0.150 170 / 0.3)" : "var(--border-s)"),
      }}>{React.cloneElement(icon, { size: 18 })}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11.5, color: "var(--text-3)", marginBottom: 2 }}>{label}</div>
        <div className="mono" style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em" }}>
          {value}
        </div>
        <div style={{ fontSize: 11, color: "var(--text-4)" }}>{unit}</div>
      </div>
    </div>
  );
}

window.ApiBalanceMonitor = ApiBalanceMonitor;
