import { createTrackerStore, computeGameProgress } from './state/tracker-store.js';
import { renderHeader } from './ui/header.js';
import { renderSidebar } from './ui/sidebar.js';
import { renderRoutesView } from './ui/routes-view.js';
import { renderPokedexView } from './ui/pokedex-view.js';
import { renderGuideView } from './ui/guide-view.js';
import { renderProfileModal, renderSpeciesModal } from './ui/modal.js';
import { setSpriteBaseUrl } from './ui/sprites.js';
export function mountApp(rootEl, store = createTrackerStore()) {
let toastTimeout = null;
function showToast(message) {
let toast = document.getElementById('poc-toast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'poc-toast';
toast.className = 'poc-toast';
document.body.appendChild(toast);
}
toast.textContent = message;
toast.classList.add('visible');
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => toast.classList.remove('visible'), 2600);
}
function positionExternalMenu(openMenu) {
if (!openMenu) return;
const trigger = rootEl.querySelector(
`[data-open-ext-menu="${openMenu.speciesId}"][data-ext-context="${openMenu.context}"]`,
);
const menu = rootEl.querySelector(
`[data-ext-menu-panel="${openMenu.speciesId}"][data-ext-context="${openMenu.context}"]`,
);
if (!trigger || !menu) return;
const rect = trigger.getBoundingClientRect();
const menuWidth = menu.offsetWidth || 244;
const menuHeight = menu.offsetHeight || 228;
const margin = 8;
let top = rect.bottom + 4;
if (top + menuHeight > window.innerHeight - margin && rect.top - menuHeight - 4 > margin) {
top = rect.top - menuHeight - 4;
}
let left = rect.right - menuWidth;
if (left < margin) left = rect.left;
left = Math.max(margin, Math.min(left, window.innerWidth - menuWidth - margin));
menu.style.position = 'fixed';
menu.style.top = `${Math.round(top)}px`;
menu.style.left = `${Math.round(left)}px`;
}
function render() {
const activeEl = document.activeElement;
const focusedSearchId =
activeEl && (activeEl.id === 'global-search' || activeEl.id === 'movedex-search')
? activeEl.id
: null;
const selStart = focusedSearchId ? activeEl.selectionStart : null;
const selEnd = focusedSearchId ? activeEl.selectionEnd : null;
const state = store.getState();
const game = store.getGame();
const progress = computeGameProgress(game, state.caught, state.ruleset, {
includeSpecialForms: state.includeSpecialForms,
});
const profiles = store.getProfilesWithCounts();
let mainHtml = '';
if (state.activeTab === 'routes') {
mainHtml = renderRoutesView(game, state, progress);
} else if (state.activeTab === 'pokedex') {
mainHtml = renderPokedexView(store, state);
} else {
mainHtml = renderGuideView(game, state);
}
rootEl.innerHTML = `
${renderHeader(game, state, progress, profiles)}
${state.activeTab === 'guide' ? '' : renderSidebar(game, state, progress)}
${mainHtml}
${renderSpeciesModal(game, state)}
${renderProfileModal(game, state)}
`;
positionExternalMenu(state.openExternalMenu);
if (state.profileModal) {
const profileInput = rootEl.querySelector('#profile-name-input');
if (profileInput) {
profileInput.focus();
profileInput.select();
}
return;
}
if (focusedSearchId) {
const nextInput = rootEl.querySelector(`#${focusedSearchId}`);
if (nextInput) {
nextInput.focus();
if (selStart !== null && selEnd !== null) {
nextInput.setSelectionRange(selStart, selEnd);
}
}
}
}
function triggerJsonDownload(filename, text) {
const blob = new Blob([text], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
function openImportPicker() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json,application/json';
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
try {
const text = await file.text();
const count = store.importJson(text);
showToast(`Imported ${count} caught Pokémon.`);
} catch (err) {
showToast(err?.message || 'Could not import JSON file.');
}
});
input.click();
}
rootEl.addEventListener('click', (e) => {
const extItemEl = e.target.closest('.ext-links-item');
if (extItemEl) {
setTimeout(() => store.closeExternalMenu(), 0);
return;
}
const extTriggerEl = e.target.closest('[data-open-ext-menu]');
if (extTriggerEl) {
e.preventDefault();
e.stopPropagation();
store.toggleExternalMenu(
extTriggerEl.dataset.openExtMenu,
extTriggerEl.dataset.extContext || 'pokedex',
);
return;
}
if (store.getState().openExternalMenu && !e.target.closest('.ext-links-menu')) {
store.closeExternalMenu();
}
const movedexTabEl = e.target.closest('[data-movedex-tab]');
if (movedexTabEl) {
store.setMovedexTab(movedexTabEl.dataset.movedexTab);
return;
}
const teamVariantEl = e.target.closest('[data-select-team-variant]');
if (teamVariantEl) {
store.setSelectedTeamVariant(teamVariantEl.dataset.selectTeamVariant);
return;
}
const eggPickEl = e.target.closest('[data-pick-jubilife-egg]');
if (eggPickEl) {
store.toggleJubilifeEggPick(eggPickEl.dataset.pickJubilifeEgg);
return;
}
const starterPickEl = e.target.closest('[data-pick-starter]');
if (starterPickEl) {
store.pickStarter(starterPickEl.dataset.pickStarter);
return;
}
const switchGameEl = e.target.closest('[data-switch-game]');
if (switchGameEl) {
store.switchGame(switchGameEl.dataset.switchGame);
showToast(`Loaded ${store.getGame().title}`);
return;
}
const tabEl = e.target.closest('[data-tab]');
if (tabEl) {
store.setActiveTab(tabEl.dataset.tab);
return;
}
const jumpTabEl = e.target.closest('[data-jump-tab]');
if (jumpTabEl) {
store.setActiveTab(jumpTabEl.dataset.jumpTab);
return;
}
const sectionEl = e.target.closest('[data-section-id]');
if (sectionEl) {
store.setActiveSectionId(sectionEl.dataset.sectionId);
return;
}
const jumpSecEl = e.target.closest('[data-jump-section]');
if (jumpSecEl) {
store.setActiveSectionId(jumpSecEl.dataset.jumpSection);
store.setActiveTab('routes');
return;
}
const areaTrainersBtn = e.target.closest('[data-toggle-area-trainers]');
if (areaTrainersBtn) {
store.toggleAreaTrainersExpanded(areaTrainersBtn.dataset.toggleAreaTrainers);
return;
}
const areaBtn = e.target.closest('[data-toggle-area]');
if (areaBtn) {
store.toggleAreaCollapsed(areaBtn.dataset.toggleArea);
return;
}
const inspectEl = e.target.closest('[data-inspect-species]');
if (inspectEl) {
store.setSelectedSpeciesId(inspectEl.dataset.inspectSpecies);
return;
}
const caughtBtn = e.target.closest('[data-toggle-species-btn]');
if (caughtBtn) {
store.toggleCaught(caughtBtn.dataset.toggleSpeciesBtn);
return;
}
const dexFilterBtn = e.target.closest('[data-dex-filter]');
if (dexFilterBtn) {
store.setPokedexFilter(dexFilterBtn.dataset.dexFilter);
return;
}
const sortBtn = e.target.closest('[data-sort-col]');
if (sortBtn) {
store.setPokedexSort(sortBtn.dataset.sortCol);
return;
}
const actionEl = e.target.closest('[data-action]');
if (actionEl) {
const action = actionEl.dataset.action;
if (action === 'clear-search') {
store.setSearchQuery('');
} else if (action === 'clear-movedex-search') {
store.setMovedexSearch('');
} else if (action === 'expand-all') {
store.setAllAreasCollapsed(false);
} else if (action === 'collapse-all') {
store.setAllAreasCollapsed(true);
} else if (action === 'clear-filters') {
store.setSearchQuery('');
store.setMethodFilter('all');
store.setUncaughtOnly(false);
} else if (action === 'new-profile') {
store.setProfileModal({ mode: 'create' });
} else if (action === 'rename-profile') {
store.setProfileModal({ mode: 'rename', profileId: store.getState().profileId });
} else if (action === 'delete-profile') {
const profiles = store.getState().profiles || [];
if (profiles.length <= 1) {
showToast('At least one save profile must remain.');
return;
}
const active = store.getActiveProfile();
if (window.confirm(`Delete save profile "${active.name}" and its progress?`)) {
store.deleteProfile(active.id);
showToast(`Deleted "${active.name}"`);
}
} else if (action === 'close-profile-modal') {
if (e.target === actionEl || !actionEl.classList.contains('modal-backdrop')) {
store.setProfileModal(null);
}
} else if (action === 'close-modal') {
if (e.target === actionEl || !actionEl.classList.contains('modal-backdrop')) {
store.setSelectedSpeciesId(null);
}
} else if (action === 'export-json') {
const json = store.exportJson();
const active = store.getActiveProfile();
const safeName = (active?.name || 'save').toLowerCase().replace(/[^a-z0-9]+/g, '-');
const dateStamp = new Date().toISOString().slice(0, 10);
triggerJsonDownload(`${store.getGame().id}-${safeName}-${dateStamp}.json`, json);
showToast('Exported save JSON backup.');
} else if (action === 'import-json') {
openImportPicker();
} else if (action === 'reset-progress') {
const active = store.getActiveProfile();
if (window.confirm(`Reset caught progress and trainers in "${active?.name || 'Save 1'}"?`)) {
store.resetProgress();
showToast(`Cleared progress for ${active?.name || 'Save 1'}.`);
}
}
}
});
rootEl.addEventListener('submit', (e) => {
if (e.target.id === 'profile-modal-form') {
e.preventDefault();
const mode = e.target.dataset.profileMode;
const profileId = e.target.dataset.profileId;
const input = e.target.querySelector('#profile-name-input');
const value = input?.value?.trim();
if (!value) return;
if (mode === 'rename') {
store.renameProfile(profileId, value);
showToast(`Renamed save to "${value}"`);
} else {
const created = store.createProfile(value);
showToast(`Created save "${created.name}"`);
}
}
});
rootEl.addEventListener('input', (e) => {
if (e.target.id === 'global-search') {
store.setSearchQuery(e.target.value);
} else if (e.target.id === 'movedex-search') {
store.setMovedexSearch(e.target.value);
}
});
rootEl.addEventListener('change', (e) => {
if (e.target.dataset.toggleSpecies) {
store.toggleCaught(e.target.dataset.toggleSpecies);
} else if (e.target.dataset.toggleTrainer) {
store.toggleTrainerDefeated(e.target.dataset.toggleTrainer);
} else if (e.target.id === 'profile-select') {
store.switchProfile(e.target.value);
} else if (e.target.id === 'uncaught-only-toggle') {
store.setUncaughtOnly(e.target.checked);
} else if (e.target.id === 'special-forms-toggle') {
store.setIncludeSpecialForms(e.target.checked);
} else if (e.target.id === 'incense-burner-toggle' || e.target.matches('[data-toggle-incense]')) {
store.setIncenseActive(e.target.checked);
showToast(
e.target.checked
? 'Special Forms enabled (+Crystal Onix, Stitched Gengar, Spiky-Eared Pichu = 550)'
: 'Strict 547 Excel Pokédex count active',
);
} else if (e.target.id === 'method-filter') {
store.setMethodFilter(e.target.value);
} else if (e.target.id === 'starter-select') {
store.setChosenStarter(e.target.value || null);
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const current = store.getState();
if (current.openExternalMenu) {
store.closeExternalMenu();
} else if (current.profileModal) {
store.setProfileModal(null);
} else if (current.selectedSpeciesId) {
store.setSelectedSpeciesId(null);
}
}
});
document.addEventListener(
'scroll',
(e) => {
if (!store.getState().openExternalMenu) return;
if (e.target instanceof Element && e.target.closest('.ext-links-menu')) return;
store.closeExternalMenu();
},
true,
);
rootEl.addEventListener(
'error',
(e) => {
const img = e.target;
if (typeof HTMLImageElement === 'undefined' || !(img instanceof HTMLImageElement)) return;
const fallback = img.dataset.fallbackSrc;
if (fallback && img.src !== fallback) {
img.dataset.fallbackSrc = '';
img.src = fallback;
} else {
img.classList.add('sprite-broken');
}
},
true,
);
store.subscribe(render);
render();
if (typeof fetch === 'function') {
fetch('./api/assets-status')
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data?.hasLocalSprites) {
setSpriteBaseUrl('./assets/sprites');
render();
}
})
.catch(() => {});
}
return store;
}
if (typeof document !== 'undefined') {
const root = document.getElementById('app');
if (root) mountApp(root);
}