// scout-api.jsx — Client-side helpers for calling Cloud Functions scoutImport and parsing Riot IDs

function parseRiotId(str) {
  if (typeof str !== 'string' || !str.includes('#')) {
    return null;
  }
  const lastHashIndex = str.lastIndexOf('#');
  if (lastHashIndex === -1) {
    return null;
  }
  const gameName = str.slice(0, lastHashIndex).trim();
  const tagLine = str.slice(lastHashIndex + 1).trim();
  if (!gameName || !tagLine) {
    return null;
  }
  return { gameName, tagLine };
}

async function scoutImport({ gameName, tagLine, platform }) {
  try {
    if (typeof firebase === 'undefined' || typeof firebase.functions !== 'function') {
      return {
        ok: false,
        code: 'unavailable',
        message: 'Firebase Functions SDK is not loaded.'
      };
    }
    const functions = firebase.functions();
    const callable = functions.httpsCallable('scoutImport');
    const result = await callable({ gameName, tagLine, platform });
    return result.data;
  } catch (error) {
    const rawCode = error && error.code ? error.code : 'unknown';
    const code = typeof rawCode === 'string' ? rawCode.replace(/^functions\//, '') : 'unknown';
    const message = (error && error.message) ? error.message : 'An error occurred during scouting import.';
    return { ok: false, code, message };
  }
}

async function scoutDeepImport({ gameName, tagLine, platform }) {
  try {
    if (typeof firebase === 'undefined' || typeof firebase.functions !== 'function') {
      return {
        ok: false,
        code: 'unavailable',
        message: 'Firebase Functions SDK is not loaded.'
      };
    }
    const functions = firebase.functions();
    const callable = functions.httpsCallable('scoutDeepImport');
    const result = await callable({ gameName, tagLine, platform });
    return result.data;
  } catch (error) {
    const rawCode = error && error.code ? error.code : 'unknown';
    const code = typeof rawCode === 'string' ? rawCode.replace(/^functions\//, '') : 'unknown';
    const message = (error && error.message) ? error.message : 'An error occurred during deep scouting.';
    return { ok: false, code, message };
  }
}

window.parseRiotId = parseRiotId;
window.scoutImport = scoutImport;
window.scoutDeepImport = scoutDeepImport;
Object.assign(window, { parseRiotId, scoutImport, scoutDeepImport });
