var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
import { ContextProvider } from "@lit/context";
import { mdiRefresh } from "@mdi/js";
import { LitElement, css, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { clientContext, tickContext } from "../client/client-context.js";
import "../components/ha-svg-icon";
import "./components/header";
import "./matter-cluster-view";
import "./matter-endpoint-view";
import "./matter-network-view";
import "./matter-node-view";
import "./matter-server-view";
import { categorizeDevices } from "./network/network-utils.js";
let MatterDashboardApp = class extends LitElement {
  constructor() {
    super(...arguments);
    this._route = {
      prefix: "",
      path: []
    };
    this._activeView = "nodes";
    this._initialSelectedNodeId = null;
    this._state = "connecting";
    this._tick = 0;
    /** Track whether nodes have been loaded at least once (to avoid redirecting before data arrives) */
    this._nodesLoaded = false;
    this.clientProvider = new ContextProvider(this, { context: clientContext });
    this.tickProvider = new ContextProvider(this, { context: tickContext, initialValue: 0 });
    this._reconnect = () => {
      this._state = "connecting";
      this._connect();
    };
  }
  firstUpdated(_changedProperties) {
    super.firstUpdated(_changedProperties);
    this._connect();
    this._updateRoute = () => {
      const hash = location.hash.substring(1);
      const pathParts = hash.split("/");
      this._initialSelectedNodeId = null;
      const { hasThreadDevices, hasWifiDevices } = this._getDeviceCounts();
      if (pathParts[0] === "thread") {
        if (this._nodesLoaded && !hasThreadDevices) {
          location.hash = "#nodes";
          return;
        }
        this._activeView = "thread";
        if (pathParts.length > 1 && pathParts[1]) {
          this._initialSelectedNodeId = pathParts[1];
        }
      } else if (pathParts[0] === "wifi") {
        if (this._nodesLoaded && !hasWifiDevices) {
          location.hash = "#nodes";
          return;
        }
        this._activeView = "wifi";
        if (pathParts.length > 1 && pathParts[1]) {
          this._initialSelectedNodeId = pathParts[1];
        }
      } else if (hash === "nodes" || hash === "" || pathParts[0] === "node") {
        this._activeView = "nodes";
      }
      this._route = {
        prefix: pathParts.length == 1 ? "" : pathParts[0],
        path: pathParts.length == 1 ? pathParts : pathParts.slice(1)
      };
    };
    window.addEventListener("hashchange", this._updateRoute);
    this._updateRoute();
  }
  _connect() {
    this.client.startListening().then(
      () => {
        this.clientProvider.setValue(this.client);
        this.tickProvider.setValue(++this._tick);
        this._state = "connected";
        this._setupEventListeners();
      },
      (_err) => {
        this._state = "error";
      }
    );
  }
  _setupEventListeners() {
    this.client.addEventListener("nodes_changed", () => {
      const wasFirstLoad = !this._nodesLoaded;
      this._nodesLoaded = true;
      if (wasFirstLoad && this._updateRoute) {
        this._updateRoute();
      }
      this.requestUpdate();
      this.tickProvider.setValue(++this._tick);
    });
    this.client.addEventListener("server_info_updated", () => {
      this.tickProvider.setValue(++this._tick);
    });
    this.client.addEventListener("connection_lost", () => {
      this._state = "disconnected";
    });
  }
  /**
   * Get device counts for Thread and WiFi networks.
   */
  _getDeviceCounts() {
    if (!this.client?.nodes) {
      return { hasThreadDevices: false, hasWifiDevices: false };
    }
    const categorized = categorizeDevices(this.client.nodes);
    return {
      hasThreadDevices: categorized.thread.length > 0,
      hasWifiDevices: categorized.wifi.length > 0 || categorized.ethernet.length > 0
    };
  }
  render() {
    if (this._state === "connecting") {
      return html`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message">Connecting...</p>
                </div>
            `;
    }
    if (this._state === "disconnected") {
      return html`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message error">Connection lost</p>
                    <p class="status-hint">
                        The connection to the Matter Server was lost. Please check if the server is running.
                    </p>
                    <button class="retry-button" @click=${this._reconnect}>
                        <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                        Reconnect
                    </button>
                </div>
            `;
    }
    if (this._state === "error") {
      return html`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message error">No connection</p>
                    <p class="status-hint">
                        Unable to connect to the Matter Server. Please check if the server is running.
                    </p>
                    <button class="retry-button" @click=${this._reconnect}>
                        <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                        Reconnect
                    </button>
                </div>
            `;
    }
    if (this._route.prefix === "node" && this._route.path.length == 3) {
      return html`
                <matter-cluster-view
                    .node=${this.client.nodes[this._route.path[0]]}
                    .endpoint=${parseInt(this._route.path[1], 10)}
                    .cluster=${parseInt(this._route.path[2], 10)}
                ></matter-cluster-view>
            `;
    }
    if (this._route.prefix === "node" && this._route.path.length == 2) {
      return html`
                <matter-endpoint-view
                    .node=${this.client.nodes[this._route.path[0]]}
                    .endpoint=${parseInt(this._route.path[1], 10)}
                ></matter-endpoint-view>
            `;
    }
    if (this._route.prefix === "node") {
      return html` <matter-node-view .node=${this.client.nodes[this._route.path[0]]}></matter-node-view> `;
    }
    const { hasThreadDevices, hasWifiDevices } = this._getDeviceCounts();
    if (this._route.prefix === "thread" || this._route.path[0] === "thread") {
      return html`<matter-network-view
                .nodes=${this.client.nodes}
                .activeView=${this._activeView}
                .initialSelectedNodeId=${this._initialSelectedNodeId}
                .hasThreadDevices=${hasThreadDevices}
                .hasWifiDevices=${hasWifiDevices}
                networkType="thread"
            ></matter-network-view>`;
    }
    if (this._route.prefix === "wifi" || this._route.path[0] === "wifi") {
      return html`<matter-network-view
                .nodes=${this.client.nodes}
                .activeView=${this._activeView}
                .initialSelectedNodeId=${this._initialSelectedNodeId}
                .hasThreadDevices=${hasThreadDevices}
                .hasWifiDevices=${hasWifiDevices}
                networkType="wifi"
            ></matter-network-view>`;
    }
    return html`<matter-server-view
            .nodes=${this.client.nodes}
            .route=${this._route}
            .activeView=${this._activeView}
            .hasThreadDevices=${hasThreadDevices}
            .hasWifiDevices=${hasWifiDevices}
        ></matter-server-view>`;
  }
};
MatterDashboardApp.styles = css`
        :host {
            display: block;
            min-height: 100vh;
            background-color: var(--md-sys-color-background);
        }

        .status-page {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 48px 24px;
            text-align: center;
        }

        .status-message {
            font-size: 1.5rem;
            color: var(--md-sys-color-on-background);
            margin: 0 0 16px 0;
        }

        .status-message.error {
            color: var(--danger-color);
        }

        .status-hint {
            font-size: 1rem;
            color: var(--md-sys-color-on-surface-variant);
            margin: 0;
            max-width: 400px;
        }

        .retry-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-top: 24px;
            padding: 12px 24px;
            font-size: 1rem;
            background-color: var(--md-sys-color-primary);
            color: var(--md-sys-color-on-primary);
            --icon-primary-color: var(--md-sys-color-on-primary);
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .retry-button:hover {
            opacity: 0.9;
        }

        .retry-button ha-svg-icon {
            width: 20px;
            height: 20px;
        }
    `;
__decorateClass([
  state()
], MatterDashboardApp.prototype, "_route", 2);
__decorateClass([
  state()
], MatterDashboardApp.prototype, "_activeView", 2);
__decorateClass([
  state()
], MatterDashboardApp.prototype, "_initialSelectedNodeId", 2);
__decorateClass([
  state()
], MatterDashboardApp.prototype, "_state", 2);
__decorateClass([
  state()
], MatterDashboardApp.prototype, "_tick", 2);
MatterDashboardApp = __decorateClass([
  customElement("matter-dashboard-app")
], MatterDashboardApp);
//# sourceMappingURL=matter-dashboard-app.js.map
