/**
 * PHANTOM ZENITH ORIGIN — OPERATIONS HUB
 * assets/js/components/OperationsHub.jsx
 * ─────────────────────────────────────────────────────────────
 * Orchestrates the multi-tool Operations page. Renders a
 * horizontal tool-selection menu and conditionally mounts the
 * active tool's React component below it.
 *
 * Tool components are registered as window.OpsTool_* globals
 * by their respective .jsx files (loaded via <script type="text/babel">
 * in index.html). This file reads those globals at render time,
 * so load order between tool files doesn't matter — they're all
 * defined before any React tree actually renders.
 *
 * Adding a new tool:
 *   1. Create assets/js/components/OpsTool_YourTool.jsx
 *   2. Register it: window.OpsTool_YourTool = YourComponent
 *   3. Add a <script type="text/babel" src="..."> in index.html
 *   4. Add an entry to TOOLS below
 *
 * Registration:
 *   window.PZO.pages['/operations'] — mount/unmount for router.js
 *
 * Depends on: React 18 (global), operations.css (hub menu styles)
 * ─────────────────────────────────────────────────────────────
 */

(function () {
  'use strict';

  const { useState } = React;

  // ══════════════════════════════════════════════════════════════
  // TOOL REGISTRY
  // Each entry defines a tab in the horizontal menu.
  // `component` is a function that returns the React component
  // from its window global — evaluated at render time, not at
  // parse time, so the tool .jsx files can load in any order.
  // ══════════════════════════════════════════════════════════════

  const TOOLS = [
    {
      id: 'worldmap',
      label: 'World Map',
      glyph: '⌖',
      description: 'Interactive regional map of Orryx. Click landmarks to explore locations around Haven Core.',
      component: function () { return window.OpsTool_WorldMap; }
    },
    {
      id: 'stagemap',
      label: 'Stage Map',
      glyph: '⬡',
      description: 'Procedural stage layout generator with per-stage tilesets and room weighting.',
      component: function () { return window.OpsTool_StageMap; }
    },
    {
      id: 'attributes',
      label: 'Attributes',
      glyph: '◈',              // matches Field Reference icon language
      description: 'Preview all six primary attributes for any RunnerType, Class, and Level.',
      component: function () { return window.OpsTool_Attributes; }
    }
    // ── Future tools ────────────────────────────────────────────
    // { id: 'damage',   label: 'Damage Calc', glyph: '⚔', ... },
    // { id: 'loot',     label: 'Loot Tables', glyph: '◆', ... },
  ];

  // ══════════════════════════════════════════════════════════════
  // TOOL MENU — Horizontal single-row selector
  // ══════════════════════════════════════════════════════════════

  function ToolMenu({ activeId, onSelect }) {
    return (
      <div className="ops-tool-menu">
        {TOOLS.map(function (tool) {
          var isActive = activeId === tool.id;
          return (
            <button
              key={tool.id}
              className={'ops-tool-tab' + (isActive ? ' active' : '')}
              onClick={function () { if (window.PZO.sound) window.PZO.sound.click(); onSelect(tool.id); }}
              title={tool.description}
            >
              <span className="ops-tool-glyph">{tool.glyph}</span>
              <span className="ops-tool-label">{tool.label}</span>
            </button>
          );
        })}
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════
  // HUB APP — Menu state + conditional tool render
  // ══════════════════════════════════════════════════════════════

  function OperationsHub() {
    var stored = TOOLS[0].id;  // default to first tool
    const [activeTool, setActiveTool] = useState(stored);

    // Look up the active tool's component from the registry.
    var toolEntry = TOOLS.find(function (t) { return t.id === activeTool; });
    var ToolComponent = toolEntry ? toolEntry.component() : null;

    return (
      <div className="container">
        <ToolMenu activeId={activeTool} onSelect={setActiveTool} />

        {/* key on activeTool forces full remount when switching tools,
            ensuring clean state (same pattern as Field Reference tabs). */}
        <div key={activeTool} className="ops-tool-viewport">
          {ToolComponent
            ? <ToolComponent />
            : <div className="ops-tool-missing">
                <span className="ops-tool-missing-icon">⚠</span>
                <span>Tool not loaded. Check console for errors.</span>
              </div>
          }
        </div>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════
  // PAGE REGISTRATION — wired into the SPA router
  // ══════════════════════════════════════════════════════════════

  window.PZO.pages['/operations'] = {
    mount: function (root) {
      document.title = 'PZO \u2014 Operations';

      root.innerHTML =
        '<div class="page-header">' +
          '<div class="page-eyebrow">// Operations \u2014 Interactive Tools</div>' +
          '<h1 class="page-title">Operations</h1>' +
          '<p class="page-subtitle">Interactive design tools built directly from the game\u2019s data models. Select a tool below.</p>' +
        '</div>' +
        '<div id="root"></div>' +
        '<footer class="site-footer">' +
          '<span>PHANTOM ZENITH ORIGIN \u2014 SOLO DEVELOPMENT</span>' +
          '<span class="footer-sig">// DEVHUB v0.1 \u2014 CONTENT INCOMPLETE BY DESIGN</span>' +
        '</footer>';

      var ErrorBoundary = window.PZO.ErrorBoundary;
      var reactRoot = ReactDOM.createRoot(document.getElementById('root'));
      reactRoot.render(<ErrorBoundary pageName="Operations"><OperationsHub /></ErrorBoundary>);
      window.PZO.activeReactRoot = reactRoot;
    },

    unmount: function () {
      // router.js calls unmountActiveReactRoot() before clearing innerHTML.
    }
  };

}());
