// Networks list — live from API

const { useState: useStateD, useEffect: useEffectD } = React;

function NetworksList({ ctx }) {
  const { t, goToNetwork } = ctx;
  const [networks, setNetworks] = useStateD([]);
  const [loading, setLoading] = useStateD(true);
  const [creating, setCreating] = useStateD(false);
  const [newName, setNewName] = useStateD("");
  const [newCidr, setNewCidr] = useStateD("10.0.0.0/24");

  useEffectD(() => { loadNetworks(); }, []);

  async function loadNetworks() {
    try {
      const data = await ww.get("/networks");
      setNetworks(data);
    } catch {}
    setLoading(false);
  }

  async function handleCreate(e) {
    e.preventDefault();
    if (!newName.trim()) return;
    try {
      await ww.post("/networks", { name: newName.trim(), ipv4_cidr: newCidr });
      setNewName("");
      setCreating(false);
      loadNetworks();
    } catch (err) {
      alert(err.message);
    }
  }

  function relativeTime(ts) {
    if (!ts) return "—";
    const diff = Math.floor(Date.now() / 1000) - ts;
    if (diff < 60) return diff + "s ago";
    if (diff < 3600) return Math.floor(diff / 60) + "m ago";
    if (diff < 86400) return Math.floor(diff / 3600) + "h ago";
    return Math.floor(diff / 86400) + "d ago";
  }

  const planTone = { free: "ghost", pro: "accent", enterprise: "warn" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <h1 style={{ fontSize: 24, fontWeight: 500, margin: 0, letterSpacing: -0.01 }}>{t.networks.title}</h1>
        <Btn onClick={() => setCreating(!creating)}>{t.networks.new}</Btn>
      </div>

      {creating && (
        <Card>
          <form onSubmit={handleCreate} style={{ display: "flex", gap: 12, alignItems: "flex-end" }}>
            <div style={{ flex: 1 }}>
              <div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>{t.networks.name}</div>
              <input value={newName} onChange={e => setNewName(e.target.value)} placeholder="my-network" autoFocus/>
            </div>
            <div style={{ width: 180 }}>
              <div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>{t.networks.cidr}</div>
              <input value={newCidr} onChange={e => setNewCidr(e.target.value)} placeholder="10.0.0.0/24" className="mono"/>
            </div>
            <Btn type="submit">{t.common.save}</Btn>
            <Btn variant="ghost" onClick={() => setCreating(false)}>{t.common.cancel}</Btn>
          </form>
        </Card>
      )}

      <Card pad={0}>
        <div className="ww-table" style={{ "--ww-cols": "2fr 1.4fr 0.8fr 1fr 1fr 24px" }}>
          <div className="ww-table__head">
            {[t.networks.name, t.networks.cidr, t.networks.plan, t.networks.devices, t.networks.lastActivity, ""].map((h, i) => (
              <div key={i}>{h}</div>
            ))}
          </div>
          {loading && <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>Loading...</div>}
          {!loading && networks.length === 0 && (
            <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
              {t.networks.empty || "No networks yet. Create one to get started."}
            </div>
          )}
          {networks.map((n) => (
            <button key={n.id} className="ww-table__row ww-table__row--clickable" onClick={() => goToNetwork(n.id)}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{n.name}</div>
              <div className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>{n.ipv4_cidr}</div>
              <div><Pill tone={planTone[n.plan] || "ghost"}>{n.plan || "free"}</Pill></div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--mono)", fontSize: 12 }}>
                <Dot c={(n.online_count > 0 && n.online_count === n.device_count) ? "var(--accent)" : (n.online_count > 0 ? "var(--warn)" : "var(--ink-3)")}/>
                {n.online_count}/{n.device_count}
              </div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{relativeTime(n.last_activity)}</div>
              <span style={{ fontSize: 14, color: "var(--ink-3)" }}>→</span>
            </button>
          ))}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { NetworksList });
