/**
 * PHANTOM ZENITH ORIGIN — OPERATIONS TOOL: ATTRIBUTE CALCULATOR
 * assets/js/components/OpsTool_Attributes.jsx
 * ─────────────────────────────────────────────────────────────
 * Extracted from the inline <script type="text/babel"> block that
 * previously lived in index.html. Contains all data definitions,
 * calculation logic, and React components for the Character
 * Attribute Calculator.
 *
 * Registration:
 *   window.OpsTool_Attributes = SimApp
 *
 * The OperationsHub reads this global and renders it when the
 * "Attributes" tool tab is active. This file is loaded via
 * <script type="text/babel" src="..."> in index.html — Babel
 * compiles it during its DOMContentLoaded pass.
 *
 * Depends on: React 18 (global), operations.css
 * ─────────────────────────────────────────────────────────────
 */

(function () {
  'use strict';

  const { useState, useMemo } = React;

  // ══════════════════════════════════════════════════════════════
  // DATA — Race, RunnerType prefix, and Class rank definitions
  // ══════════════════════════════════════════════════════════════

  const RACES = {
    mir:    { name: 'Mir (Human Male)',     HP:  0, WP: -1, ATK:  0, DFX: -1, RSN:  0, IMT:  1 },
    mirl:   { name: 'Mirl (Human Female)',  HP: -1, WP:  0, ATK:  0, DFX:  1, RSN:  0, IMT:  0 },
    karn:   { name: 'Karn (Robot Male)',     HP:  2, WP: -1, ATK:  2, DFX:  1, RSN: -1, IMT:  1 },
    karnex: { name: 'Karnex (Robot Female)', HP: 1, WP: -1, ATK:  1, DFX:  2, RSN: -1, IMT:  1 },
    sire:   { name: 'Sire (Elf Male)',      HP: -1, WP:  1, ATK:  0, DFX: -1, RSN:  2, IMT: -1 },
    sirea:  { name: 'Sirea (Elf Female)',   HP: -1, WP:  2, ATK: -1, DFX:  0, RSN:  1, IMT: -1 }
  };

  const TYPE_PREFIXES = {
    VAN: { name: 'Vanguard-aligned',  HP:  1, WP: -1, ATK:  1, DFX:  0, RSN: -1, IMT:  1 },
    SOL: { name: 'Solaris-aligned',   HP:  0, WP: -1, ATK:  0, DFX:  1, RSN: -1, IMT:  1 },
    TEK: { name: 'Teknician-aligned', HP: -1, WP:  1, ATK: -1, DFX:  0, RSN:  1, IMT:  0 }
  };

  const CLASSES = {
    Vanguard:  { HP:  2, WP: -2, ATK:  1, DFX:  0, RSN: -1, IMT:  1 },
    Solaris:   { HP:  1, WP: -1, ATK:  0, DFX:  2, RSN: -2, IMT:  1 },
    Teknician: { HP: -2, WP:  1, ATK: -1, DFX:  0, RSN:  2, IMT:  0 }
  };

  const RUNNER_TYPES = [
    'VANmir','VANmirl','VANkarn','VANkarnex','VANsire','VANsirea',
    'SOLmir','SOLmirl','SOLkarn','SOLkarnex','SOLsire','SOLsirea',
    'TEKmir','TEKmirl','TEKkarn','TEKkarnex','TEKsire','TEKsirea'
  ];

  const STATS = ['HP','WP','ATK','DFX','RSN','IMT'];
  const STAT_NAMES = {
    HP:  'Hit Points',
    WP:  'Willpower',
    ATK: 'Attack Power',
    DFX: 'Defense Index',
    RSN: 'Resonance',
    IMT: 'Impact'
  };

  // ══════════════════════════════════════════════════════════════
  // LOGIC — RunnerType parsing and attribute calculation
  // ══════════════════════════════════════════════════════════════

  function parseRunnerType(rt) {
    return { prefix: rt.substring(0, 3), race: rt.substring(3).toLowerCase() };
  }

  function calculateAttributes(runnerType, className, level) {
    const { prefix, race } = parseRunnerType(runnerType);
    const raceData  = RACES[race];
    const typeData  = TYPE_PREFIXES[prefix];
    const classData = CLASSES[className];
    const results   = {};

    for (const stat of STATS) {
      const racePercent  = raceData[stat]  * 6;
      const typePercent  = typeData[stat]  * 6;
      const classPercent = classData[stat] * 14;
      const unclamped    = racePercent + typePercent + classPercent;
      const totalPercent = Math.max(-40, Math.min(40, unclamped));
      const growth       = 1 + (level - 1) / 19;
      const finalStat    = 100 * growth * (1 + totalPercent / 100);

      results[stat] = {
        value: Math.round(finalStat * 10) / 10,
        racePercent, typePercent, classPercent, totalPercent,
        totalPercentUnclamped: unclamped,
        clamped: unclamped !== totalPercent
      };
    }
    return results;
  }

  // ══════════════════════════════════════════════════════════════
  // COMPONENTS
  // ══════════════════════════════════════════════════════════════

  /** Individual stat row with bar, breakdown, and modifier badge. */
  function StatBar({ stat, data, maxValue = 280 }) {
    const pct = (data.value / maxValue) * 100;
    const cls = data.totalPercent > 0 ? 'positive'
              : data.totalPercent < 0 ? 'negative'
              : 'neutral';

    return (
      <div className="stat-item">
        <div className="stat-header">
          <div>
            <span className="stat-name">{STAT_NAMES[stat]}</span>
            <span className="stat-abbr">({stat})</span>
          </div>
          <div className="stat-right">
            <span className={`stat-percent ${cls}`}>
              {data.totalPercent > 0 ? '+' : ''}{data.totalPercent}%
              {data.clamped && ' (clamped)'}
            </span>
            <span className="stat-value">{data.value}</span>
          </div>
        </div>
        <div className="stat-bar-bg">
          <div className={`stat-bar-fill ${stat.toLowerCase()}`}
               style={{ width: `${Math.min(100, pct)}%` }} />
        </div>
        <div className="stat-breakdown">
          <span>Race: {data.racePercent > 0 ? '+' : ''}{data.racePercent}%</span>
          <span>Type: {data.typePercent > 0 ? '+' : ''}{data.typePercent}%</span>
          <span>Class: {data.classPercent > 0 ? '+' : ''}{data.classPercent}%</span>
        </div>
      </div>
    );
  }

  /** Main Attribute Calculator — configuration + identity summary + stat bars. */
  function SimApp() {
    const [runnerType, setRunnerType] = useState('VANmir');
    const [className,  setClassName]  = useState('Vanguard');
    const [level,      setLevel]      = useState(1);

    const { prefix, race } = parseRunnerType(runnerType);
    const raceData = RACES[race];

    const attributes = useMemo(
      () => calculateAttributes(runnerType, className, level),
      [runnerType, className, level]
    );
    const totalStatSum = useMemo(
      () => STATS.reduce((s, stat) => s + attributes[stat].value, 0),
      [attributes]
    );

    return (
      <div className="attr-calc">
        <div className="grid">

          {/* ── Configuration panel ── */}
          <div className="panel">
            <h2 className="panel-title cyan">Character Configuration</h2>

            <div className="form-group">
              <label>RunnerType</label>
              <div className="runnertype-grid">
                <div className="runnertype-row-label van">Vanguard-aligned</div>
                {RUNNER_TYPES.filter(t => t.startsWith('VAN')).map(t => (
                  <button key={t} onClick={() => { if (window.PZO.sound) window.PZO.sound.click(); setRunnerType(t); }}
                    className={`runnertype-btn van ${runnerType === t ? 'active' : ''}`}>{t}</button>
                ))}
                <div className="runnertype-row-label sol">Solaris-aligned</div>
                {RUNNER_TYPES.filter(t => t.startsWith('SOL')).map(t => (
                  <button key={t} onClick={() => { if (window.PZO.sound) window.PZO.sound.click(); setRunnerType(t); }}
                    className={`runnertype-btn sol ${runnerType === t ? 'active' : ''}`}>{t}</button>
                ))}
                <div className="runnertype-row-label tek">Teknician-aligned</div>
                {RUNNER_TYPES.filter(t => t.startsWith('TEK')).map(t => (
                  <button key={t} onClick={() => { if (window.PZO.sound) window.PZO.sound.click(); setRunnerType(t); }}
                    className={`runnertype-btn tek ${runnerType === t ? 'active' : ''}`}>{t}</button>
                ))}
              </div>
            </div>

            <div className="form-group">
              <label>Class</label>
              <div className="class-buttons">
                {Object.keys(CLASSES).map(cls => (
                  <button key={cls} onClick={() => { if (window.PZO.sound) window.PZO.sound.click(); setClassName(cls); }}
                    className={`class-btn ${className === cls ? `active ${cls.toLowerCase()}` : 'inactive'}`}>{cls}</button>
                ))}
              </div>
            </div>

            <div className="form-group">
              <label>Level: <span className="level-value">{level}</span></label>
              <input type="range" min="1" max="20" value={level}
                onChange={e => setLevel(parseInt(e.target.value))} />
              <div className="level-labels"><span>1</span><span>10</span><span>20</span></div>
            </div>
          </div>

          {/* ── Identity summary ── */}
          <div className="panel">
            <h2 className="panel-title purple">Identity Summary</h2>
            <div className="summary-row">
              <span className="summary-label">Race</span>
              <span className="summary-value">{raceData.name}</span>
            </div>
            <div className="summary-row">
              <span className="summary-label">RunnerType Prefix</span>
              <span className="summary-value">{prefix} ({TYPE_PREFIXES[prefix].name})</span>
            </div>
            <div className="summary-row">
              <span className="summary-label">Active Class</span>
              <span className={`summary-value ${className.toLowerCase()}`}>{className}</span>
            </div>
            <div className="summary-row">
              <span className="summary-label">Level</span>
              <span className="summary-value">{level}</span>
            </div>
            <div className="summary-row">
              <span className="summary-label">Growth Multiplier</span>
              <span className="summary-value">×{(1 + (level - 1) / 19).toFixed(3)}</span>
            </div>
            <div className="total-box">
              <div className="total-label">// TOTAL STAT POINTS</div>
              <div className="total-value">{totalStatSum.toFixed(1)}</div>
            </div>
          </div>
        </div>

        {/* ── Attributes ── */}
        <div className="panel">
          <h2 className="panel-title cyan">Attributes</h2>
          <div className="stats-grid">
            {STATS.map(stat => <StatBar key={stat} stat={stat} data={attributes[stat]} />)}
          </div>
        </div>

        {/* ── Formula Reference ── */}
        <div className="panel">
          <h2 className="panel-title gray">// Formula Reference</h2>
          <div className="formula-box">
            <p>TotalPercent = clamp(RaceRank×6 + TypeRank×6 + ClassRank×14, -40%, +40%)</p>
            <p>Growth(L) = 1 + (L - 1) / 19</p>
            <p>FinalStat(L) = 100 × Growth(L) × (1 + TotalPercent / 100)</p>
          </div>
        </div>
      </div>
    );
  }

  // ── Global registration ──────────────────────────────────────
  // The OperationsHub reads this to render the tool when active.
  window.OpsTool_Attributes = SimApp;

}());
