// Raw package data (ids/prices/numbers are stable; display text resolves via i18n in getPackages()).
const PACKAGES = [
  { id:'starter', price:249, spots:250, markets:1,
    featKeys:['pkg.feat.spots250','pkg.feat.market1','pkg.feat.days30','pkg.feat.reportBasic'] },
  { id:'growth', price:499, spots:500, markets:2, popular:true,
    featKeys:['pkg.feat.spots500','pkg.feat.markets2','pkg.feat.days30','pkg.feat.reportAdv','pkg.feat.priority'] },
  { id:'pro', price:899, spots:1000, markets:3,
    featKeys:['pkg.feat.spots1000','pkg.feat.markets3','pkg.feat.days30','pkg.feat.reportAdv','pkg.feat.targeting'] },
  { id:'enterprise', price:null, spots:9999, markets:9,
    featKeys:['pkg.feat.customMarkets','pkg.feat.manager','pkg.feat.analytics','pkg.feat.api'] },
];

const GOALS = [
  { id:'awareness', icon:'speaker' },
  { id:'sales', icon:'tag' },
  { id:'event', icon:'cal' },
  { id:'calls', icon:'headset' },
];

// Business categories grouped by sector. ids are stable (what gets stored in data.category); 'other' last.
// Labels + group headers resolve via i18n (camp.cat.<id> / camp.catgroup.<g>) at render time.
const CATEGORY_GROUPS = [
  { g:'automotive', ids:['auto.dealer','auto.repair','auto.parts'] },
  { g:'food',       ids:['food.restaurant','food.fastfood','food.grocery'] },
  { g:'retail',     ids:['retail','furniture'] },
  { g:'home',       ids:['home.plumbing','home.hvac','home.landscaping','home.roofing','home.remodeling'] },
  { g:'health',     ids:['health.medical','health.dental','health.vision','health.chiro','health.hearing'] },
  { g:'realestate', ids:['realestate'] },
  { g:'finance',    ids:['finance.bank','finance.insurance','finance.mortgage','finance.tax','remittance'] },
  { g:'legal',      ids:['legal','immigration'] },
  { g:'beauty',     ids:['beauty.salon','beauty.barber','beauty.spa'] },
  { g:'lifestyle',  ids:['fitness','education'] },
  { g:'events',     ids:['events','wedding'] },
  { g:'business',   ids:['travel','jobs','telecom'] },
  { g:'services',   ids:['pets','moving','cleaning'] },
  { g:'community',  ids:['religious','nonprofit'] },
  { g:null,         ids:['other'] },
];
const CATEGORIES = CATEGORY_GROUPS.reduce((a,s)=>a.concat(s.ids), []); // flat id list

// Hidden search aliases per category id (language-agnostic, matched accent-insensitively in the
// combobox in addition to the visible label). Categories not listed here simply match by label.
const CATEGORY_ALIASES = {
  'food.grocery': ['supermercado','supermarket','bodega','grocery','abarrotes','comestibles','mercado','minimarket','tienda de comida','colmado'],
};

const LANGS = [
  { id:'en', name:'English' },
  { id:'es', name:'Spanish' },
];

// Markets/stations come from static JSON loaded via fetch() — NOT bundled, NOT Babel-parsed —
// so this scales to thousands of stations (Phase 2: FCC). Two layers:
//   markets-index.json  -> { states:[{code,name,markets:[{id,city,pop,count}]}] }  (lightweight list)
//   stations.json       -> { marketId: [{id,name,fmt,reach}] }                      (loaded on demand)
// Both are fetched at most once and cached on window. STATIONS_BY_ID is a flat id->station lookup
// (with marketId/city/state attached) so the review step can resolve a selection without re-walking.
let _idxPromise = null, _staPromise = null;
window.MARKETS_INDEX = null;
window.STATIONS = null;
window.STATIONS_BY_ID = null;
function loadMarketsIndex(){
  if(!_idxPromise) _idxPromise = fetch('data/markets-index.json').then(r=>r.json()).then(j=>{ window.MARKETS_INDEX = j; return j; });
  return _idxPromise;
}
function loadStations(){
  if(!_staPromise) _staPromise = Promise.all([loadMarketsIndex(), fetch('data/stations.json').then(r=>r.json())]).then(function(res){
    var idx = res[0], sta = res[1];
    window.STATIONS = sta;
    var byId = {};
    idx.states.forEach(function(st){ st.markets.forEach(function(m){ (sta[m.id]||[]).forEach(function(s){ byId[s.id] = Object.assign({}, s, { marketId:m.id, city:m.city, state:st.code }); }); }); });
    window.STATIONS_BY_ID = byId;
    return sta;
  });
  return _staPromise;
}

// Voice names are proper nouns (kept); meta descriptions resolve via i18n. `lang` is the AD voice language (data, not UI).
const VOICES = [
  { id:'marcus', name:'Marcus', lang:'EN' },
  { id:'olivia', name:'Olivia', lang:'EN' },
  { id:'james', name:'James', lang:'EN' },
  { id:'sofia', name:'Sofía', lang:'ES' },
  { id:'diego', name:'Diego', lang:'ES' },
  { id:'carmen', name:'Carmen', lang:'ES' },
];

const DAYPARTS = [
  { id:'am', time:'6a–10a', mult:1.4 },
  { id:'mid', time:'10a–3p', mult:1.0 },
  { id:'pm', time:'3p–7p', mult:1.35 },
  { id:'eve', time:'7p–12a', mult:0.85 },
];

const fmtNum = (n) => n>=1000 ? (n/1000).toFixed(n%1000===0?0:1)+'K' : ''+n;
const fmtMoney = (n) => '$'+n.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2});

// i18n-aware getters: return copies with display text translated to the current language.
// Components call these at render time, so they re-translate when the language toggles (App re-renders on 'langchange').
// NOTE: must NOT be named `T` — top-level consts leak onto the global object when @babel/standalone
// runs these scripts, and a global `T` would clobber window.T (the real translator) → infinite recursion.
const tr = (k)=> (window.T ? window.T(k) : k);
const getPackages   = ()=> PACKAGES.map(p=>({ ...p, name:tr('pkg.'+p.id+'.name'), sub:tr('pkg.'+p.id+'.sub'), feats:p.featKeys.map(tr) }));
const getGoals      = ()=> GOALS.map(g=>({ ...g, name:tr('camp.goal.'+g.id), desc:tr('camp.goal.'+g.id+'.desc') }));
const getCategories = ()=> CATEGORIES.map(id=>({ id, label:tr('camp.cat.'+id) }));
const getCategoryGroups = ()=> CATEGORY_GROUPS.map(s=>({
  group: s.g,
  label: s.g ? tr('camp.catgroup.'+s.g) : '',
  items: s.ids.map(id=>({ id, label:tr('camp.cat.'+id) })),
}));
const getVoices     = ()=> VOICES.map(v=>({ ...v, meta:tr('camp.voice.'+v.id+'.meta') }));
const getDayparts   = ()=> DAYPARTS.map(d=>({ ...d, name:tr('camp.daypart.'+d.id) }));

Object.assign(window, { PACKAGES, GOALS, CATEGORIES, LANGS, VOICES, DAYPARTS, fmtNum, fmtMoney,
  getPackages, getGoals, getCategories, getCategoryGroups, getVoices, getDayparts, CATEGORY_ALIASES,
  loadMarketsIndex, loadStations });
