/* ============================================================
   NetroIQ demo — Site Detail (8 tabs + live charts)
   ============================================================ */
var useState = React.useState, useEffect = React.useEffect, useRef = React.useRef;

function SiteDetail({ go, id }) {
  const site = DEMO.sites.find(s => s.id === id) || DEMO.focus;
  const f = DEMO.focus;
  const [tab, setTab] = useState("devices");
  const [tpTab, setTpTab] = useState("live");

  const dcounts = [
    ["Total Devices", f.devices, ""], ["Offline", f.offline, f.offline ? "crit" : "green"],
    ["WiFi APs", f.wifiAps, ""], ["Wired", f.wired, ""], ["Pending Updates", f.pending, f.pending ? "warn" : "green"],
  ];

  return (
    <div className="fade">
      <div className="sd-head">
        <div>
          <h1><Icon name="router" style={{ width: 22, height: 22, color: "var(--ink-dim)" }} /> {site.name}
            <span className={"badge " + site.type}>{site.type}</span></h1>
          <div className="meta">
            <span><Icon name="clock" /> 13:34 · Sun, May 31 · {f.tz}</span>
            <span><Icon name="globe" /> Local ({site.wanIp})</span>
          </div>
        </div>
        <div className="right">
          <button className="btn solid"><Icon name="ext" /> Open UniFi Console</button>
        </div>
      </div>

      {/* summary tiles */}
      <div className="tiles c5">
        <div className="tile"><div className="tk">ISP Provider</div><div className="tv" style={{ fontSize: "1.1rem" }}>{site.isp}</div><div className="ts">{f.ispParent}</div></div>
        <div className="tile"><div className="tk">WAN IP</div><div className="tv" style={{ fontSize: "1.1rem" }}>{site.wanIp}</div><div className="ts">wan</div></div>
        <div className="tile"><div className="tk">Console</div><div className="tv" style={{ fontSize: "1.1rem" }}>{f.console}</div><div className="ts">FW {f.fw}</div></div>
        <div className={"tile " + (site.status === "on" ? "" : "warn")}><div className="tk">Status</div><div className={"tv " + (site.status === "on" ? "green" : "warn")} style={{ fontSize: "1.1rem" }}>{site.status === "on" ? "Healthy" : site.status === "deg" ? "Degraded" : "Down"}</div><div className="ts">WAN Uptime: {site.uptime.toFixed(1)}%</div></div>
        <div className="tile"><div className="tk">Clients</div><div className="tv">{site.clients}</div><div className="ts">{f.wifiClients} WiFi · {f.wiredClients} Wired</div></div>
      </div>

      {/* ISP connection health */}
      <div className="panel" style={{ marginTop: 16 }}>
        <div className="panel-h">
          <h3><span className="lbl">ISP Connection Health</span> <span className="badge info">EXCELLENT</span> <span className="sel" style={{ marginLeft: 6 }}><select defaultValue="7D"><option>24H</option><option>7D</option><option>30D</option></select></span></h3>
          <span style={{ fontFamily: "var(--ff-display)", fontSize: "1.4rem", color: "var(--green)", fontWeight: 600 }}>{site.uptime.toFixed(2)}%</span>
        </div>
        <div className="panel-b">
          <div className="isp-mini">
            <div className="m"><div className="k">WAN Uptime</div><div className="v ok">{site.uptime.toFixed(2)}%</div></div>
            <div className="m"><div className="k">ISP Provider</div><div className="v">{site.isp}</div></div>
            <div className="m"><div className="k">Latency (avg/max)</div><div className="v">{f.health.latencyAvg}/{f.health.latencyMax}ms</div></div>
            <div className="m"><div className="k">Packet Loss (avg/peak)</div><div className="v warn">{f.health.lossAvg}/{f.health.lossPeak.toFixed(1)}%</div></div>
            <div className="m"><div className="k">Total Downtime</div><div className="v ok">{f.health.downtime}</div></div>
          </div>
          <div className="lbl" style={{ marginBottom: 8 }}>Uptime, Latency &amp; Packet Loss (80 data points, 7 days — hourly)</div>
          <ISPChart />

          {/* throughput tabs */}
          <div style={{ marginTop: 18 }}>
            <div className="tp-tabs">
              <button className={"tp-tab" + (tpTab === "live" ? " active" : "")} onClick={() => setTpTab("live")}><span className="lp" /> LIVE WAN THROUGHPUT</button>
              <button className={"tp-tab" + (tpTab === "speed" ? " active" : "")} onClick={() => setTpTab("speed")}>ISP SPEED TEST RESULTS</button>
            </div>
            <div className="tp-wrap">
              {tpTab === "live" ? <LiveThroughput /> : (
                <div className="tp-stats">
                  <div className="tp-stat"><div className="k">Download</div><div className="v dl">912 Mbps</div></div>
                  <div className="tp-stat"><div className="k">Upload</div><div className="v ul">104 Mbps</div></div>
                  <div className="tp-stat"><div className="k">Latency</div><div className="v">9 ms</div></div>
                  <div className="tp-stat"><div className="k">Last Test</div><div className="v" style={{ fontSize: "1rem" }}>2h ago</div></div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* internet issues */}
      <div className="issues" style={{ marginTop: 16 }}>
        <div className="ih"><span className="t">Internet Issues ({DEMO.issues.length})</span><Icon name="alerts" style={{ width: 16, height: 16, color: "var(--red)" }} /></div>
        <div className="issues-scroll">{DEMO.issues.map((is, i) => (
          <div key={i} className={"issue" + (is.k === "gap" ? " gray" : "")}><Icon name={is.k === "gap" ? "clock" : "zap"} /> {is.t}</div>
        ))}</div>
      </div>

      {/* device counts */}
      <div className="tiles c5" style={{ marginTop: 16 }}>
        {dcounts.map(([k, v, cls], i) => (
          <div key={i} className="tile"><div className="tk">{k}</div><div className={"tv" + (cls ? " " + cls : "")} style={{ fontSize: "1.4rem" }}>{v}</div></div>
        ))}
      </div>

      {/* tabs */}
      <div className="tabs">
        {[["devices", "switch", "Devices", f.offline], ["clients", "customers", "Clients"], ["network", "topology", "Network"],
          ["security", "shield", "Security"], ["health", "health", "Health"], ["updates", "download", "Updates", f.pending],
          ["topology", "topology", "Topology"], ["ai", "ai", "AI Assistant"]].map(([k, ic, lb, n]) => (
          <button key={k} className={"tab" + (tab === k ? " active" : "")} onClick={() => setTab(k)}>
            <Icon name={ic} /> {lb}{n ? <span className="n">{n}</span> : null}
          </button>))}
      </div>

      <div className="fade" key={tab}>
        {tab === "devices" && <DevicesTab />}
        {tab === "clients" && <ClientsTab site={site} />}
        {tab === "network" && <NetworkTab />}
        {tab === "security" && <SecurityTab />}
        {tab === "health" && <SiteHealthTab />}
        {tab === "updates" && <UpdatesTab />}
        {tab === "topology" && <TopologyTab />}
        {tab === "ai" && <AITab />}
      </div>
    </div>
  );
}

/* ---- Devices tab ---- */
function DevicesTab() {
  const [q, setQ] = useState(""), [st, setSt] = useState("all");
  const rows = DEMO.devices.filter(d =>
    (st === "all" || (st === "online" ? d[7] === "on" : d[7] === "off")) &&
    (!q || d[0].toLowerCase().includes(q.toLowerCase()) || d[3].toLowerCase().includes(q.toLowerCase())));
  const tagcls = t => t === "ROUTER / GATEWAY" || t === "EFG" ? "gw" : t === "ACCESS POINT" ? "ap" : t === "SWITCH" ? "sw" : "gen";
  return (
    <div className="panel">
      <div className="panel-h">
        <h3><Icon name="switch" /> Site Devices ({DEMO.devices.length})</h3>
        <div style={{ display: "flex", gap: 8 }}>
          <div className="search" style={{ minWidth: 170, padding: "7px 11px" }}><Icon name="search" /><input placeholder="Filter devices…" value={q} onChange={e => setQ(e.target.value)} /></div>
          <div className="sel"><select value={st} onChange={e => setSt(e.target.value)}><option value="all">All Statuses</option><option value="online">Online</option><option value="offline">Offline</option></select></div>
        </div>
      </div>
      <table className="tbl">
        <thead><tr><th>Status</th><th>Name</th><th>Type</th><th>Model</th><th>IP Address</th><th>Firmware</th><th>Uptime</th></tr></thead>
        <tbody>{rows.map((d, i) => (
          <tr key={i}>
            <td><span className={"st " + (d[7] === "on" ? "on" : "off")}>{d[7] === "on" ? "ONLINE" : "OFFLINE"}</span></td>
            <td className="strong">{d[0]}</td>
            <td><span className={"dtag " + tagcls(d[2])}>{d[2]}</span></td>
            <td>{d[3]}</td>
            <td className="lk">{d[4]}</td>
            <td>{d[5] === "—" ? <span className="mut">N/A</span> : <span className="fw">{d[5]}</span>}</td>
            <td className="mut">{d[6]}</td>
          </tr>))}</tbody>
      </table>
    </div>
  );
}

/* ---- Clients tab ---- */
function ClientsTab({ site }) {
  const f = DEMO.focus;
  const [q, setQ] = useState("");
  const rows = DEMO.clients.filter(c => !q || c.name.toLowerCase().includes(q.toLowerCase()) || (c.ip || "").includes(q));
  return (
    <div>
      <div className="tiles c5" style={{ marginBottom: 14 }}>
        <div className="tile"><div className="tk">Total Clients</div><div className="tv teal">{site.clients}</div></div>
        <div className="tile"><div className="tk">WiFi Clients</div><div className="tv">{f.wifiClients}</div></div>
        <div className="tile"><div className="tk">Wired Clients</div><div className="tv">{f.wiredClients}</div></div>
        <div className="tile"><div className="tk">Guests</div><div className="tv mut">{f.guests}</div></div>
        <div className="tile"><div className="tk">Default Access</div><div className="tv teal">{site.clients}</div></div>
      </div>
      <div className="panel">
        <div className="panel-h">
          <h3>Connected Clients ({site.clients})</h3>
          <div className="search" style={{ minWidth: 200, padding: "7px 11px" }}><Icon name="search" /><input placeholder="Search by name, MAC, IP…" value={q} onChange={e => setQ(e.target.value)} /></div>
        </div>
        <table className="tbl">
          <thead><tr><th>Type</th><th>Name</th><th>IP Address</th><th>MAC</th><th>Signal</th><th>Access</th><th>Connected Since</th><th className="r">Actions</th></tr></thead>
          <tbody>{rows.map((c, i) => (
            <tr key={i}>
              <td><Icon name={c.type === "wifi" ? "wifi" : "ethernet"} style={{ width: 16, height: 16, color: "var(--ink-dim)" }} /></td>
              <td className="strong">{c.name}</td>
              <td className="lk">{c.ip}</td>
              <td className="mut mono" style={{ fontSize: ".74rem" }}>{c.mac}</td>
              <td><span className={"lk"} style={{ color: c.type === "wifi" ? "var(--teal)" : "var(--ink-soft)" }}>{c.type === "wifi" ? "WiFi" : "Wired"}</span></td>
              <td className="lk">{c.access}</td>
              <td className="mut">{c.since}</td>
              <td className="r"><span className="acts"><button className="block" title="Block"><Icon name="block" /></button><button className="kick" title="Disconnect"><Icon name="kick" /></button><button className="re" title="Reconnect"><Icon name="refresh" /></button></span></td>
            </tr>))}</tbody>
        </table>
      </div>
    </div>
  );
}

/* ---- Network tab ---- */
function NetworkTab() {
  const [sub, setSub] = useState("vlans");
  return (
    <div>
      <div className="subtabs">
        {[["vlans", "VLANs & Networks"], ["wifi", "WiFi"], ["vpn", "VPN"], ["wan", "WAN / SD-WAN"], ["ports", "Port Management"]].map(([k, l]) =>
          <button key={k} className={"subtab" + (sub === k ? " active" : "")} onClick={() => setSub(k)}>{l}</button>)}
      </div>
      {sub === "vlans" ? (
        <div className="panel"><div className="panel-h"><h3><Icon name="topology" /> Configured Networks ({DEMO.vlans.length})</h3></div>
          <table className="tbl"><thead><tr><th>VLAN / Network</th><th>Subnet</th><th className="r">Clients</th><th>Status</th></tr></thead>
            <tbody>{DEMO.vlans.map((v, i) => (
              <tr key={i}><td className="strong">{v[0]}</td><td className="lk mono">{v[1]}</td><td className="r">{(i * 7 + 3) % 60}</td><td><span className="st on">Active</span></td></tr>))}</tbody>
          </table></div>
      ) : <div className="empty">The <strong style={{ textTransform: "uppercase" }}>{sub}</strong> view is part of the full platform.</div>}
    </div>
  );
}

/* ---- Security tab ---- */
function SecurityTab() {
  const zones = [["WAN → LAN", "Block", "deny"], ["LAN → WAN", "Allow", "allow"], ["Guest → LAN", "Block", "deny"], ["VPN → LAN", "Allow", "allow"]];
  const dpi = [["Streaming Media", 42], ["Web", 23], ["Business", 14], ["VoIP / Video Conf", 9], ["File Transfer", 7], ["Other", 5]];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
      <div className="panel"><div className="panel-h"><h3><Icon name="shield" /> Firewall Zones</h3></div>
        <table className="tbl"><thead><tr><th>Policy</th><th>Action</th><th className="r">Status</th></tr></thead>
          <tbody>{zones.map((z, i) => (<tr key={i}><td className="strong">{z[0]}</td><td><span className={"badge " + (z[2] === "deny" ? "crit" : "info")}>{z[1]}</span></td><td className="r"><span className="st on">Enforced</span></td></tr>))}</tbody></table>
      </div>
      <div className="panel"><div className="panel-h"><h3><Icon name="chart" /> Deep Packet Inspection</h3></div>
        <div className="panel-b">{dpi.map((d, i) => (
          <div key={i} style={{ marginBottom: 11 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: ".8rem", marginBottom: 5 }}><span className="strong">{d[0]}</span><span className="mut">{d[1]}%</span></div>
            <div style={{ height: 7, background: "#eef0f5", borderRadius: 5, overflow: "hidden" }}><div style={{ width: d[1] + "%", height: "100%", background: "var(--teal)", borderRadius: 5 }} /></div>
          </div>))}</div>
      </div>
    </div>
  );
}

/* ---- Site Health tab ---- */
function SiteHealthTab() {
  const f = DEMO.focus;
  return (
    <div>
      <div className="tiles c4" style={{ marginBottom: 14 }}>
        <div className="tile crit"><div className="tk crit">Offline Devices</div><div className="tv crit">{f.offline}</div></div>
        <div className="tile"><div className="tk">WAN Uptime</div><div className="tv green">{f.uptime.toFixed(1)}%</div></div>
        <div className="tile"><div className="tk">Critical Alerts</div><div className="tv teal">{f.health.criticalAlerts}</div></div>
        <div className="tile"><div className="tk">Events</div><div className="tv">{f.health.events}</div></div>
      </div>
      <div className="panel crit" style={{ marginBottom: 14 }}>
        <div className="panel-h"><h3 style={{ color: "var(--red)" }}>Offline Devices</h3></div>
        <table className="tbl"><thead><tr><th>Name</th><th>Type</th><th>Model</th><th>IP</th><th>Last Seen</th></tr></thead>
          <tbody><tr><td className="strong">US 8 60W</td><td><span className="dtag gen">US8P60</span></td><td>US 8 60W</td><td className="lk">10.0.17.174</td><td className="mut">27 days ago</td></tr></tbody></table>
      </div>
      <div className="panel">
        <div className="panel-h"><h3><Icon name="prompt" /> Site Event Log</h3></div>
        <div className="log">{DEMO.siteEvents.map((e, i) => (
          <div key={i} className={"log-row " + (e[1] === "CRITICAL" ? "crit" : "info")}>
            <span className="tm">{e[0]}</span><span className={"sv " + (e[1] === "CRITICAL" ? "crit" : "info")}>{e[1]}</span><span className="ty">{e[2]}</span><span className="ms">{e[3]} — {e[4]}</span>
          </div>))}</div>
      </div>
    </div>
  );
}

/* ---- Updates tab ---- */
function UpdatesTab() {
  return (
    <div className="panel">
      <div className="panel-h"><h3><Icon name="download" /> Firmware Updates Available ({DEMO.firmware.length})</h3></div>
      <table className="tbl">
        <thead><tr><th>Status</th><th>Name</th><th>Model</th><th>Current Firmware</th><th>Available Update</th><th className="r">Action</th></tr></thead>
        <tbody>{DEMO.firmware.map((u, i) => (
          <tr key={i}><td><span className="st off">OFFLINE</span></td><td className="strong">{u.name}</td><td>{u.model}</td><td className="mut">{u.current}</td>
            <td><span className="fwnew">{u.update}</span></td><td className="r"><span className="mut" style={{ color: "var(--red)", fontWeight: 700 }}>Offline</span></td></tr>))}</tbody>
      </table>
    </div>
  );
}

/* ---- Topology tab ---- */
function TopologyTab() {
  const node = (icon, nm, sub, on = true) => (
    <div className="topo-node"><span className={"pd " + (on ? "on" : "off")} /><div className="nn"><Icon name={icon} style={{ width: 14, height: 14, color: "var(--ink-dim)" }} /> {nm}</div><div className="ns">{sub}</div></div>
  );
  return (
    <div>
      <div className="topo-bar">
        <span className="sp"><Icon name="router" /> 1 Gateway</span>
        <span className="sp"><Icon name="switch" /> 18 Switches</span>
        <span className="sp"><Icon name="ap" /> 34 APs</span>
        <span className="sp" style={{ color: "var(--green)" }}>● 52 Online</span>
        <span className="sp" style={{ color: "var(--red)" }}>● 1 Offline</span>
        <span className="sp"><Icon name="customers" /> 70 Clients</span>
        <span className="right"><button className="btn">Hide APs</button><button className="btn">Show Clients</button><button className="btn solid"><Icon name="refresh" /> Refresh</button></span>
      </div>
      <div className="topo-stage">
        <div className="topo-legend">
          <h5>Network Legend</h5>
          {DEMO.vlans.slice(0, 9).map((v, i) => <div key={i} className="vl"><span className="nm">{v[0]}</span><span className="ip">{v[1]}</span></div>)}
        </div>
        <div className="topo-tree">
          <div className="topo-node inet"><div className="nn"><Icon name="globe" style={{ width: 14, height: 14 }} /> Internet</div><div className="ns" style={{ color: "rgba(255,255,255,.7)" }}>WAN · 4.1.171.115</div></div>
          {node("router", "Northwind Studios | HQ", "UDM-Ent")}
          <div className="topo-row">
            {node("switch", "Main Fiber Switch", "10.0.16.115")}
            {node("switch", "Call Center Sw 2", "10.0.16.78")}
            {node("switch", "B Main Switch", "10.0.17.44")}
            {node("switch", "2nd Flr East", "10.0.17.48")}
          </div>
          <div className="topo-row">
            {node("ap", "AP | Studio J 2", "10.0.17.147")}
            {node("ap", "AP | Bullpen 1", "10.0.17.74")}
            {node("ap", "AP | Serverroom", "10.0.17.204")}
            {node("ap", "AP | MH 02", "10.0.17.125")}
            {node("switch", "US 8 60W", "offline", false)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---- AI Assistant tab ---- */
function AITab() {
  const [msgs, setMsgs] = useState([]);
  const [approved, setApproved] = useState({});
  const bodyRef = useRef(null);
  useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, approved]);

  const responses = {
    offline: { tool: "called list_devices · get_site_health", body: (<>One device is currently offline on <strong>Northwind Studios | HQ</strong>:<ul><li><i style={{ background: "var(--red)" }} /><strong>US 8 60W</strong> — switch · <code>10.0.17.174</code> · down 26 days</li></ul></>), action: { tool: "restart_device", desc: "This will power-cycle US 8 60W (10.0.17.174). The assistant won't run it until you approve." } },
    clients: { tool: "called list_clients", body: (<>This site has <strong>144 connected clients</strong> — 67 on WiFi and 77 wired. No guest clients are currently active. The busiest VLAN is <code>#20 Office Network</code>.</>) },
    firmware: { tool: "called get_firmware_status", body: (<>1 device has a firmware update pending: <strong>US 8 60W</strong> → <code>7.4.1.16850</code>. It's currently offline, so the update is queued until it reconnects.</>) },
    latency: { tool: "called get_isp_health", body: (<>WAN uptime is <strong>100%</strong> over 7 days. Average latency is 9ms (peak 66ms) with 0.17% packet loss — well within healthy range for Lumen.</>) },
  };
  const chips = [["Which devices are offline?", "offline"], ["How many clients are connected?", "clients"], ["Any firmware updates pending?", "firmware"], ["How's the ISP latency?", "latency"]];

  const ask = (text, key) => {
    const r = responses[key];
    const id = Date.now();
    setMsgs(m => [...m, { who: "user", text }, { who: "bot", ...r, id }]);
  };

  return (
    <div className="ai">
      <div className="ai-h"><span className="t"><Icon name="ai" /> Site Assistant</span><span className="ai-model"><i /> Claude · Sonnet</span></div>
      <div className="ai-body" ref={bodyRef}>
        {msgs.length === 0 && (
          <div className="ai-msg bot"><div className="ai-bb">Hi — I'm the assistant for <strong>Northwind Studios | HQ</strong>. Ask me about devices, clients, firewall rules or ISP health. I can read everything; any change I make pauses for your approval.</div></div>
        )}
        {msgs.map((m, i) => m.who === "user" ? (
          <div key={i} className="ai-msg user">{m.text}</div>
        ) : (
          <div key={i} className="ai-msg bot">
            <span className="ai-tool"><Icon name="file" /> {m.tool}</span>
            <div className="ai-bb">{m.body}
              {m.action && (
                <div className={"ai-approve" + (approved[m.id] ? " done" : "")}>
                  {approved[m.id] ? (
                    <div className="aw" style={{ color: "var(--green)" }}><Icon name="check" /> Approved — restart_device queued on US 8 60W.</div>
                  ) : (<>
                    <div className="aw"><Icon name="alerts" /> Approval required · {m.action.tool}</div>
                    <div className="desc">{m.action.desc}</div>
                    <div className="ab"><button className="ok" onClick={() => setApproved(a => ({ ...a, [m.id]: true }))}>Approve</button><button className="no" onClick={() => setApproved(a => ({ ...a, [m.id]: "no" }))}>Deny</button></div>
                  </>)}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      <div className="ai-foot">
        <div className="ai-chips">{chips.map(([t, k]) => <button key={k} className="ai-chip" onClick={() => ask(t, k)}>{t}</button>)}</div>
        <div className="ai-input"><input placeholder="Ask about devices, clients, firewall rules, signal…" onKeyDown={e => { if (e.key === "Enter" && e.target.value.trim()) { ask(e.target.value, "offline"); e.target.value = ""; } }} /><button onClick={() => ask("Which devices are offline?", "offline")}><Icon name="prompt" style={{ width: 18, height: 18 }} /></button></div>
      </div>
    </div>
  );
}

Object.assign(window, { SiteDetail });
