/**
 * SPCAMO_Import.js
 * ─────────────────────────────────────────────────────────────────────────────
 * JSON import handlers for EDITOR_SPCAMO.
 *
 * Depends on (must be loaded first):
 *   SPCAMO_ScenData.js    — SPCAMO_MONTHS, SPCAMO_WEATHER, SPCAMO_BATTLE_TYPES,
 *                           SPWW2_NATIONS, SPMBT_NATIONS
 *   SPCAMO_Translation.js — SP1_NATION_NAMES, SP2_NATION_NAMES,
 *                           SP1_TO_SPWW2_NATION, SP2_TO_SPMBT_NATION
 *
 * References editor globals (set by EDITOR_SPCAMO):
 *   _ab, _scen, _vlocs, _gameType
 *   _markDirty(), renderScenario(), renderVLocs()
 *
 * Public entry points called by the editor HTML buttons:
 *   importScenJSON()   — SCENARIO PARAMETERS (JSON) button
 *   importVlocJSON()   — VLOC JSON button
 */

'use strict';

// ─────────────────────────────────────────────────────────────────────────────
// Nation name translation helper
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Resolve a nation name string (as it appears in a SP1/SP2 JSON export)
 * to the corresponding SPWW2 or SPMBT nation index used by SPCAMO.
 *
 * Strategy:
 *   1. Search SP1_NATION_NAMES (ww2) or SP2_NATION_NAMES (mbt) for the string.
 *   2. Translate that source-game index via SP1_TO_SPWW2_NATION or SP2_TO_SPMBT_NATION.
 *   3. Fallback: direct case-insensitive search in SPWW2_NATIONS / SPMBT_NATIONS
 *      (catches names that appear identically in both games).
 *
 * Returns the SPCAMO nation index, or -1 if not found.
 *
 * @param {string} name  - Nation name as it appears in the source JSON
 * @param {string} game  - 'ww2' or 'mbt'
 */
function _lookupNationIdx(name, game) {
  if (!name) return -1;
  const lower = name.trim().toLowerCase();

  if (game === 'ww2') {
    const sp1Idx = SP1_NATION_NAMES.findIndex(n => n.toLowerCase() === lower);
    if (sp1Idx >= 0) {
      const spww2Idx = SP1_TO_SPWW2_NATION[sp1Idx];
      if (spww2Idx !== undefined) return spww2Idx;
    }
    const direct = SPWW2_NATIONS.findIndex(n => n.toLowerCase() === lower);
    if (direct >= 0) return direct;
  } else {
    const sp2Idx = SP2_NATION_NAMES.findIndex(n => n.toLowerCase() === lower);
    if (sp2Idx >= 0) {
      const spmbtIdx = SP2_TO_SPMBT_NATION[sp2Idx];
      if (spmbtIdx !== undefined) return spmbtIdx;
    }
    const direct = SPMBT_NATIONS.findIndex(n => n.toLowerCase() === lower);
    if (direct >= 0) return direct;
  }

  return -1;
}

// ─────────────────────────────────────────────────────────────────────────────
// Scenario parameter import
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Open a JSON file picker and import scenario parameters into _scen.
 * Handles: location, month, year, visibility, maxTurns, battleType,
 *          terrain (→ weather), p1Nation, p2Nation.
 * Called by the IMPORT SCENARIO PARAMETERS (JSON) button.
 */
function importScenJSON() {
  if (!_ab) { alert('Load a DAT file first.'); return; }

  const fi = document.getElementById('scen-json-input');
  fi.onchange = e => {
    const file = e.target.files[0];
    fi.value = '';
    if (!file) return;
    const r = new FileReader();
    r.onload = ev => {
      try {
        const data = JSON.parse(ev.target.result);
        const sc = data.scenario;
        if (!sc) throw new Error('No "scenario" object found in this JSON.');

        // Location (max 28 chars)
        if (sc.location != null) {
          _scen.location = String(sc.location).slice(0, 28);
        }

        // Month — JSON carries a name string; reverse-lookup to index
        if (sc.month != null) {
          const mName = String(sc.month);
          const mIdx  = SPCAMO_MONTHS.findIndex(m => m.toLowerCase() === mName.toLowerCase());
          if (mIdx >= 1) {
            _scen.month     = mIdx;
            _scen.monthName = SPCAMO_MONTHS[mIdx];
          }
        }

        // Year — JSON carries full 4-digit year; store as offset from 1900
        if (sc.year != null) {
          const fy = parseInt(sc.year);
          if (!isNaN(fy) && fy >= 1900 && fy <= 2155) {
            _scen.year     = (fy - 1900) & 0xFF;
            _scen.fullYear = fy;
          }
        }

        // Visibility
        if (sc.visibility != null) {
          _scen.visibility = Math.max(0, Math.min(255, parseInt(sc.visibility) || 0));
        }

        // Max Turns
        if (sc.maxTurns != null) {
          _scen.maxTurns = Math.max(1, Math.min(255, parseInt(sc.maxTurns) || 1));
        }

        // Battle Type — match string label to bf1/bf2 pair
        if (sc.battleType != null) {
          const bt = SPCAMO_BATTLE_TYPES.find(([, , label]) =>
            label.toLowerCase() === String(sc.battleType).toLowerCase());
          if (bt) {
            _scen.bf1        = bt[0];
            _scen.bf2        = bt[1];
            _scen.battleType = bt[2];
          }
        }

        // Terrain / Weather — SP1/SP2 exports as "Winter", "Summer", "Desert"
        if (sc.terrain != null) {
          const tName = String(sc.terrain).trim();
          const wIdx  = SPCAMO_WEATHER.findIndex(w => w.toLowerCase() === tName.toLowerCase());
          if (wIdx >= 0) {
            _scen.weather     = wIdx;
            _scen.weatherName = SPCAMO_WEATHER[wIdx];
          }
        }

        // P1 / P2 Nation — resolve string name to SPWW2/SPMBT nation index
        const warnings = [];
        const nations  = _gameType === 'mbt' ? SPMBT_NATIONS : SPWW2_NATIONS;

        if (sc.p1Nation != null) {
          const idx = _lookupNationIdx(String(sc.p1Nation), _gameType);
          if (idx >= 0) {
            _scen.p1NationIdx = idx;
            _scen.p1Nation    = nations[idx];
          } else {
            warnings.push(`P1 Nation "${sc.p1Nation}" not found in ${_gameType.toUpperCase()} nation table — skipped.`);
          }
        }

        if (sc.p2Nation != null) {
          const idx = _lookupNationIdx(String(sc.p2Nation), _gameType);
          if (idx >= 0) {
            _scen.p2NationIdx = idx;
            _scen.p2Nation    = nations[idx];
          } else {
            warnings.push(`P2 Nation "${sc.p2Nation}" not found in ${_gameType.toUpperCase()} nation table — skipped.`);
          }
        }

        renderScenario();
        _markDirty();

        if (warnings.length) {
          alert('Import completed with warnings:\n\n' + warnings.join('\n'));
        }

        const btn = document.getElementById('scen-import-btn');
        if (btn) {
          btn.textContent = '✓ IMPORTED';
          btn.style.color       = 'var(--amber)';
          btn.style.borderColor = 'var(--amber-dim)';
          setTimeout(() => {
            btn.textContent      = 'IMPORT SCENARIO PARAMETERS (JSON)';
            btn.style.color      = '';
            btn.style.borderColor = '';
            btn.style.background  = '';
          }, 2500);
        }
      } catch (err) {
        alert('Scenario JSON import error:\n' + err.message);
      }
    };
    r.readAsText(file);
  };
  fi.click();
}

// ─────────────────────────────────────────────────────────────────────────────
// Victory Location import
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Open a JSON file picker and import victory locations into _vlocs.
 * Slots present and non-empty in the JSON are updated; all others are cleared.
 * Called by the VLOC JSON button.
 */
function importVlocJSON() {
  if (!_ab) { alert('Load a DAT file first.'); return; }

  const fi = document.getElementById('vloc-json-input');
  fi.onchange = e => {
    const file = e.target.files[0];
    fi.value = '';
    if (!file) return;
    const r = new FileReader();
    r.onload = ev => {
      try {
        const data = JSON.parse(ev.target.result);
        const vlocs = data.victoryLocations;
        if (!Array.isArray(vlocs)) throw new Error('No "victoryLocations" array found in this JSON.');

        // Build a lookup map: index → JSON entry
        const byIndex = {};
        vlocs.forEach(v => { byIndex[v.index] = v; });

        // Resolve control value — prefer the human-readable controlLabel when present.
        const resolveControl = (entry) => {
          if (entry.controlLabel) {
            const lbl = entry.controlLabel.toLowerCase();
            if (lbl === 'p1') return 0;
            if (lbl === 'p2') return 1;
            if (lbl === 'neutral') return 2;
          }
          const raw = parseInt(entry.controlRaw);
          if (!isNaN(raw) && raw >= 0 && raw <= 2) return raw;
          return 2; // default to Neutral
        };

        const CTRL_LABEL = ['P1', 'P2', 'Neutral'];

        // Apply to all 21 VLOC slots.
        // Slots present in the JSON get their values updated; slots not present
        // (or explicitly isEmpty) are cleared to empty (0xDE).
        for (let i = 0; i < 21; i++) {
          const v   = _vlocs[i];
          if (!v) continue;
          const src = byIndex[i];

          if (src && !src.isEmpty) {
            v.isEmpty       = false;
            v.xloc          = Math.max(0, Math.min(254, parseInt(src.xloc)  || 0));
            v.yloc          = Math.max(0, Math.min(254, parseInt(src.yloc)  || 0));
            v.value         = Math.max(0, Math.min(255, parseInt(src.value) || 0));
            v.control       = resolveControl(src);
            v.controlLabel  = CTRL_LABEL[v.control] || 'Unknown';
          } else {
            v.isEmpty       = true;
            v.xloc          = 0xDE;
            v.yloc          = 0xDE;
            v.value         = 0;
            v.control       = 2;
            v.controlLabel  = '';
          }
        }

        // Refresh status bar count
        const active = _vlocs.filter(v => !v.isEmpty).length;
        document.getElementById('sb-vloccount').textContent = active + '/21';

        renderVLocs();
        _markDirty();

        const btn = document.getElementById('vloc-import-btn');
        if (btn) {
          btn.textContent = '✓ IMPORTED';
          btn.classList.add('imported');
          setTimeout(() => {
            btn.textContent = 'VLOC JSON';
            btn.classList.remove('imported');
          }, 2500);
        }
      } catch (err) {
        alert('VLOC JSON import error:\n' + err.message);
      }
    };
    r.readAsText(file);
  };
  fi.click();
}
