/**
 * dashboard/Dashboard.jsx — public face of the dashboard module.
 *
 * Renders the DOM structure the Three.js modules expect (#pool-stats,
 * #tx-log, app cards, SVG leader layer), then mounts the WebGPU scene
 * via init.js into the canvas-host div. All Three.js code lives in
 * init.js + ./modules/* — this file only owns the React lifecycle.
 *
 * No-bundler form:
 * - React is a window global (UMD via unpkg).
 * - dashboard/styles.css is loaded as a <link> in index.html, NOT
 *   imported here.
 * - dashboard/init.js is loaded as a <script type="module"> earlier
 *   in index.html and exposes initDashboard via window.initDashboard.
 * - This file is loaded as <script type="text/babel">.
 */
const { useEffect, useRef, useState } = React;

function Dashboard() {
  const containerRef = useRef(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    // ES modules cache forever within a page load. The dashboard modules
    // capture DOM refs at top-level (e.g. document.getElementById('tx-log__list')).
    // If this component remounts after an in-SPA navigation, those cached refs
    // point to torn-down nodes and the panels stay empty. Force a fresh page
    // load on remount so module evaluation runs again with the current DOM.
    if (window.__strk20DashboardLoaded) {
      window.location.reload()
      return
    }
    window.__strk20DashboardLoaded = true

    let cleanupFn = null
    let cancelled = false
    // window.initDashboard is set by dashboard/init.js (loaded
    // earlier as a <script type="module"> in index.html).
    Promise.resolve(window.initDashboard).then((initDashboard) => {
      if (cancelled || !containerRef.current || !initDashboard) return
      initDashboard(containerRef.current).then((cleanup) => {
        if (cancelled) { cleanup?.(); return }
        cleanupFn = cleanup
        // Two rAFs so the first paint of the canvas + panels is committed
        // before we trigger the opacity transition — avoids a frame where
        // the fade-in starts on a still-empty scene.
        requestAnimationFrame(() => {
          requestAnimationFrame(() => setReady(true))
        })
      }).catch((err) => {
        console.error('Dashboard init failed:', err)
        setReady(true)
      })
    })
    return () => {
      cancelled = true
      cleanupFn?.()
    }
  }, [])

  return (
    <div className={`dashboard-root ${ready ? 'is-ready' : ''}`}>
      <div ref={containerRef} className="dashboard-canvas-host" />

      <aside id="pool-stats" aria-label="STRK20 privacy pool state">
        <header id="pool-stats__head">
          <h3>STRK20 // POOL STATE</h3>
          <span className="live">LIVE</span>
        </header>
        <div className="frame">
          <div className="frame__label">CURRENT TVL</div>
          <div className="frame__value" id="m-tvl">$11,748</div>
          <div className="frame__hint">USD · shielded across all tokens</div>
        </div>

        <div className="metrics">
          <div className="metric">
            <span className="metric__label">all-time revenue</span>
            <span className="metric__value" id="m-revenue">—</span>
          </div>
          <div className="metric">
            <span className="metric__label">volume processed</span>
            <span className="metric__value" id="m-volume">$718,378</span>
          </div>
          <div className="metric">
            <span className="metric__label">private tx cost</span>
            <span className="metric__value">$0.20</span>
          </div>
          <div className="metric">
            <span className="metric__label">distinct users</span>
            <span className="metric__value" id="m-users">962</span>
          </div>
          <div className="activities-section__head">
            <span className="activities-section__head-title">most frequent activities</span>
            <span className="activities-section__head-window">30D</span>
          </div>
          <div id="activities-list" className="activities-list"></div>

          <div className="pool-stats-grid__title">all-time</div>
          <div className="pool-stats-grid">
            {/* All DeFi-flavored stats are awaiting integration with the
                privacy pool, so each is tagged data-status="coming-soon".
                Styled into a soft tag + dimmed numbers by the CSS rule
                in dashboard/styles.css. */}
            <div className="stat-cell" data-status="coming-soon">
              <div className="stat-cell__label">PRIVATE TRANSFERS</div>
              <div className="stat-cell__value" id="m-private-transfers">0</div>
            </div>
            <div className="stat-cell" data-status="coming-soon">
              <div className="stat-cell__label">LENDING VOLUME</div>
              <div className="stat-cell__value" id="m-lending">$0</div>
            </div>
            <div className="stat-cell" data-status="coming-soon">
              <div className="stat-cell__label">BORROWING VOLUME</div>
              <div className="stat-cell__value" id="m-borrowing">$0</div>
            </div>
            <div className="stat-cell" data-status="coming-soon">
              <div className="stat-cell__label">VOLUME SWAPPED</div>
              <div className="stat-cell__value" id="m-swapped">$0</div>
            </div>
            <div className="stat-cell stat-cell--wide" data-status="coming-soon">
              <div className="stat-cell__label">PRIVATE STAKING</div>
              <div className="stat-cell__value" id="m-staking">$0</div>
            </div>
          </div>

          <div className="erc20-section__head">all shielded ERC20s</div>
          <div id="erc20-list" className="erc20-list"></div>
        </div>
      </aside>

      {/* App cards (Troves / Ekubo / AVNU / Endur) and the placeholder
          set are temporarily removed from the dashboard frontend — to
          be reintroduced once the layout direction is decided. The
          underlying modules (appdropdown.js, applivevolume.js) stay in
          place so re-enabling is just a JSX restore plus a flip in
          init.js's dynamic-import list. */}

      <aside id="tx-log" aria-label="Privacy pool live transactions">
        <header id="tx-log__head">
          <span>STRK20 // LIVE TX</span>
          <span className="live">REC</span>
        </header>
        <div id="tx-log__list"></div>
        {/* Uptime block removed — re-enable together with the matching
            import('./modules/uptime.js') line in dashboard/init.js. */}
      </aside>
    </div>
  )
}

// No export — loaded as a script tag, Dashboard becomes a window
// global referenced by app.jsx's pathname switch.
