<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>APEX Sovereign | Realized Intelligence Dashboard</title>
    <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
    <script src="https://unpkg.com/recharts@2.1.9/umd/Recharts.js"></script>
    <link
      href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@300;500;800&display=swap"
      rel="stylesheet"
    />
    <script
      src="https://arifos.arif-fazil.com/scripts/sovereign-unify.js"
      async
    ></script>
    <style>
      :root {
        --bg: #050505;
        --card: #0f0f0f;
        --accent: #00ffcc;
        --accent-dim: rgba(0, 255, 204, 0.1);
        --text: #e0e0e0;
        --dim: #666;
        --border: #222;
        --font-mono: "JetBrains Mono", monospace;
        --font-sans: "Inter", sans-serif;
        --danger: #ff4444;
        --success: #00ff88;
      }

      body {
        background: var(--bg);
        color: var(--text);
        font-family: var(--font-sans);
        margin: 0;
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-height: 100vh;
      }

      .container {
        max-width: 1200px;
        width: 100%;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
      }

      header {
        width: 100%;
        max-width: 1200px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        border-bottom: 1px solid var(--border);
        padding-bottom: 15px;
      }

      .motto {
        font-family: var(--font-mono);
        font-size: 0.8rem;
        color: var(--accent);
        text-transform: uppercase;
        letter-spacing: 2px;
      }

      .title h1 {
        margin: 0;
        font-size: 1.5rem;
        font-weight: 800;
        letter-spacing: -1px;
      }

      .card {
        background: var(--card);
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 24px;
        position: relative;
        overflow: hidden;
      }

      .card h3 {
        margin-top: 0;
        font-size: 0.9rem;
        text-transform: uppercase;
        color: var(--dim);
        letter-spacing: 1px;
        margin-bottom: 20px;
      }

      .full-width {
        grid-column: 1 / -1;
      }

      .metric-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 15px;
      }

      .metric-box {
        background: #151515;
        padding: 15px;
        border-radius: 8px;
        border-left: 3px solid var(--accent);
      }

      .metric-label {
        font-size: 0.7rem;
        color: var(--dim);
        margin-bottom: 5px;
      }

      .metric-value {
        font-family: var(--font-mono);
        font-size: 1.2rem;
        font-weight: 700;
      }

      .main-score {
        font-size: 4rem;
        font-weight: 800;
        color: var(--accent);
        text-shadow: 0 0 20px var(--accent-glow);
        margin: 10px 0;
      }

      .controls {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
      }

      button {
        background: var(--card);
        border: 1px solid var(--border);
        color: var(--text);
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        font-family: var(--font-mono);
        font-size: 0.8rem;
        transition: all 0.2s;
      }

      button.active {
        border-color: var(--accent);
        background: var(--accent-dim);
        color: var(--accent);
      }

      button:hover {
        border-color: var(--accent);
      }

      .badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
      }

      .badge-success {
        background: var(--success);
        color: #000;
      }
      .badge-danger {
        background: var(--danger);
        color: #fff;
      }

      .log-line {
        font-family: var(--font-mono);
        font-size: 0.8rem;
        padding: 4px 0;
        border-bottom: 1px solid #111;
        display: flex;
        justify-content: space-between;
      }

      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 8px;
      }

      .pulse {
        animation: pulse-animation 2s infinite;
      }

      @keyframes pulse-animation {
        0% {
          box-shadow: 0 0 0 0px rgba(0, 255, 204, 0.4);
        }
        100% {
          box-shadow: 0 0 0 10px rgba(0, 255, 204, 0);
        }
      }
    </style>
  </head>
  <body>
    <div id="root"></div>

    <script type="text/babel">
      const { useState, useEffect, useMemo } = React;
      const {
        Radar,
        RadarChart,
        PolarGrid,
        PolarAngleAxis,
        PolarRadiusAxis,
        ResponsiveContainer,
        BarChart,
        Bar,
        XAxis,
        YAxis,
        Tooltip,
        Cell,
      } = Recharts;

      // MCP Apps SDK Integration
      let mcpApp = null;
      try {
        const dynamicImport = new Function("url", "return import(url)");
        dynamicImport(
          "https://unpkg.com/@modelcontextprotocol/ext-apps@0.4.0/app-with-deps",
        )
          .then((module) => {
            const { App } = module;
            mcpApp = new App({ name: "APEX Sovereign", version: "1.0.0" });
            mcpApp
              .connect()
              .then(() => console.log("MCP Host Connected"))
              .catch((e) => console.warn("MCP Connect Error", e));
          })
          .catch((e) => console.warn("Dynamic import failed", e));
      } catch (e) {
        console.warn("MCP SDK Load failed, running in standalone mode", e);
      }

      const DEMO_DATA = {
        machine_vitals: { cpu_percent: 12, memory_percent: 24 },
        apex_output: {
          capacity_layer: {
            A: 0.95,
            P: 0.92,
            X: 0.85,
            capacity_product: 0.7429,
          },
          effort_layer: {
            E: 0.88,
            effort_amplifier: 0.7744,
            reasoning_steps: 12,
            tool_calls: 3,
          },
          entropy_layer: { H_before: 2.4, H_after: 1.8, delta_S: -0.35 },
          efficiency_layer: { C: 120, entropy_removed: 0.6, eta: 0.005 },
          governed_intelligence: { G_star: 0.5753, G_dagger: 0.002864 },
          governance_layer: {
            amanah_score: 0.75,
            truth_floor: "pass",
            authority_status: "pass",
            sovereignty_status: "pass",
            tri_witness_status: "0.95/0.88/0.76",
          },
          diagnostics: {
            log_decomposition: {
              logA: -0.051,
              logP: -0.083,
              logX: -0.162,
              "2logE": -0.255,
              logDeltaS: -0.51,
              logC: 2.0,
            },
            primary_constraint: "none",
            equation:
              "G\u2020 = (A \u00B7 P \u00B7 X \u00B7 E\u00B2) \u00B7 (1 - h)",
            runtime_story: "Status: ACTIVE. Hysteresis: 0.02",
          },
        },
      };

      function Dashboard() {
        const [mode, setMode] = useState("live");
        const [endpoint, setEndpoint] = useState(
          "https://arifosmcp.arif-fazil.com/api/governance-status",
        );
        const [data, setData] = useState(DEMO_DATA);
        const [isPolling, setIsPolling] = useState(true);

        useEffect(() => {
          if (mcpApp) {
            mcpApp.ontoolresult = ({ content }) => {
              const textContent = content?.find((c) => c.type === "text");
              if (textContent) {
                try {
                  const parsed = JSON.parse(textContent.text);
                  if (parsed.apex_output) {
                    setData(parsed);
                  }
                } catch (e) {}
              }
            };
          }
        }, []);

        useEffect(() => {
          let interval;
          if (mode === "live" && isPolling) {
            fetchData();
            interval = setInterval(fetchData, 3000);
          }
          return () => clearInterval(interval);
        }, [mode, isPolling]);

        const fetchData = async () => {
          try {
            const res = await fetch(endpoint);
            const json = await res.json();

            if (json.telemetry || json.floors) {
              const normalized = {
                machine_vitals: json.machine_vitals || {
                  cpu_percent: 0,
                  memory_percent: 0,
                },
                apex_output: {
                  capacity_layer: {
                    A: json.floors?.F1 || 0.95,
                    P: json.telemetry?.peace2 || 1.0,
                    X: json.telemetry?.confidence || 0.85,
                    capacity_product:
                      (json.floors?.F1 || 0.95) *
                      (json.telemetry?.peace2 || 1.0) *
                      (json.telemetry?.confidence || 0.85),
                  },
                  effort_layer: {
                    E: json.telemetry?.psi_le || 1.0,
                    effort_amplifier: Math.pow(
                      json.telemetry?.psi_le || 1.0,
                      2,
                    ),
                    reasoning_steps: json.metabolic_stage || 12,
                    tool_calls: 3,
                  },
                  entropy_layer: {
                    H_before: 2.4,
                    H_after: 1.8,
                    delta_S: json.telemetry?.dS || 0.0,
                  },
                  efficiency_layer: {
                    C: 120,
                    entropy_removed: Math.abs(json.telemetry?.dS || 0.0),
                    eta: (json.telemetry?.joules || 0.001) / 0.1,
                  },
                  governed_intelligence: {
                    G_star: json.telemetry?.confidence || 0.8,
                    G_dagger:
                      (json.telemetry?.confidence || 0.8) *
                      (1 - (json.telemetry?.hysteresis || 0.0)),
                  },
                  governance_layer: {
                    amanah_score: json.floors?.F1 || 0.75,
                    truth_floor:
                      (json.floors?.F2 || 0) >= 0.8 ? "pass" : "fail",
                    authority_status:
                      (json.floors?.F11 || 0) >= 0.8 ? "pass" : "fail",
                    sovereignty_status:
                      (json.floors?.F13 || 0) >= 0.8 ? "pass" : "fail",
                    tri_witness_status: json.witness
                      ? `${json.witness.human}/${json.witness.ai}/${json.witness.earth}`
                      : "Cannot Compute",
                  },
                  diagnostics: {
                    log_decomposition: {
                      logA: Math.log10(json.floors?.F1 || 0.95),
                      logP: Math.log10(json.telemetry?.peace2 || 1.0),
                      logX: Math.log10(json.telemetry?.confidence || 0.85),
                      "2logE": 2 * Math.log10(json.telemetry?.psi_le || 1.0),
                      logDeltaS: -Math.abs(json.telemetry?.dS || 0.01),
                      logC: 2.0,
                    },
                    primary_constraint: "none",
                    equation:
                      "G\u2020 = (A \u00B7 P \u00B7 X \u00B7 E\u00B2) \u00B7 (1 - h)",
                    runtime_story: `Status: ${json.telemetry?.verdict || "ACTIVE"}. Hysteresis: ${json.telemetry?.hysteresis || 0.0}`,
                  },
                },
              };
              setData(normalized);
            }
          } catch (e) {
            console.error("Fetch failed", e);
          }
        };

        const apex = data.apex_output;
        const machine = data.machine_vitals || {
          cpu_percent: 0,
          memory_percent: 0,
        };

        return (
          <div style={{ width: "100%" }}>
            <header>
              <div className="title">
                <div className="motto">Ditempa Bukan Diberi</div>
                <h1>APEX Sovereign Dashboard</h1>
              </div>
              <div className="controls">
                <button
                  className={mode === "live" ? "active" : ""}
                  onClick={() => setMode("live")}
                >
                  Live Mind
                </button>
                <button 
                  onClick={() => window.open('https://arifos.arif-fazil.com', '_blank')}
                  title="Theory & Documentation (arifOS Mind)"
                >
                  Mind Library ↗
                </button>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "8px",
                    fontSize: "0.7rem",
                    color: "var(--dim)",
                  }}
                >
                  <div
                    className={`status-dot ${isPolling ? "pulse" : ""}`}
                    style={{ background: "var(--accent)" }}
                  ></div>
                  {isPolling ? "SYNCED" : "OFFLINE"}
                </div>
              </div>
            </header>

            <div className="container">
              <div className="card">
                <h3>The Mind (G\u2020: Realized Intelligence)</h3>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    height: "300px",
                    flexDirection: "column",
                  }}
                >
                  <div className="main-score">
                    {apex.governed_intelligence.G_dagger.toFixed(6)}
                  </div>
                  <div
                    style={{
                      color: "var(--dim)",
                      fontSize: "0.8rem",
                      textAlign: "center",
                      maxWidth: "80%",
                    }}
                  >
                    Governed Intelligence ($G\u2020$) is the final
                    'truth-weight' of a thought after filtering for safety and
                    entropy.
                  </div>
                  <div style={{ marginTop: "20px" }}>
                    <span
                      className={`badge ${apex.governed_intelligence.G_dagger >= 0.001 ? "badge-success" : "badge-danger"}`}
                    >
                      {apex.governed_intelligence.G_dagger >= 0.001
                        ? "SOVEREIGN SEAL"
                        : "VOID / PROVISIONAL"}
                    </span>
                  </div>
                </div>
              </div>

              <div className="card">
                <h3>The Machine (VPS Vitals)</h3>
                <div
                  style={{
                    height: "300px",
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "center",
                    gap: "20px",
                  }}
                >
                  <div className="metric-box">
                    <div className="metric-label">CPU LOAD</div>
                    <div className="metric-value">{machine.cpu_percent}%</div>
                    <div
                      style={{
                        width: "100%",
                        height: "4px",
                        background: "#222",
                        marginTop: "8px",
                        borderRadius: "2px",
                      }}
                    >
                      <div
                        style={{
                          width: `${machine.cpu_percent}%`,
                          height: "100%",
                          background: "var(--accent)",
                          borderRadius: "2px",
                        }}
                      ></div>
                    </div>
                  </div>
                  <div className="metric-box">
                    <div className="metric-label">RAM USAGE</div>
                    <div className="metric-value">
                      {machine.memory_percent}%
                    </div>
                    <div
                      style={{
                        width: "100%",
                        height: "4px",
                        background: "#222",
                        marginTop: "8px",
                        borderRadius: "2px",
                      }}
                    >
                      <div
                        style={{
                          width: `${machine.memory_percent}%`,
                          height: "100%",
                          background: "#ffcc00",
                          borderRadius: "2px",
                        }}
                      ></div>
                    </div>
                  </div>
                  <div style={{ fontSize: "0.7rem", color: "var(--dim)" }}>
                    Machine health represents the 'Bio-Mass'. If CPU/RAM is
                    critical, the Mind's latency ($C$) increases, reducing
                    $G\u2020$.
                  </div>
                </div>
              </div>

              <div className="card full-width">
                <h3>Synthesis Metabolizer Flow</h3>
                <div className="metric-grid">
                  <div className="metric-box">
                    <div className="metric-label">Akal (A)</div>
                    <div className="metric-value">
                      {apex.capacity_layer.A.toFixed(4)}
                    </div>
                    <div className="metric-label">Logical Accuracy</div>
                  </div>
                  <div className="metric-box">
                    <div className="metric-label">Clarity (\u0394S)</div>
                    <div className="metric-value">
                      {apex.entropy_layer.delta_S.toFixed(4)}
                    </div>
                    <div className="metric-label">Entropy Reduction</div>
                  </div>
                  <div className="metric-box">
                    <div className="metric-label">Energy (E)</div>
                    <div className="metric-value">
                      {apex.effort_layer.E.toFixed(4)}
                    </div>
                    <div className="metric-label">Metabolic Fuel</div>
                  </div>
                  <div className="metric-box">
                    <div className="metric-label">Hysteresis (h)</div>
                    <div className="metric-value">
                      {(
                        1 -
                        apex.governed_intelligence.G_dagger /
                          apex.governed_intelligence.G_star
                      ).toFixed(4)}
                    </div>
                    <div className="metric-label">System Scars</div>
                  </div>
                </div>
              </div>

              <div className="card">
                <h3>Sovereign Guidance</h3>
                <div style={{ fontSize: "0.85rem", lineHeight: "1.4" }}>
                  <p>
                    <strong>\u0394S (Clarity):</strong> Measures if the AI is
                    simplifying information. $ \u0394S \le 0 $ is mandatory.
                    Positive values mean the AI is generating 'noise'.
                  </p>
                  <p>
                    <strong>h (Hysteresis):</strong> The 'Scars'. Accumulated
                    from past lies or failed floors. High $h$ makes it harder
                    for the AI to reach a SEAL verdict.
                  </p>
                  <p>
                    <strong>C (Complexity):</strong> The cognitive cost of the
                    task. High machine load increases $C$, making 'Cheap Truth'
                    impossible.
                  </p>
                </div>
              </div>

              <div className="card">
                <h3>Governance Integrity</h3>
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "10px",
                  }}
                >
                  <div className="log-line">
                    <span>F1 Amanah (Integrity)</span>
                    <span className="badge badge-success">PASS</span>
                  </div>
                  <div className="log-line">
                    <span>F2 Truth (Physical Bond)</span>
                    <span
                      className={`badge ${apex.governance_layer.truth_floor === "pass" ? "badge-success" : "badge-danger"}`}
                    >
                      {apex.governance_layer.truth_floor.toUpperCase()}
                    </span>
                  </div>
                  <div className="log-line">
                    <span>F7 Humility (Gödel Band)</span>
                    <span className="badge badge-success">IN-BAND</span>
                  </div>
                  <div className="log-line">
                    <span>Witness Consensus</span>
                    <span
                      style={{
                        fontFamily: "var(--font-mono)",
                        color: "var(--accent)",
                      }}
                    >
                      {apex.governance_layer.tri_witness_status}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <footer
              style={{
                marginTop: "40px",
                color: "#333",
                fontSize: "0.7rem",
                textAlign: "center",
                width: "100%",
              }}
            >
              ARIFOS L0 KERNEL | UNIFIED MACHINE-MIND INTERFACE | VERSION
              2026.03.12-FORGED
            </footer>
          </div>
        );
      }

      const root = ReactDOM.createRoot(document.getElementById("root"));
      root.render(<Dashboard />);
    </script>
  </body>
</html>
