/* global React */
// ════════════════════════════════════════════════════════════════
// Sostratus app SHELL, faithful reproduction of the real ui-app
// shell: two-row top header (logo+ostratus / search / bell+avatar,
// then scope-icon + entity/page + centered nav tabs w/ violet
// active underline) and the centered content frame w/ breadcrumbs.
// Exported to window. Pairs with appmocks.jsx (page bodies).
// ════════════════════════════════════════════════════════════════
const { useId } = React;

function LogoMark({ size = 30, stroke = "#a78bfa", fill = "#6d28d9" }) {
  const uid = useId().replace(/:/g, "");
  return (
    <svg width={size} height={size * (768 / 731)} viewBox="0 0 731 768" aria-hidden="true" style={{ display: "block", flexShrink: 0 }}>
      <defs>
        <mask id={`gap-${uid}`}>
          <rect x="0" y="0" width="731" height="768" fill="white" />
          <path d="M 130 480 L 302 292 L 394 434 L 654 147" stroke="black" strokeWidth="55" strokeLinejoin="miter" strokeLinecap="butt" fill="none" />
        </mask>
      </defs>
      <g mask={`url(#gap-${uid})`}>
        <path d="M 527,100 C 510.3,88 458.2,54.3 431,41 C 403.8,27.7 392.2,23.5 364,20 C 335.8,16.5 293.8,14 262,20 C 230.2,26 199.2,39.5 173,56 C 146.8,72.5 120.8,100.7 105,119 C 89.2,137.3 84.8,151.2 78,166 C 71.2,180.8 66.5,187.7 64,208 C 61.5,228.3 57.7,260.5 63,288 C 68.3,315.5 85.5,352.5 96,373 C 106,392 120,410 140,404 C 168,395 200,350 215,318 C 225,298 215,275 208,258 C 201,241 200,226 206,212 C 214,196 230,178 252,163 C 274,148 296,146 318,148 C 346,150 378,164 406,186 C 434,208 462,200 484,184 C 504,170 518,145 524,126 C 530,112 532,104 527,100 Z" fill={fill} />
        <path d="M 576,447 C 570,428 558,405 545,392 C 525,374 505,388 475,420 C 452,446 442,468 440,488 C 438,508 440,528 436,548 C 430,568 418,586 400,600 C 380,614 356,620 330,620 C 304,620 274,612 248,598 C 218,582 182,558 150,538 C 125,522 108,516 96,518 C 82,520 72,532 60,550 C 44,572 30,590 24,600 C 18,610 16,614 22,608 C 43.5,627.8 125.5,686.7 158,708 C 190.5,729.3 196,728.7 217,736 C 238,743.3 255.3,750.3 284,752 C 312.7,753.7 356.5,754 389,746 C 421.5,738 452.3,723.5 479,704 C 505.7,684.5 531.8,655.7 549,629 C 566.2,602.3 576.2,567.5 582,544 C 587.8,520.5 585,504.2 584,488 C 583,471.8 580.8,462 576,447 Z" fill={fill} />
      </g>
      <path d="M 130 480 L 302 292 L 394 434 L 654 147" stroke={stroke} strokeWidth="43" strokeLinejoin="miter" strokeLinecap="butt" fill="none" />
    </svg>
  );
}

// marketing wordmark (full "Sostratus")
function Wordmark({ size = 30, sub }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <LogoMark size={size} />
      <div style={{ lineHeight: 1 }}>
        <div style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: size * 0.72, letterSpacing: "-0.01em", color: "#fff" }}>Sostratus</div>
        {sub && <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--tx-3)", marginTop: 3 }}>{sub}</div>}
      </div>
    </div>
  );
}

// ---- Phosphor-ish line icons (currentColor) ----
function Icon({ name, size = 18, weight = "regular" }) {
  const sw = weight === "duotone" ? 1.7 : 1.7;
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "house": return <svg {...p}><path d="M4 11l8-6 8 6v8a1 1 0 0 1-1 1h-4v-5h-6v5H5a1 1 0 0 1-1-1z" /></svg>;
    case "buildings": return <svg {...p}><rect x="4" y="3" width="9" height="17" rx="1" /><path d="M13 9h6a1 1 0 0 1 1 1v10H13M7 7h3M7 11h3M7 15h3M16 12h1M16 16h1" /></svg>;
    case "hard-drives": return <svg {...p}><rect x="3" y="4" width="18" height="7" rx="1.5" /><rect x="3" y="13" width="18" height="7" rx="1.5" /><path d="M7 7.5h.01M7 16.5h.01" /><circle cx="17" cy="7.5" r=".7" fill="currentColor" /><circle cx="17" cy="16.5" r=".7" fill="currentColor" /></svg>;
    case "graph": return <svg {...p}><circle cx="6" cy="6" r="2.4" /><circle cx="18" cy="8" r="2.4" /><circle cx="12" cy="18" r="2.4" /><path d="M7.8 7.6l2.8 8.6M16.2 9.6l-3.4 6.4M8 6.6l7.6 1" /></svg>;
    case "gauge": return <svg {...p}><path d="M4 18a8 8 0 1 1 16 0" /><path d="M12 14l4-3" /><circle cx="12" cy="18" r="1.1" fill="currentColor" /></svg>;
    case "wrench": return <svg {...p}><path d="M15 4a5 5 0 0 0-6 6L4 15v5h5l5-5a5 5 0 0 0 6-6l-3 3-3-1-1-3z" /></svg>;
    case "dots-three": return <svg {...p}><circle cx="5" cy="12" r="1.3" fill="currentColor" stroke="none" /><circle cx="12" cy="12" r="1.3" fill="currentColor" stroke="none" /><circle cx="19" cy="12" r="1.3" fill="currentColor" stroke="none" /></svg>;
    case "search": return <svg {...p}><circle cx="11" cy="11" r="6" /><path d="M20 20l-4-4" /></svg>;
    case "bell": return <svg {...p}><path d="M6 10a6 6 0 0 1 12 0c0 5 2 6 2 6H4s2-1 2-6" /><path d="M10 20a2 2 0 0 0 4 0" /></svg>;
    case "caret-down": return <svg {...p}><path d="M6 9l6 6 6-6" /></svg>;
    case "plus": return <svg {...p}><path d="M12 5v14M5 12h14" /></svg>;
    case "router": return <svg {...p}><rect x="3" y="13" width="18" height="7" rx="1.5" /><path d="M7 13V8M12 13V5M17 13V9" /><circle cx="7" cy="16.5" r=".7" fill="currentColor" /><circle cx="11" cy="16.5" r=".7" fill="currentColor" /></svg>;
    case "desktop-tower": return <svg {...p}><rect x="4" y="3" width="8" height="18" rx="1.5" /><rect x="15" y="3" width="5" height="11" rx="1" /><path d="M7 6h2M7 9h2M16.5 17v3M15 20h3" /></svg>;
    case "download": return <svg {...p}><path d="M12 4v10m0 0l-4-4m4 4l4-4M5 19h14" /></svg>;
    case "refresh": return <svg {...p}><path d="M4 12a8 8 0 0 1 13.7-5.6L20 8M20 4v4h-4M20 12a8 8 0 0 1-13.7 5.6L4 16M4 20v-4h4" /></svg>;
    case "globe": return <svg {...p}><circle cx="12" cy="12" r="8" /><path d="M4 12h16M12 4c2.5 2.5 2.5 13 0 16M12 4c-2.5 2.5-2.5 13 0 16" /></svg>;
    case "rows": return <svg {...p}><rect x="3" y="5" width="18" height="4.5" rx="1" /><rect x="3" y="14.5" width="18" height="4.5" rx="1" /><path d="M6.5 7.2h.01M6.5 16.7h.01" /></svg>;
    case "package": return <svg {...p}><path d="M3 7l9-4 9 4v10l-9 4-9-4z" /><path d="M3 7l9 4 9-4M12 11v10" /></svg>;
    case "bomb": return <svg {...p}><circle cx="11" cy="14" r="7" /><path d="M16 9l2-2M18 7l1 1M18 5v2.5M20.5 7H18" /></svg>;
    case "shield": return <svg {...p}><path d="M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z" /><path d="M9 12l2 2 4-4" /></svg>;
    case "robot": return <svg {...p}><rect x="4" y="8" width="16" height="11" rx="2.5" /><path d="M12 4v4M8 13v1.5M16 13v1.5M3 12v3M21 12v3" /><circle cx="9" cy="13" r=".6" fill="currentColor" /><circle cx="15" cy="13" r=".6" fill="currentColor" /></svg>;
    case "radar": return <svg {...p}><circle cx="12" cy="12" r="8" /><circle cx="12" cy="12" r="4" /><path d="M12 12l6-3" /><circle cx="12" cy="12" r="1.1" fill="currentColor" /></svg>;
    case "flask": return <svg {...p}><path d="M9.5 3h5M10.5 3v6L5.6 17.5A2 2 0 0 0 7.3 20.5h9.4a2 2 0 0 0 1.7-3L13.5 9V3" /><path d="M8 14.5h8" /><circle cx="11" cy="16.5" r=".6" fill="currentColor" /><circle cx="13.5" cy="18" r=".5" fill="currentColor" /></svg>;
    default: return <svg {...p}><circle cx="12" cy="12" r="7" /></svg>;
  }
}

function DeviceIcon({ t, size = 16 }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (t) {
    case "router": return <svg {...p}><rect x="3" y="13" width="18" height="7" rx="1.5" /><path d="M7 13V8M12 13V5M17 13V9" /></svg>;
    case "switch": return <svg {...p}><rect x="3" y="9" width="18" height="6" rx="1.5" /><path d="M6 15v2M9.5 15v2M13 15v2M16.5 15v2" /></svg>;
    case "firewall": return <svg {...p}><path d="M12 3l7 3v5c0 4-3 7-7 9-4-2-7-5-7-9V6z" /></svg>;
    case "server": return <svg {...p}><rect x="4" y="4" width="16" height="7" rx="1.5" /><rect x="4" y="13" width="16" height="7" rx="1.5" /></svg>;
    case "vm": return <svg {...p}><rect x="3" y="4" width="18" height="13" rx="2" /><path d="M8 21h8M12 17v4" /></svg>;
    case "container": return <svg {...p}><path d="M12 3l8 4v8l-8 4-8-4V7z" /><path d="M4 7l8 4 8-4M12 11v8" /></svg>;
    default: return <svg {...p}><circle cx="12" cy="12" r="7" /></svg>;
  }
}

// ---- small primitives matching the app ----
function Pill({ tone = "violet", children }) {
  const map = { ok: ["rgba(52,211,153,0.12)", "#34d399"], warn: ["rgba(240,160,96,0.12)", "#f0a060"], err: ["rgba(240,96,128,0.12)", "#f06080"], info: ["rgba(96,188,224,0.12)", "#60bce0"], violet: ["rgba(145,128,212,0.15)", "#bdb0f6"] };
  const [bg, c] = map[tone] || map.violet;
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "2px 9px", borderRadius: 6, fontSize: 11, fontFamily: "var(--mono)", background: bg, color: c, letterSpacing: ".02em" }}>{children}</span>;
}

function StatusDot({ tone = "ok", size = 7 }) {
  const c = { ok: "#34d399", warn: "#f0a060", err: "#f06080", info: "#60bce0", idle: "#56555E" }[tone] || "#34d399";
  return <span style={{ width: size, height: size, borderRadius: 99, background: c, display: "inline-block", flexShrink: 0, boxShadow: `0 0 7px ${c}66` }} />;
}

// donut chart (SVG), values:[{label,value,color}]
function Donut({ data, size = 96, thickness = 13 }) {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = (size - thickness) / 2;
  const C = 2 * Math.PI * r;
  let off = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(242,242,244,0.06)" strokeWidth={thickness} />
      {data.map((d, i) => {
        const len = (d.value / total) * C;
        const el = <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={d.color} strokeWidth={thickness} strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-off} transform={`rotate(-90 ${size / 2} ${size / 2})`} strokeLinecap="butt" />;
        off += len;
        return el;
      })}
      <text x="50%" y="50%" textAnchor="middle" dominantBaseline="central" fill="#ECEAF4" fontFamily="var(--mono)" fontSize={size * 0.2} fontWeight="600">{total}</text>
    </svg>
  );
}

// ════════════════════════════════════════════════════════════════
// APP SHELL, header (2 rows) + content frame
// ════════════════════════════════════════════════════════════════
const TENANT_TABS = [
  { id: "home", label: "Home", icon: "house" },
  { id: "sites", label: "Sites", icon: "buildings", group: true },
  { id: "agents", label: "Agents", icon: "hard-drives", group: true },
  { id: "network", label: "Networks", icon: "graph", group: true },
  { id: "monitoring", label: "Monitoring", icon: "gauge", group: true },
  { id: "operations", label: "Operations", icon: "wrench", group: true },
  { id: "more", label: "More", icon: "dots-three", group: true },
];

function ShellHeader({ scopeIcon, entityName, pageName, tabs, activeTab, avatar = "JD" }) {
  return (
    <div style={{ background: "#08080A", borderBottom: "1px solid rgba(242,242,244,0.06)" }}>
      {/* Row 1 */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 26px 7px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 2 }}>
          <LogoMark size={30} />
          <span style={{ fontFamily: "var(--sans)", fontSize: 25, fontWeight: 600, letterSpacing: "0.01em", color: "#ECEAF4", marginLeft: -3 }}>ostratus</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, width: 340, maxWidth: "38%", padding: "7px 12px", borderRadius: 8, border: "1px solid rgba(242,242,244,0.10)", background: "rgba(242,242,244,0.03)", color: "var(--tx-3)" }}>
          <Icon name="search" size={16} />
          <span style={{ fontSize: 13, flex: 1 }}>Search devices, events…</span>
          <span className="mono" style={{ fontSize: 10.5, padding: "2px 6px", borderRadius: 4, border: "1px solid rgba(242,242,244,0.10)", color: "var(--tx-4)" }}>⌘K</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ position: "relative", color: "var(--tx-2)", display: "flex" }}>
            <Icon name="bell" size={20} />
            <span style={{ position: "absolute", top: -2, right: -2, width: 6, height: 6, borderRadius: 99, background: "#f06080" }} />
          </span>
          <span style={{ width: 32, height: 32, borderRadius: 99, background: "rgba(145,128,212,0.18)", border: "1px solid rgba(145,128,212,0.4)", color: "#bdb0f6", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12.5, fontWeight: 600, fontFamily: "var(--mono)" }}>{avatar}</span>
        </div>
      </div>
      {/* Row 2 */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "flex-end", padding: "0 26px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, paddingBottom: 9 }}>
          <span style={{ color: "#9180d4", display: "flex" }}><Icon name={scopeIcon} size={40} /></span>
          <div style={{ lineHeight: 1.25 }}>
            <div style={{ fontSize: 14, color: "var(--tx-2)" }}>{entityName}</div>
            <div style={{ fontSize: 19, fontWeight: 600, color: "#ECEAF4" }}>{pageName}</div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "center" }}>
          {tabs.map(tab => {
            const on = tab.id === activeTab;
            return (
              <div key={tab.id} style={{ position: "relative", display: "flex", alignItems: "center", gap: 6, height: 44, padding: "0 13px", fontSize: 14, fontWeight: 600, color: on ? "#ECEAF4" : "#706F7A", cursor: "pointer", whiteSpace: "nowrap" }}>
                <Icon name={tab.icon} size={18} />
                {tab.label}
                {tab.group && <span style={{ opacity: 0.6, display: "flex" }}><Icon name="caret-down" size={14} /></span>}
                {on && <span style={{ position: "absolute", left: 6, right: 6, bottom: 0, height: 2, borderRadius: 1, background: "#9180d4" }} />}
              </div>
            );
          })}
        </div>
        <div />
      </div>
    </div>
  );
}

function AppShell({ scopeIcon, entityName, pageName, tabs, activeTab, breadcrumb, avatar, children }) {
  return (
    <div style={{ borderRadius: 14, overflow: "hidden", border: "1px solid var(--hair)", background: "var(--bg)", boxShadow: "0 40px 90px rgba(0,0,0,0.55)" }}>
      <ShellHeader scopeIcon={scopeIcon} entityName={entityName} pageName={pageName} tabs={tabs} activeTab={activeTab} avatar={avatar} />
      <div style={{ padding: "22px 30px 26px", background: "var(--bg)" }}>
        {breadcrumb && (
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 20 }}>
            {breadcrumb.map((c, i) => (
              <span key={i} style={{ display: "flex", alignItems: "center", gap: 7 }}>
                {i > 0 && <span style={{ color: "var(--tx-4)", fontSize: 12 }}>›</span>}
                <span style={{ fontSize: 12.5, fontWeight: i === breadcrumb.length - 1 ? 500 : 400, color: i === breadcrumb.length - 1 ? "var(--tx)" : "#9180d4" }}>{c}</span>
              </span>
            ))}
          </div>
        )}
        {children}
      </div>
    </div>
  );
}

// card (ContentSection), violet 18px title + optional action
function Card({ title, action, pad = false, children }) {
  return (
    <div style={{ background: "var(--card)", border: "1px solid #1c1c22", borderRadius: 8, overflow: "hidden", display: "flex", flexDirection: "column" }}>
      {title && (
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 50, padding: "0 18px", flexShrink: 0 }}>
          <span style={{ fontSize: 17, color: "#9180d4", whiteSpace: "nowrap" }}>{title}</span>
          {action}
        </div>
      )}
      <div style={{ padding: pad ? "0 0 6px" : 0 }}>{children}</div>
    </div>
  );
}

// ---- KPI strip (DashboardTemplate-style stat cards) ----
function KpiStrip({ items }) {
  return (
    <div style={{ display: "flex", gap: 14, marginBottom: 16 }}>
      {items.map(k => (
        <div key={k.l} style={{ flex: 1, padding: "13px 16px", border: "1px solid var(--divider)", borderRadius: 10 }}>
          <div style={{ fontSize: 12, color: "var(--tx-2)" }}>{k.l}</div>
          <div className="mono" style={{ fontSize: 25, fontWeight: 600, color: k.tone || "#ECEAF4", marginTop: 3, whiteSpace: "nowrap" }}>{k.v}</div>
          {k.sub && <div className="mono" style={{ fontSize: 10.5, color: "var(--tx-3)", marginTop: 2 }}>{k.sub}</div>}
        </div>
      ))}
    </div>
  );
}

// ---- generic table, cols:[{k,label,w,mono,render}], rows ----
function Table({ cols, rows, grid }) {
  const gt = grid || cols.map(c => c.w || "1fr").join(" ");
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: gt, padding: "9px 18px", borderTop: "1px solid var(--divider)", background: "rgba(242,242,244,0.02)" }}>
        {cols.map(c => <div key={c.k} className="mono" style={{ fontSize: 9.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--tx-3)", textAlign: c.right ? "right" : "left" }}>{c.label}</div>)}
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: gt, alignItems: "center", padding: "10px 18px", borderTop: "1px solid var(--divider-2)" }}>
          {cols.map(c => (
            <div key={c.k} style={{ fontSize: 12.5, color: c.mono ? "var(--tx)" : "var(--tx-2)", fontFamily: c.mono ? "var(--mono)" : "var(--sans)", textAlign: c.right ? "right" : "left", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              {c.render ? c.render(r[c.k], r) : r[c.k]}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

// ---- area sparkline ----
function AreaSpark({ values, color = "#a78bfa", w = 320, h = 70 }) {
  const max = Math.max(...values), min = Math.min(...values);
  const rng = max - min || 1;
  const pts = values.map((v, i) => [(i / (values.length - 1)) * w, h - ((v - min) / rng) * (h - 10) - 5]);
  const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ");
  const area = `${line} L${w} ${h} L0 ${h} Z`;
  const uid = "as" + Math.random().toString(36).slice(2, 7);
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display: "block" }}>
      <defs><linearGradient id={uid} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity="0.32" /><stop offset="100%" stopColor={color} stopOpacity="0" /></linearGradient></defs>
      <path d={area} fill={`url(#${uid})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ---- mini vertical bars ----
function MiniBars({ values, color = "#a78bfa", h = 70 }) {
  const max = Math.max(...values) || 1;
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 3, height: h }}>
      {values.map((v, i) => <div key={i} style={{ flex: 1, height: `${(v / max) * 100}%`, background: color, opacity: 0.35 + 0.65 * (v / max), borderRadius: "2px 2px 0 0", minHeight: 2 }} />)}
    </div>
  );
}

// ---- horizontal utilization bar ----
function UtilBar({ value, color }) {
  const c = color || (value > 90 ? "#f06080" : value > 75 ? "#f0a060" : "#34d399");
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
      <div style={{ flex: 1, height: 5, background: "rgba(242,242,244,0.07)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{ width: `${value}%`, height: "100%", background: c, borderRadius: 3 }} />
      </div>
      <span className="mono" style={{ fontSize: 11, color: "var(--tx-3)", minWidth: 32, textAlign: "right" }}>{value}%</span>
    </div>
  );
}

Object.assign(window, { LogoMark, Wordmark, Icon, DeviceIcon, Pill, StatusDot, Donut, AppShell, Card, KpiStrip, Table, AreaSpark, MiniBars, UtilBar, TENANT_TABS });
