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.rl10, state.progressMode);
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);
}
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();
}
} else if (focusedSearchId) {
const searchEl = rootEl.querySelector(`#${focusedSearchId}`);
if (searchEl) {
searchEl.focus();
if (selStart !== null && selEnd !== null) {
searchEl.setSelectionRange(selStart, selEnd);
}
}
}
}
function handleExport() {
const state = store.getState();
const activeProfile = store.getActiveProfile();
const profileSlug =
(activeProfile?.name || 'save-1')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '') || 'save';
const json = store.exportJson();
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${state.gameId}-${profileSlug}-poc-save-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
showToast(`Exported "${activeProfile?.name || 'Save'}" backup (.json)`);
}
function handleImport() {
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(`Import failed: ${err.message}`);
}
});
input.click();
}
rootEl.addEventListener('click', (e) => {
const extTriggerBtn = e.target.closest('[data-open-ext-menu]');
if (extTriggerBtn) {
store.toggleExternalMenu(
extTriggerBtn.dataset.openExtMenu,
extTriggerBtn.dataset.extContext || 'pokedex',
);
return;
}
const extMenuItem = e.target.closest('.ext-links-menu a.ext-links-item');
if (extMenuItem) {
setTimeout(() => store.closeExternalMenu(), 0);
return;
}
if (e.target.closest('.ext-links-menu')) return;
const hadExternalMenu = store.closeExternalMenu();
if (hadExternalMenu && e.target.classList.contains('modal-backdrop')) return;
const modalToggleBtn = e.target.closest('[data-toggle-species-btn]');
if (modalToggleBtn) {
store.toggleCaught(modalToggleBtn.dataset.toggleSpeciesBtn);
return;
}
const modalRl10Btn = e.target.closest('[data-toggle-rl10-btn]');
if (modalRl10Btn) {
store.toggleRl10(modalRl10Btn.dataset.toggleRl10Btn);
return;
}
const rl10ChipBtn = e.target.closest('[data-toggle-rl10]');
if (rl10ChipBtn) {
store.toggleRl10(rl10ChipBtn.dataset.toggleRl10, {
sectionId: rl10ChipBtn.dataset.sectionId || null,
choiceOption: rl10ChipBtn.dataset.choiceOption || null,
});
return;
}
const inspectBtn = e.target.closest('[data-inspect-species]');
if (inspectBtn) {
store.setSelectedSpeciesId(inspectBtn.dataset.inspectSpecies);
return;
}
const tabBtn = e.target.closest('[data-tab]');
if (tabBtn) {
store.setActiveTab(tabBtn.dataset.tab);
return;
}
const jumpTabBtn = e.target.closest('[data-jump-tab]');
if (jumpTabBtn) {
store.setActiveTab(jumpTabBtn.dataset.jumpTab);
window.scrollTo({ top: 0, behavior: 'smooth' });
return;
}
const sectionBtn = e.target.closest('[data-section-id]');
if (sectionBtn && sectionBtn.tagName === 'BUTTON') {
store.setActiveSectionId(sectionBtn.dataset.sectionId);
return;
}
const jumpSectionBtn = e.target.closest('[data-jump-section]');
if (jumpSectionBtn) {
store.setActiveTab('routes');
store.setActiveSectionId(jumpSectionBtn.dataset.jumpSection);
window.scrollTo({ top: 0, behavior: 'smooth' });
return;
}
const markSectionBtn = e.target.closest('[data-mark-section]');
if (markSectionBtn) {
store.setSectionComplete(
markSectionBtn.dataset.markSection,
markSectionBtn.dataset.markValue === '1',
);
return;
}
const areaToggleBtn = e.target.closest('[data-toggle-area]');
if (areaToggleBtn) {
store.toggleAreaCollapsed(areaToggleBtn.dataset.toggleArea);
return;
}
const groupToggleBtn = e.target.closest('[data-toggle-group]');
if (groupToggleBtn) {
store.toggleGroupCollapsed(groupToggleBtn.dataset.toggleGroup);
return;
}
const trainersToggleBtn = e.target.closest('[data-toggle-section-trainers]');
if (trainersToggleBtn) {
store.toggleSectionTrainersExpanded(trainersToggleBtn.dataset.toggleSectionTrainers);
return;
}
const dexFilterBtn = e.target.closest('[data-dex-filter]');
if (dexFilterBtn) {
store.setPokedexFilter(dexFilterBtn.dataset.dexFilter);
return;
}
const movedexTabBtn = e.target.closest('[data-movedex-tab]');
if (movedexTabBtn) {
store.setMovedexTab(movedexTabBtn.dataset.movedexTab);
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 === 'close-modal') {
if (e.target.classList.contains('modal-backdrop') || actionEl.tagName === 'BUTTON') {
store.setSelectedSpeciesId(null);
}
return;
}
if (action === 'close-profile-modal') {
if (e.target.classList.contains('modal-backdrop') || actionEl.tagName === 'BUTTON') {
store.setProfileModal(null);
}
return;
}
if (action === 'new-profile') {
store.setProfileModal({ mode: 'create' });
return;
}
if (action === 'rename-profile') {
store.setProfileModal({ mode: 'rename', profileId: store.getState().profileId });
return;
}
if (action === 'delete-profile') {
const activeProfile = store.getActiveProfile();
if (
store.getState().profiles.length > 1 &&
window.confirm(`Delete save profile "${activeProfile?.name || 'Save'}"?`)
) {
store.deleteProfile(activeProfile?.id);
showToast('Save profile deleted');
}
return;
}
if (action === 'clear-search') {
store.setSearchQuery('');
return;
}
if (action === 'clear-movedex-search') {
store.setMovedexSearch('');
return;
}
if (action === 'expand-all') {
store.setAllCollapsed(false);
return;
}
if (action === 'collapse-all') {
store.setAllCollapsed(true);
return;
}
if (action === 'reset-filters') {
store.setSearchQuery('');
store.setUncaughtOnly(false);
store.setMethodFilter('all');
store.setActiveSectionId('all');
return;
}
if (action === 'export-json') {
handleExport();
return;
}
if (action === 'import-json') {
handleImport();
return;
}
if (action === 'reset-progress') {
const activeProfile = store.getActiveProfile();
if (window.confirm(`Reset all Caught, RL10 & Trainer progress for "${activeProfile?.name || 'Save 1'}"?`)) {
store.resetProgress();
showToast('Save progress reset');
}
}
}
});
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, {
sectionId: e.target.dataset.sectionId || null,
choiceOption: e.target.dataset.choiceOption || null,
});
} 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 === 'method-filter') {
store.setMethodFilter(e.target.value);
} else if (e.target.id === 'progress-mode-select') {
store.setProgressMode(e.target.value);
showToast(
e.target.value === 'rl10'
? 'Goal switched to Research Lv. 10 (Unown completes in Sec 5)'
: 'Goal switched to Caught Only',
);
} else if (e.target.id === 'satchel-mp-toggle') {
store.setAllowSatchelMp(e.target.checked);
showToast(
e.target.checked
? 'Satchel MP Shop enabled (+4 early evos in Pre-Kleavor)'
: 'Satchel MP Shop skipped (Ore/Distortion timing)',
);
} else if (e.target.id === 'save-mythicals-toggle') {
store.setIncludeSaveMythicals(e.target.checked);
showToast(
e.target.checked
? 'Save-Data Mythicals included (Shaymin & Darkrai · 242 total)'
: 'Base Hisui Pokédex only (240 total)',
);
}
});
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 || data?.localSpritesAvailable) {
setSpriteBaseUrl('./assets/sprites');
render();
}
})
.catch(() => {});
}
return store;
}
if (typeof document !== 'undefined') {
const root = document.getElementById('app');
if (root) {
mountApp(root);
}
}