/* global React */
const { useState, useMemo } = React;

// ---------- Mock inventory ----------
const ASSETS = [
  {
    id: "AST-10421", host: "srv-lyon-db-01", type: "server", typeLabel: "Server",
    vendor: "Dell", model: "PowerEdge R750", serial: "DLPE-R750-7821J",
    cpu: "2× Xeon Gold 6354 (36c)", ram: "512 GB DDR4", storage: "8× 1.92TB NVMe", os: "RHEL 9.3",
    rack: "titan-33", room: "Hall B", uPos: "U22-U23", uSize: 2, status: "prod", role: "BDD prod",
    health: "warn", cpuUtz: 72, memUtz: 84, powerW: 612, ipv4: "10.42.7.11",
    purchase: "2023-04-12", warrantyEnd: "2027-04-12", warrantyDays: 522,
    tags: ["bdd", "prod", "p1"],
    nics: [
      { name: "eth0", speed: "25G", status: "up", peer: "switch-tor-d03 · gi1/12" },
      { name: "eth1", speed: "25G", status: "up", peer: "switch-tor-d03 · gi1/13" },
      { name: "ipmi", speed: "1G", status: "up", peer: "switch-mgmt · gi0/22" },
    ],
    activity: [
      { t: "4 min ago", text: "Alert AL-2034 · loss de redondance PSU2", sev: "crit" },
      { t: "2j", text: "Maintenance schedulede completede — patch kernel 5.14.0-362", sev: "ok" },
      { t: "3 sem", text: "Moved U20 → U22 by M. Cooper", sev: "info" },
      { t: "8 mois", text: "Mise en production · ticket TIC-0918", sev: "info" },
    ],
  },
  {
    id: "AST-10422", host: "srv-lyon-db-02", type: "server", typeLabel: "Server",
    vendor: "Dell", model: "PowerEdge R750", serial: "DLPE-R750-7822K",
    cpu: "2× Xeon Gold 6354 (36c)", ram: "512 GB DDR4", storage: "8× 1.92TB NVMe", os: "RHEL 9.3",
    rack: "titan-33", room: "Hall B", uPos: "U24-U25", uSize: 2, status: "prod", role: "BDD replica",
    health: "ok", cpuUtz: 38, memUtz: 61, powerW: 540, ipv4: "10.42.7.12",
    purchase: "2023-04-12", warrantyEnd: "2027-04-12", warrantyDays: 522,
    tags: ["bdd", "prod"],
  },
  {
    id: "AST-10417", host: "srv-lyon-app-04", type: "server", typeLabel: "Server",
    vendor: "HPE", model: "ProLiant DL380 Gen10", serial: "HPED-7710-09Z",
    cpu: "2× Xeon Silver 4214 (24c)", ram: "256 GB DDR4", storage: "4× 960GB SSD",
    rack: "mars-12", room: "Hall B", uPos: "U18-U19", uSize: 2, status: "prod", role: "App backend",
    health: "warn", cpuUtz: 54, memUtz: 73, powerW: 410, ipv4: "10.42.5.34",
    purchase: "2021-09-02", warrantyEnd: "2025-09-02", warrantyDays: -242, os: "Ubuntu 22.04",
    tags: ["app", "prod", "warn"],
  },
  {
    id: "AST-10399", host: "srv-lyon-app-07", type: "server", typeLabel: "Server",
    vendor: "Dell", model: "PowerEdge R650", serial: "DLPE-R650-4412M",
    cpu: "2× Xeon Silver 4314 (32c)", ram: "256 GB DDR4", storage: "2× 480GB SSD",
    rack: "titan-33", room: "Hall B", uPos: "U10-U11", uSize: 2, status: "prod", role: "App backend",
    health: "ok", cpuUtz: 41, memUtz: 55, powerW: 318, ipv4: "10.42.5.37",
    purchase: "2024-02-14", warrantyEnd: "2028-02-14", warrantyDays: 829, os: "Ubuntu 22.04",
    tags: ["app", "prod"],
  },
  {
    id: "AST-10210", host: "switch-core-02", type: "network", typeLabel: "Switch core",
    vendor: "Cisco", model: "Nexus 9336C-FX2", serial: "FOX2502N0XK",
    cpu: "—", ram: "32 GB", storage: "120 GB SSD",
    rack: "mercury-11", room: "Hall A", uPos: "U40-U41", uSize: 2, status: "maint", role: "Core uplink",
    health: "warn", powerW: 380, ipv4: "10.42.0.2",
    purchase: "2022-06-30", warrantyEnd: "2027-06-30", warrantyDays: 601, os: "NX-OS 10.3",
    tags: ["network", "core", "maintenance"],
  },
  {
    id: "AST-10211", host: "switch-tor-d03", type: "network", typeLabel: "Switch ToR",
    vendor: "Arista", model: "7050SX3-48YC8", serial: "JPE21340421",
    cpu: "—", ram: "16 GB", storage: "32 GB",
    rack: "titan-33", room: "Hall B", uPos: "U42", uSize: 1, status: "prod", role: "ToR titan-33",
    health: "ok", powerW: 220, ipv4: "10.42.0.43",
    purchase: "2023-04-12", warrantyEnd: "2028-04-12", warrantyDays: 887,
    tags: ["network", "tor"],
  },
  {
    id: "AST-10610", host: "pdu-d03-a", type: "pdu", typeLabel: "PDU",
    vendor: "APC", model: "AP8959EU3", serial: "ZA2147005012",
    cpu: "—", ram: "—", storage: "—",
    rack: "titan-33", room: "Hall B", uPos: "ZeroU", uSize: 0, status: "prod", role: "PDU phase A",
    health: "crit", powerW: 5920, ipv4: "10.42.10.31",
    purchase: "2021-11-04", warrantyEnd: "2026-11-04", warrantyDays: 188,
    tags: ["pdu", "energy", "p1"],
  },
  {
    id: "AST-10611", host: "pdu-d03-b", type: "pdu", typeLabel: "PDU",
    vendor: "APC", model: "AP8959EU3", serial: "ZA2147005013",
    cpu: "—", ram: "—", storage: "—",
    rack: "titan-33", room: "Hall B", uPos: "ZeroU", uSize: 0, status: "prod", role: "PDU phase B",
    health: "ok", powerW: 4810, ipv4: "10.42.10.32",
    purchase: "2021-11-04", warrantyEnd: "2026-11-04", warrantyDays: 188,
    tags: ["pdu", "energy"],
  },
  {
    id: "AST-10520", host: "ups-lyon-1", type: "ups", typeLabel: "UPS",
    vendor: "Eaton", model: "9PX 11000i", serial: "GB22340092",
    cpu: "—", ram: "—", storage: "—",
    rack: "—", room: "Local TGBT", uPos: "—", uSize: 0, status: "prod", role: "UPS principal",
    health: "ok", powerW: 8400, ipv4: "10.42.10.1",
    purchase: "2020-08-10", warrantyEnd: "2025-08-10", warrantyDays: -283,
    tags: ["energy", "UPS"],
  },
  {
    id: "AST-10310", host: "san-prim-01", type: "storage", typeLabel: "Rack de stockage",
    vendor: "NetApp", model: "AFF A400", serial: "721934-22",
    cpu: "—", ram: "256 GB cache", storage: "240 TB usable NVMe",
    rack: "mars-07", room: "Hall B", uPos: "U30-U33", uSize: 4, status: "prod", role: "SAN primaire",
    health: "ok", powerW: 1840, ipv4: "10.42.6.10",
    purchase: "2023-09-14", warrantyEnd: "2028-09-14", warrantyDays: 1042,
    tags: ["stockage", "san"],
  },
  {
    id: "AST-10101", host: "srv-lyon-app-12", type: "server", typeLabel: "Server",
    vendor: "Dell", model: "PowerEdge R640", serial: "DLPE-R640-1102D",
    cpu: "2× Xeon Gold 6230", ram: "192 GB", storage: "2× 480GB SSD",
    rack: "mercury-15", room: "Hall A", uPos: "U14-U15", uSize: 2, status: "sbye", role: "Sbye cold",
    health: "off", powerW: 0, ipv4: "—",
    purchase: "2020-03-01", warrantyEnd: "2024-03-01", warrantyDays: -796, os: "—",
    tags: ["sbye", "eol"],
  },
  {
    id: "AST-10102", host: "srv-lyon-app-13", type: "server", typeLabel: "Server",
    vendor: "Dell", model: "PowerEdge R640", serial: "DLPE-R640-1102E",
    cpu: "2× Xeon Gold 6230", ram: "192 GB", storage: "2× 480GB SSD",
    rack: "mercury-15", room: "Hall A", uPos: "U16-U17", uSize: 2, status: "eol", role: "Decommissionnement",
    health: "off", powerW: 0, ipv4: "—",
    purchase: "2020-03-01", warrantyEnd: "2024-03-01", warrantyDays: -796, os: "—",
    tags: ["eol", "deco"],
  },
  {
    id: "AST-10705", host: "kvm-bay-d03", type: "kvm", typeLabel: "KVM",
    vendor: "Avocent", model: "ACS8016", serial: "AV81-D03-00",
    cpu: "—", ram: "—", storage: "—",
    rack: "titan-33", room: "Hall B", uPos: "U01", uSize: 1, status: "prod", role: "Drawle out-of-band",
    health: "ok", powerW: 32, ipv4: "10.42.20.3",
    purchase: "2022-02-15", warrantyEnd: "2027-02-15", warrantyDays: 466,
    tags: ["kvm", "ooba"],
  },
  {
    id: "AST-10220", host: "fw-lyon-1", type: "network", typeLabel: "Firewall",
    vendor: "Fortinet", model: "FortiGate 600F", serial: "FGT60FT9201",
    cpu: "—", ram: "32 GB", storage: "240 GB SSD",
    rack: "mercury-11", room: "Hall A", uPos: "U38-U39", uSize: 2, status: "prod", role: "Firewall perimeter",
    health: "ok", powerW: 280, ipv4: "10.42.0.1",
    purchase: "2024-05-22", warrantyEnd: "2029-05-22", warrantyDays: 1295,
    tags: ["network", "security"],
  },
];

const TYPES = {
  server:  { label: "Servers",  ico: "▤" },
  network: { label: "Network",    ico: "⤧" },
  storage: { label: "Storage",  ico: "▥" },
  pdu:     { label: "PDU",       ico: "⌁" },
  ups:     { label: "UPSs", ico: "⏚" },
  kvm:     { label: "KVM/drawle", ico: "⌨" },
};
const STATUSES = {
  prod: "Production", maint: "Maintenance", sbye: "Sbye", eol: "Fin de vie", deco: "Decommiss.",
};

// ---------- Helpers ----------
const fmtPower = (w) => w >= 1000 ? `${(w / 1000).toFixed(2)} kW` : `${w} W`;

const warrantyClass = (d) => d < 0 ? "danger" : d < 90 ? "warn" : "ok";
const warrantyText = (d) => d < 0 ? `expired ${-d}j` : `${d}j restants`;

// ---------- KPIs ----------
function InvKpis({ assets }) {
  const total = assets.length;
  const byType = (t) => assets.filter(a => a.type === t).length;
  const totalPower = assets.reduce((s, a) => s + (a.powerW || 0), 0);
  const expired = assets.filter(a => a.warrantyDays < 0).length;
  const warningSoon = assets.filter(a => a.warrantyDays >= 0 && a.warrantyDays < 365).length;
  const eol = assets.filter(a => a.status === "eol").length;
  const sbye = assets.filter(a => a.status === "sbye").length;

  return (
    <div className="inv-kpis">
      <div className="inv-kpi accent">
        <div className="inv-kpi-label">Actives total</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{total}<span>équipements</span></div>
          <div className="inv-kpi-trend up">▲ +4</div>
        </div>
        <div className="inv-kpi-sub">vs mois previous</div>
      </div>
      <div className="inv-kpi info">
        <div className="inv-kpi-label">Servers</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{byType("server")}</div>
        </div>
        <div className="inv-kpi-sub">dont {assets.filter(a => a.type === "server" && a.status === "prod").length} en prod</div>
      </div>
      <div className="inv-kpi info">
        <div className="inv-kpi-label">Network</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{byType("network")}</div>
        </div>
        <div className="inv-kpi-sub">switches, routeurs, firewalls</div>
      </div>
      <div className="inv-kpi ok">
        <div className="inv-kpi-label">Storage</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{byType("storage")}</div>
        </div>
        <div className="inv-kpi-sub">240 TB utilisables</div>
      </div>
      <div className="inv-kpi warn">
        <div className="inv-kpi-label">Draw. aggregated</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{(totalPower / 1000).toFixed(1)}<span>kW</span></div>
        </div>
        <div className="inv-kpi-sub">real-time · 14:35</div>
      </div>
      <div className="inv-kpi danger">
        <div className="inv-kpi-label">Hors garantie</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{expired}</div>
          <div className="inv-kpi-trend down">▲ +1</div>
        </div>
        <div className="inv-kpi-sub">{warningSoon} expirent &lt; 12 mois</div>
      </div>
      <div className="inv-kpi">
        <div className="inv-kpi-label">EOL / sbye</div>
        <div className="inv-kpi-row">
          <div className="inv-kpi-val">{eol}<span>/ {sbye}</span></div>
        </div>
        <div className="inv-kpi-sub">à decommissionner / availables</div>
      </div>
    </div>
  );
}

// ---------- Filter rail ----------
function InvRail({ filters, setFilters, assets }) {
  const count = (pred) => assets.filter(pred).length;

  const types = Object.entries(TYPES).map(([k, v]) => ({ id: k, label: v.label, ico: v.ico, n: count(a => a.type === k) }));
  const statuses = Object.entries(STATUSES).map(([k, v]) => ({ id: k, label: v, n: count(a => a.status === k) }));
  const vendors = ["Dell", "HPE", "Cisco", "Arista", "APC", "Eaton", "NetApp", "Avocent", "Fortinet"]
    .map(v => ({ id: v, label: v, n: count(a => a.vendor === v) }))
    .filter(v => v.n);
  const tree = [
    { lvl: 1, id: "Site mars-7", n: assets.length },
    { lvl: 2, id: "Hall A", n: count(a => a.room === "Hall A") },
    { lvl: 3, id: "mercury-11", n: count(a => a.rack === "mercury-11") },
    { lvl: 3, id: "mercury-15", n: count(a => a.rack === "mercury-15") },
    { lvl: 2, id: "Hall B", n: count(a => a.room === "Hall B") },
    { lvl: 3, id: "mars-07", n: count(a => a.rack === "mars-07") },
    { lvl: 3, id: "mars-12", n: count(a => a.rack === "mars-12") },
    { lvl: 3, id: "titan-33", n: count(a => a.rack === "titan-33") },
    { lvl: 2, id: "Local TGBT", n: count(a => a.room === "Local TGBT") },
  ];

  const toggle = (key, val) => {
    const cur = new Set(filters[key]);
    if (cur.has(val)) cur.delete(val); else cur.add(val);
    setFilters({ ...filters, [key]: [...cur] });
  };

  return (
    <aside className="inv-rail">
      <div>
        <div className="rail-section-title">Vues saved</div>
        <div className="saved-views">
          <div className="saved-view"><span className="sv-icon">★</span><span>Hors garantie</span><span className="sv-count">3</span></div>
          <div className="saved-view"><span className="sv-icon">◆</span><span>BDD prod</span><span className="sv-count">2</span></div>
          <div className="saved-view"><span className="sv-icon">⚠</span><span>Health degradede</span><span className="sv-count">3</span></div>
          <div className="saved-view"><span className="sv-icon">↺</span><span>Acquis &lt; 30 j</span><span className="sv-count">0</span></div>
        </div>
      </div>

      <div>
        <div className="rail-section-title">Localisation</div>
        <ul className="inv-tree">
          {tree.map(t => (
            <li key={t.id}
                className={`tree-l${t.lvl} ${filters.location === t.id ? "active" : ""}`}
                onClick={() => setFilters({ ...filters, location: filters.location === t.id ? "" : t.id })}>
              <span>{t.lvl === 3 ? "↳ " : ""}{t.id}</span>
              <span className="tcount">{t.n}</span>
            </li>
          ))}
        </ul>
      </div>

      <div>
        <div className="rail-section-title">
          <span>Type</span>
          <a href="#" onClick={e => { e.preventDefault(); setFilters({ ...filters, type: [] }); }}>all</a>
        </div>
        <ul className="rail-list">
          {types.map(t => (
            <li key={t.id}
                className={`rail-item ${filters.type?.includes(t.id) ? "active" : ""}`}
                onClick={() => toggle("type", t.id)}>
              <span className="ico">{t.ico}</span>
              <span>{t.label}</span>
              <span className="rail-count">{t.n}</span>
            </li>
          ))}
        </ul>
      </div>

      <div>
        <div className="rail-section-title">
          <span>Status</span>
          <a href="#" onClick={e => { e.preventDefault(); setFilters({ ...filters, status: [] }); }}>all</a>
        </div>
        <ul className="rail-list">
          {statuses.map(s => (
            <li key={s.id}
                className={`rail-item ${filters.status?.includes(s.id) ? "active" : ""}`}
                onClick={() => toggle("status", s.id)}>
              <span className="ico">·</span>
              <span>{s.label}</span>
              <span className="rail-count">{s.n}</span>
            </li>
          ))}
        </ul>
      </div>

      <div>
        <div className="rail-section-title">
          <span>Constructeur</span>
          <a href="#" onClick={e => { e.preventDefault(); setFilters({ ...filters, vendor: [] }); }}>all</a>
        </div>
        <ul className="rail-list">
          {vendors.map(v => (
            <li key={v.id}
                className={`rail-item ${filters.vendor?.includes(v.id) ? "active" : ""}`}
                onClick={() => toggle("vendor", v.id)}>
              <span className="ico">▢</span>
              <span>{v.label}</span>
              <span className="rail-count">{v.n}</span>
            </li>
          ))}
        </ul>
      </div>
    </aside>
  );
}

// ---------- Detail ----------
function AssetDetail({ a }) {
  const [tab, setTab] = useState("overview");

  if (!a) {
    return (
      <div className="inv-detail">
        <div className="empty-id">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
            <rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/>
          </svg>
          <div>Select un active pour view sa fiche.</div>
        </div>
      </div>
    );
  }

  const lifecycle = ["Achat", "Stock", "En prod", "Maintenance", "EOL", "Decommiss."];
  const stageMap = { prod: 2, maint: 3, sbye: 1, eol: 4, deco: 5 };
  const stage = stageMap[a.status] ?? 2;

  return (
    <div className="inv-detail">
      <div className="id-head">
        <div className="id-title">{a.host}</div>
        <div className="id-sub">
          <span className={`type-pill ${a.type}`}><span className="ti"/>{a.typeLabel}</span>
          <span>·</span>
          <b>{a.vendor}</b>
          <span>{a.model}</span>
        </div>
        <div className="id-pills">
          <span className={`status-pill ${a.status}`}>{STATUSES[a.status]}</span>
          <span className="tag" style={{fontFamily: "var(--mono)"}}>{a.id}</span>
          <span className="tag">{a.rack} · {a.uPos}</span>
          <span className="tag">{a.room}</span>
        </div>
      </div>

      <div className="id-actions">
        <button className="btn primary">Éditer</button>
        <button className="btn">Move</button>
        <button className="btn">Label</button>
        <button className="btn ghost">Decommiss.</button>
      </div>

      <div className="id-tabs">
        <button className={tab === "overview" ? "active" : ""} onClick={() => setTab("overview")}>Overview</button>
        <button className={tab === "specs" ? "active" : ""} onClick={() => setTab("specs")}>Specs</button>
        <button className={tab === "network" ? "active" : ""} onClick={() => setTab("network")}>Network</button>
        <button className={tab === "lifecycle" ? "active" : ""} onClick={() => setTab("lifecycle")}>Cycle de vie</button>
        <button className={tab === "history" ? "active" : ""} onClick={() => setTab("history")}>History</button>
      </div>

      <div className="id-body">
        {tab === "overview" && (
          <>
            <div className="id-section">
              <div className="id-section-title">Vue rack · face avant</div>
              <div className="asset-hero">
                <div className="asset-fig">
                  <div className="face">
                    {Array.from({ length: Math.max(a.uSize, 1) }, (_, i) => <div key={i} className="row"/>)}
                  </div>
                </div>
                <div className="asset-info-grid">
                  <div className="k">Role</div><div className="v">{a.role}</div>
                  <div className="k">Position</div><div className="v">{a.rack} · {a.uPos}</div>
                  <div className="k">Hall</div><div className="v">{a.room}</div>
                  <div className="k">Health</div>
                  <div className="v"><span className="health-cell"><span className={`health-dot ${a.health}`}/>{a.health === "ok" ? "Nameinal" : a.health === "warn" ? "Degraded" : a.health === "crit" ? "Critical" : "Offline"}</span></div>
                  <div className="k">IPv4</div><div className="v">{a.ipv4}</div>
                </div>
              </div>
            </div>

            <div className="id-section">
              <div className="id-section-title">Indicateurs real-time</div>
              <div className="spec-grid">
                {a.cpuUtz !== undefined && (
                  <div className="spec-tile">
                    <div className="k">CPU</div>
                    <div className="v">{a.cpuUtz}<span>%</span></div>
                    <div className="spec-bar"><div style={{width: `${a.cpuUtz}%`, background: a.cpuUtz > 80 ? "var(--danger)" : a.cpuUtz > 60 ? "var(--warn)" : "var(--ok)"}}/></div>
                    <div className="sub">moy. 1h · 67%</div>
                  </div>
                )}
                {a.memUtz !== undefined && (
                  <div className="spec-tile">
                    <div className="k">Memory</div>
                    <div className="v">{a.memUtz}<span>%</span></div>
                    <div className="spec-bar"><div style={{width: `${a.memUtz}%`, background: a.memUtz > 85 ? "var(--danger)" : a.memUtz > 70 ? "var(--warn)" : "var(--ok)"}}/></div>
                    <div className="sub">{Math.round(a.memUtz * 5.12)} GB / 512 GB</div>
                  </div>
                )}
                <div className="spec-tile">
                  <div className="k">Draw.</div>
                  <div className="v">{a.powerW}<span>W</span></div>
                  <div className="spec-bar"><div style={{width: `${Math.min(100, a.powerW / 15)}%`, background: "var(--info)"}}/></div>
                  <div className="sub">~{(a.powerW * 24 / 1000).toFixed(1)} kWh / jour</div>
                </div>
                <div className="spec-tile">
                  <div className="k">Warranty</div>
                  <div className="v" style={{color: a.warrantyDays < 0 ? "var(--danger)" : a.warrantyDays < 365 ? "var(--warn)" : "var(--text)"}}>
                    {Math.abs(a.warrantyDays)}<span>j</span>
                  </div>
                  <div className="sub">{a.warrantyDays < 0 ? "expired" : "restants"} · {a.warrantyEnd}</div>
                </div>
              </div>
            </div>

            <div className="id-section">
              <div className="id-section-title">Identity</div>
              <div className="id-kv">
                <div><div className="k">Asset ID</div><div className="v">{a.id}</div></div>
                <div><div className="k">Hostname</div><div className="v">{a.host}</div></div>
                <div><div className="k">Serial</div><div className="v">{a.serial}</div></div>
                <div><div className="k">Model</div><div className="v">{a.model}</div></div>
                <div><div className="k">Achat</div><div className="v">{a.purchase}</div></div>
                <div><div className="k">Fin garantie</div><div className="v">{a.warrantyEnd}</div></div>
              </div>
            </div>

            <div className="id-section">
              <div className="id-section-title">Tags</div>
              <div className="tag-row">{a.tags.map(t => <span key={t} className="tag">{t}</span>)}</div>
            </div>
          </>
        )}

        {tab === "specs" && (
          <div className="id-section">
            <div className="id-section-title">Specifications hardwareles</div>
            <div className="id-kv">
              <div><div className="k">CPU</div><div className="v">{a.cpu}</div></div>
              <div><div className="k">Memory</div><div className="v">{a.ram}</div></div>
              <div><div className="k">Storage</div><div className="v">{a.storage}</div></div>
              <div><div className="k">OS / firmware</div><div className="v">{a.os || "—"}</div></div>
              <div><div className="k">Format</div><div className="v">{a.uSize}U</div></div>
              <div><div className="k">Draw. nameinale</div><div className="v">{fmtPower(a.powerW)}</div></div>
            </div>
            <div className="id-section-title" style={{marginTop: 12}}>Documentation</div>
            <div className="related-list">
              <div className="related-item"><span className="ri-type">DOC</span><span className="ri-text">Datasheet {a.model}</span><span className="ri-meta">PDF · 4.2 MB</span></div>
              <div className="related-item"><span className="ri-type">DOC</span><span className="ri-text">Procedure d'installation interne</span><span className="ri-meta">v2 · 12p</span></div>
              <div className="related-item"><span className="ri-type">URL</span><span className="ri-text">Portail support {a.vendor}</span><span className="ri-meta">↗</span></div>
            </div>
          </div>
        )}

        {tab === "network" && (
          <div className="id-section">
            <div className="id-section-title">Interfaces network</div>
            <table className="mini-table">
              <thead><tr><th>Port</th><th>Speed</th><th>État</th><th>Voisin</th></tr></thead>
              <tbody>
                {(a.nics || [
                  { name: "eth0", speed: "10G", status: "up", peer: a.rack ? `tor-${a.rack.toLowerCase()}` : "—" },
                  { name: "ipmi", speed: "1G", status: a.health === "off" ? "down" : "up", peer: "switch-mgmt" },
                ]).map((n, i) => (
                  <tr key={i}>
                    <td>{n.name}</td>
                    <td>{n.speed}</td>
                    <td className={n.status}>● {n.status}</td>
                    <td style={{color: "var(--text-dim)"}}>{n.peer}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="id-section-title" style={{marginTop: 12}}>Adresses</div>
            <div className="id-kv">
              <div><div className="k">IPv4</div><div className="v">{a.ipv4}</div></div>
              <div><div className="k">IPv6</div><div className="v">2001:db8:42::{a.id.slice(-3)}</div></div>
              <div><div className="k">VLAN</div><div className="v">prod-app · 142</div></div>
              <div><div className="k">DNS</div><div className="v">{a.host}.lyon-1.dc</div></div>
            </div>
          </div>
        )}

        {tab === "lifecycle" && (
          <>
            <div className="id-section">
              <div className="id-section-title">Cycle de vie</div>
              <div className="lifecycle">
                {lifecycle.map((s, i) => (
                  <div key={i} className={`seg ${i === stage ? "active" : i < stage ? "done" : ""}`}>
                    {s}
                  </div>
                ))}
              </div>
              <div style={{display: "flex", justifyContent: "space-between", fontSize: 10, fontFamily: "var(--mono)", color: "var(--text-dim)", marginTop: 4}}>
                <span>{a.purchase}</span>
                <span>aujourd'hui</span>
                <span>{a.warrantyEnd}</span>
              </div>
            </div>
            <div className="id-section">
              <div className="id-section-title">Warranty & contrat</div>
              <div className="id-kv">
                <div><div className="k">Niveau support</div><div className="v">ProSupport 24×7</div></div>
                <div><div className="k">Contrat</div><div className="v">CTR-2023-{a.id.slice(-4)}</div></div>
                <div><div className="k">Start</div><div className="v">{a.purchase}</div></div>
                <div><div className="k">Fin</div><div className="v" style={{color: a.warrantyDays < 0 ? "var(--danger)" : "inherit"}}>{a.warrantyEnd}</div></div>
              </div>
            </div>
            <div className="id-section">
              <div className="id-section-title">Position dans le rack {a.rack}</div>
              <div className="rack-map">
                <div className="rack-map-grid">
                  {Array.from({ length: 32 }, (_, i) => {
                    const isHere = i >= 8 && i < 8 + Math.max(a.uSize, 1);
                    return <div key={i} className={`rm-cell ${isHere ? "has you" : i % 5 === 2 ? "has" : ""}`}>{`U${32 - i}`}</div>;
                  })}
                </div>
              </div>
            </div>
          </>
        )}

        {tab === "history" && (
          <div className="id-section">
            <div className="id-section-title">History</div>
            <ul className="id-activity">
              {(a.activity || [
                { t: "2h", text: "Patch firmware applied — version 4.2.1", sev: "ok" },
                { t: "12 j", text: "Inspection physique — label renewed", sev: "info" },
                { t: "3 mois", text: "Moved depuis mercury-13 vers " + a.rack, sev: "info" },
                { t: a.purchase, text: "Mis en service", sev: "info" },
              ]).map((e, i) => (
                <li key={i}>
                  <span className={`tdot ${e.sev}`}/>
                  <span className="text">{e.text}</span>
                  <span className="time">{e.t}</span>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}

// ---------- Main view ----------
function VueInventory() {
  const [filters, setFilters] = useState({ type: [], status: [], vendor: [], location: "", tags: [] });
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(ASSETS[0]);
  const [checked, setChecked] = useState(new Set());
  const [view, setView] = useState("table");
  const [sort, setSort] = useState("host");

  const filtered = useMemo(() => {
    let r = ASSETS.filter(a => {
      if (filters.type.length && !filters.type.includes(a.type)) return false;
      if (filters.status.length && !filters.status.includes(a.status)) return false;
      if (filters.vendor.length && !filters.vendor.includes(a.vendor)) return false;
      if (filters.location) {
        if (![a.room, a.rack, "Site mars-7"].includes(filters.location)) return false;
      }
      if (search) {
        const s = search.toLowerCase();
        if (!`${a.id} ${a.host} ${a.model} ${a.vendor} ${a.serial} ${a.rack} ${a.room} ${a.role}`.toLowerCase().includes(s)) return false;
      }
      return true;
    });
    if (sort === "host") r.sort((a, b) => a.host.localeCombye(b.host));
    if (sort === "rack") r.sort((a, b) => (a.rack || "").localeCombye(b.rack || ""));
    if (sort === "warranty") r.sort((a, b) => a.warrantyDays - b.warrantyDays);
    if (sort === "power") r.sort((a, b) => b.powerW - a.powerW);
    return r;
  }, [filters, search, sort]);

  const toggleCheck = (id) => {
    const s = new Set(checked);
    if (s.has(id)) s.delete(id); else s.add(id);
    setChecked(s);
  };

  return (
    <div className="inv-view" data-screen-label="Inventory">
      {/* Head */}
      <div className="inv-head">
        <div className="inv-title-block">
          <div className="inv-bc">
            <a href="room.html">Site mars-7</a>
            <span>›</span>
            <span className="bc-current">Inventory</span>
          </div>
          <h1>Inventory hardware</h1>
          <div className="inv-meta">
            <span className="dot-pulse"/>
            <span>Sync auto · DCIM ↔ CMDB</span>
            <span className="meta-sep">·</span>
            <span>last discovered : <b>6 min</b></span>
            <span className="meta-sep">·</span>
            <span><b>{ASSETS.length}</b> actives · <b>2</b> halls · <b>7</b> racks</span>
          </div>
        </div>
        <div className="inv-actions">
          <input className="inv-search" placeholder="Search hostname, serial, model, IP…" value={search} onChange={e => setSearch(e.target.value)}/>
          <div className="inv-seg">
            <button className={view === "table" ? "active" : ""} onClick={() => setView("table")}>Panel</button>
            <button className={view === "cards" ? "active" : ""} onClick={() => setView("cards")}>Cards</button>
          </div>
          <button className="btn">Import CSV</button>
          <button className="btn">Export</button>
          <button className="btn primary">+ Ajouter un active</button>
        </div>
      </div>

      <InvKpis assets={ASSETS}/>

      <div className="inv-body">
        <InvRail filters={filters} setFilters={setFilters} assets={ASSETS}/>

        <div className="inv-list-wrap">
          <div className="inv-toolbar">
            <div className="lt-count">
              {filtered.length} actives<span>sur {ASSETS.length} total</span>
            </div>
            <div className="lt-actions">
              <select className="btn ghost" style={{height: 28, fontSize: 11, paddingRight: 24}}
                      value={sort} onChange={e => setSort(e.target.value)}>
                <option value="host">Sort : hostname ↓</option>
                <option value="rack">Sort : rack ↓</option>
                <option value="warranty">Sort : garantie ↑</option>
                <option value="power">Sort : draw. ↓</option>
              </select>
              <button className="btn ghost" style={{height: 28, fontSize: 11}}>Colonnes</button>
              <button className="btn ghost" style={{height: 28, fontSize: 11}}>Density</button>
            </div>
          </div>

          {checked.size > 0 && (
            <div className="inv-bulk-bar">
              <span className="inv-bulk-count">{checked.size} selected{checked.size > 1 ? "s" : ""}</span>
              <button className="btn ghost" style={{height: 26, fontSize: 11}}>Move…</button>
              <button className="btn ghost" style={{height: 26, fontSize: 11}}>Étiqueter…</button>
              <button className="btn ghost" style={{height: 26, fontSize: 11}}>Export</button>
              <span className="inv-bulk-spacer"/>
              <button className="btn ghost" style={{height: 26, fontSize: 11}} onClick={() => setChecked(new Set())}>Cancel</button>
            </div>
          )}

          {view === "table" && (
            <div className="inv-table-scroll">
              <table className="inv-table">
                <thead>
                  <tr>
                    <th style={{width: 28}}>
                      <span className={`inv-check ${checked.size === filtered.length && filtered.length > 0 ? "on" : ""}`}
                            onClick={() => {
                              if (checked.size === filtered.length) setChecked(new Set());
                              else setChecked(new Set(filtered.map(a => a.id)));
                            }}/>
                    </th>
                    <th style={{width: 14}}></th>
                    <th>Hostname / Asset</th>
                    <th>Type</th>
                    <th>Model</th>
                    <th>Localisation</th>
                    <th>Status</th>
                    <th>Utilization</th>
                    <th className="num">Draw.</th>
                    <th>Warranty</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map(a => {
                    const utz = a.cpuUtz ?? Math.round((a.powerW || 50) / 80);
                    return (
                      <tr key={a.id}
                          className={selected?.id === a.id ? "selected" : ""}
                          onClick={() => setSelected(a)}>
                        <td onClick={e => e.stopPropagation()}>
                          <span className={`inv-check ${checked.has(a.id) ? "on" : ""}`}
                                onClick={() => toggleCheck(a.id)}/>
                        </td>
                        <td>
                          <span className={`health-dot ${a.health}`}/>
                        </td>
                        <td className="host">
                          <b>{a.host}</b>
                          <div style={{fontSize: 10, color: "var(--text-muted)", fontWeight: 400, marginTop: 2}}>{a.id} · {a.serial}</div>
                        </td>
                        <td>
                          <span className={`type-pill ${a.type}`}><span className="ti"/>{a.typeLabel}</span>
                        </td>
                        <td className="dim">{a.vendor} {a.model}</td>
                        <td className="dim">{a.rack === "—" ? a.room : `${a.rack} · ${a.uPos}`}</td>
                        <td><span className={`status-pill ${a.status}`}>{STATUSES[a.status]}</span></td>
                        <td>
                          <div className="utz-cell">
                            <div className="utz-bar"><div style={{width: `${Math.min(100, utz)}%`, background: utz > 80 ? "var(--danger)" : utz > 60 ? "var(--warn)" : "var(--ok)"}}/></div>
                            <div className="utz-val">{utz}%</div>
                          </div>
                        </td>
                        <td className="num">{fmtPower(a.powerW)}</td>
                        <td>
                          <span className={`warranty-pill ${warrantyClass(a.warrantyDays)}`}>{warrantyText(a.warrantyDays)}</span>
                        </td>
                      </tr>
                    );
                  })}
                  {filtered.length === 0 && (
                    <tr><td colSpan="10" style={{padding: 40, textAlign: "center", color: "var(--text-dim)"}}>None active ne correspond aux filtres.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {view === "cards" && (
            <div className="inv-cards">
              {filtered.map(a => (
                <div key={a.id}
                     className={`asset-card ${selected?.id === a.id ? "selected" : ""}`}
                     onClick={() => setSelected(a)}>
                  <div className="ac-head">
                    <div>
                      <div className="ac-host">{a.host}</div>
                      <div className="ac-model">{a.vendor} {a.model}</div>
                      <div className="ac-loc">{a.rack === "—" ? a.room : `${a.rack} · ${a.uPos} · ${a.room}`}</div>
                    </div>
                    <span className={`type-pill ${a.type}`}><span className="ti"/>{a.typeLabel}</span>
                  </div>
                  <div className="asset-fig" style={{height: 50}}>
                    <div className="face">
                      {Array.from({ length: Math.max(a.uSize, 1) }, (_, i) => <div key={i} className="row"/>)}
                    </div>
                  </div>
                  <div className="ac-foot">
                    <span className="health-cell">
                      <span className={`health-dot ${a.health}`}/>
                      <span style={{fontFamily: "var(--mono)", color: "var(--text-dim)"}}>{fmtPower(a.powerW)}</span>
                    </span>
                    <span className={`status-pill ${a.status}`}>{STATUSES[a.status]}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <AssetDetail a={selected}/>
      </div>
    </div>
  );
}

window.VueInventory = VueInventory;
