import { getCurrentAccountSession } from '../../account/ui/account-control.mjs'; import { pullEquipmentCatalog, websiteApiBase } from '../../account/data/account-api.mjs'; import { loadAccountConfig } from '../../account/domain/account-config.mjs'; import { createRodPrivateStorage } from '../data/rod-private-storage.mjs'; import { synchronizeRodsForAccount } from '../data/rod-account-service.mjs'; import { createPrivateRodRecord, nextRodSlot, removePrivateRod, savePrivateRod, updatePrivateRodRecord, } from '../domain/rod-inventory.mjs'; import { DEFAULT_USER_ROD_COLORS } from '../domain/rod-sync-contract.mjs'; import { ROD_TECHNIQUE_OPTIONS, canonicalRodTechnique, equipmentCatalogFilterOptions, equipmentCatalogReelFilterOptions, filterEquipmentCatalogItems, } from '../domain/rod-tackle-catalog.mjs'; import { rodTechniqueArtFamily } from '../domain/rod-technique-art.mjs'; import { t } from '../../../shared/i18n.mjs'; const elements = { add: document.querySelector('#add-rod-button'), cancel: document.querySelector('#cancel-rod-button'), catalogClose: document.querySelector('#rod-catalog-close'), catalogDialog: document.querySelector('#rod-catalog-dialog'), catalogBrand: document.querySelector('#rod-catalog-brand'), catalogFilters: document.querySelector('#rod-catalog-filters'), catalogGrid: document.querySelector('#rod-catalog-grid'), catalogMechanism: document.querySelector('#rod-catalog-mechanism'), catalogMechanismFilter: document.querySelector('#rod-catalog-mechanism-filter'), catalogModelYear: document.querySelector('#rod-catalog-model-year'), catalogReset: document.querySelector('#rod-catalog-reset'), catalogSearch: document.querySelector('#rod-catalog-search'), catalogSize: document.querySelector('#rod-catalog-size'), catalogSizeFilter: document.querySelector('#rod-catalog-size-filter'), catalogTechnique: document.querySelector('#rod-catalog-technique'), catalogTitle: document.querySelector('#rod-catalog-title'), colors: document.querySelector('#rod-color-options'), conflicts: document.querySelector('#rod-sync-conflicts'), count: document.querySelector('#rod-inventory-count'), delete: document.querySelector('#delete-rod-button'), dialog: document.querySelector('#rod-editor-dialog'), form: document.querySelector('#rod-editor-form'), grid: document.querySelector('#rod-inventory-grid'), name: document.querySelector('#rod-editor-name'), reelOrTip: document.querySelector('#rod-editor-reel-or-tip'), reelOrTipClear: document.querySelector('#rod-editor-reel-or-tip-clear'), reelOrTipKind: document.querySelector('#rod-editor-reel-or-tip-kind'), reelOrTipLabel: document.querySelector('#rod-editor-reel-or-tip-label'), line: document.querySelector('#rod-editor-line'), lineClear: document.querySelector('#rod-editor-line-clear'), notice: document.querySelector('#rod-editor-notice'), rod: document.querySelector('#rod-editor-rod'), rodClear: document.querySelector('#rod-editor-rod-clear'), slot: document.querySelector('#rod-editor-slot'), status: document.querySelector('#rod-sync-status'), sync: document.querySelector('#sync-rods-button'), technique: document.querySelector('#rod-editor-technique'), techniqueOptions: document.querySelector('#rod-technique-options'), title: document.querySelector('#rod-editor-title'), }; const storage = createRodPrivateStorage(); const configPromise = loadAccountConfig(); let session = getCurrentAccountSession(); let rods = []; let busy = false; let editingRodId = null; let loadRevision = 0; let syncController = null; let statusKey = session ? 'rods.status.local' : 'rods.status.disconnected'; let catalog = []; let catalogBaseUrl = ''; let catalogState = 'loading'; let catalogPickerKind = null; let catalogPickerFilters = { brand: 'all', mechanism: 'all', modelYear: 'all', size: 'all', technique: 'all', }; let catalogLoadRevision = 0; let editorComponents = { rod: null, reelOrTip: null, line: null }; const RETRYABLE_SYNC_STATUSES = new Set([ 'rods.status.slotConflict', 'rods.status.conflict', 'rods.status.pending', 'rods.status.offline', ]); const ROD_SYNC_POLL_MILLISECONDS = 60_000; const escapeHtml = (value) => String(value ?? '').replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"', })[character]); function isCurrentSession(expectedSession, revision = loadRevision) { return revision === loadRevision && session?.user.id === expectedSession.user.id && session.accessToken === expectedSession.accessToken; } function message(titleKey, copyKey) { return `

${escapeHtml(t(titleKey))}

${escapeHtml(t(copyKey))}

`; } function catalogItem(catalogId, kind = null) { return catalog.find((item) => item.id === catalogId && (kind === null || item.kind === kind)) ?? null; } function catalogImageUrl(item) { return new URL(item.imagePath, `${catalogBaseUrl}/`).toString(); } function materialCard(label, component, kind) { const item = component?.catalogId ? catalogItem(component.catalogId, kind) : null; const visual = item ? `` : ''; return `
${visual}
${escapeHtml(label)}
${escapeHtml(component?.name ?? t('rods.notSet'))}
`; } function rodCard(rod) { const disabled = busy ? ' disabled' : ''; const pairedKind = rod.reelOrTip?.kind === 'tip' ? 'rods.tip' : 'rods.reel'; const artFamily = rodTechniqueArtFamily(rod.technique?.name) ?? 'generic'; return `
${materialCard(t('rods.rod'), rod.rod, 'rod')}${materialCard(t(pairedKind), rod.reelOrTip, rod.reelOrTip?.kind ?? 'reel')}${materialCard(t('rods.line'), rod.line, 'line')}
`; } function render() { elements.count.textContent = `${rods.length} / 10`; elements.status.textContent = t(statusKey); elements.add.disabled = busy || !session || rods.length >= 10; elements.sync.hidden = busy || !session || !RETRYABLE_SYNC_STATUSES.has(statusKey); elements.sync.disabled = busy || !session; elements.sync.textContent = t('rods.retry'); if (elements.conflicts) { elements.conflicts.hidden = true; elements.conflicts.replaceChildren(); } if (!session) { elements.grid.innerHTML = message('rods.connect.heading', 'rods.connect.copy'); return; } if (busy && rods.length === 0) { elements.grid.innerHTML = message('rods.loading.heading', 'rods.loading.copy'); return; } elements.grid.innerHTML = rods.length ? rods.map(rodCard).join('') : message('rods.empty.heading', 'rods.empty.copy'); } function renderSlotOptions(selectedSlot, currentId) { elements.slot.innerHTML = Array.from({ length: 10 }, (_, index) => { const slot = index + 1; const occupied = rods.some((rod) => rod.id !== currentId && rod.slot === slot); return ``; }).join(''); } function renderColorOptions(selectedColor) { elements.colors.innerHTML = DEFAULT_USER_ROD_COLORS.map((entry) => ``).join(''); } function renderTackleOptions() { elements.techniqueOptions.innerHTML = ROD_TECHNIQUE_OPTIONS.map((option) => ``).join(''); } function defaultReelOrTipKind(technique) { const normalized = String(technique ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase(); return normalized.includes('coup') || normalized.includes('pole') ? 'tip' : 'reel'; } function catalogItems(kind) { return catalog.filter((item) => item.kind === kind); } function catalogUnavailableLabel() { if (catalogState === 'loading') return t('rods.catalog.loading'); if (catalogState === 'error') return t('rods.catalog.unavailable'); return t('rods.catalog.comingSoon'); } function renderCatalogSelection(button, kind, component, clearButton = null) { const published = component?.catalogId ? catalogItem(component.catalogId, kind) : null; const available = catalogItems(kind).length > 0; const name = published?.name ?? component?.name ?? (available ? t('rods.catalog.choose') : catalogUnavailableLabel()); const detail = published?.description ?? (component ? t('rods.catalog.unpublished') : available ? t('rods.catalog.verified') : t('rods.catalog.nonePublished')); const visual = published ? `` : ''; button.disabled = busy || !available; button.innerHTML = `${visual}${escapeHtml(name)}${escapeHtml(detail)}`; if (clearButton) { clearButton.hidden = !component; clearButton.disabled = busy; } } function renderEditorComponents() { const pairedKind = elements.reelOrTipKind.value === 'tip' ? 'tip' : 'reel'; elements.reelOrTipLabel.textContent = t(pairedKind === 'tip' ? 'rods.tip' : 'rods.reel'); renderCatalogSelection(elements.rod, 'rod', editorComponents.rod, elements.rodClear); renderCatalogSelection(elements.reelOrTip, pairedKind, editorComponents.reelOrTip, elements.reelOrTipClear); renderCatalogSelection(elements.line, 'line', editorComponents.line, elements.lineClear); elements.notice.hidden = catalogState !== 'error'; elements.notice.textContent = t('rods.catalog.unavailableCopy'); } function renderCatalogPicker() { if (!catalogPickerKind) return; const availableItems = catalogItems(catalogPickerKind); const options = equipmentCatalogFilterOptions(availableItems); const reelOptions = equipmentCatalogReelFilterOptions(availableItems, catalogPickerFilters.mechanism); if (catalogPickerFilters.brand !== 'all' && !options.brands.includes(catalogPickerFilters.brand)) catalogPickerFilters.brand = 'all'; if (catalogPickerFilters.modelYear !== 'all' && catalogPickerFilters.modelYear !== 'unknown' && !options.modelYears.includes(Number(catalogPickerFilters.modelYear))) { catalogPickerFilters.modelYear = 'all'; } if (catalogPickerFilters.modelYear === 'unknown' && !options.hasUnknownModelYear) catalogPickerFilters.modelYear = 'all'; if (catalogPickerFilters.technique !== 'all' && !options.techniques.includes(catalogPickerFilters.technique)) { catalogPickerFilters.technique = 'all'; } if (catalogPickerFilters.mechanism !== 'all' && !reelOptions.mechanisms.includes(catalogPickerFilters.mechanism)) { catalogPickerFilters.mechanism = 'all'; } const normalizedReelOptions = equipmentCatalogReelFilterOptions(availableItems, catalogPickerFilters.mechanism); if (catalogPickerFilters.size !== 'all' && !normalizedReelOptions.sizes.includes(catalogPickerFilters.size)) { catalogPickerFilters.size = 'all'; } elements.catalogBrand.innerHTML = `${options.brands.map((brand) => ``).join('')}`; elements.catalogBrand.value = catalogPickerFilters.brand; elements.catalogModelYear.innerHTML = `${options.modelYears.map((year) => ``).join('')}${options.hasUnknownModelYear ? `` : ''}`; elements.catalogModelYear.value = catalogPickerFilters.modelYear; elements.catalogTechnique.innerHTML = `${options.techniques.map((technique) => ``).join('')}`; elements.catalogTechnique.value = catalogPickerFilters.technique; const isReel = catalogPickerKind === 'reel'; elements.catalogMechanismFilter.hidden = !isReel; elements.catalogSizeFilter.hidden = !isReel; if (isReel) { elements.catalogMechanism.innerHTML = `${normalizedReelOptions.mechanisms.map((mechanism) => ``).join('')}`; elements.catalogMechanism.value = catalogPickerFilters.mechanism; elements.catalogSize.innerHTML = `${normalizedReelOptions.sizes.map((size) => ``).join('')}`; elements.catalogSize.value = catalogPickerFilters.size; } elements.catalogFilters.hidden = availableItems.length < 2; elements.catalogReset.hidden = Object.values(catalogPickerFilters).every((value) => value === 'all'); const query = elements.catalogSearch.value.trim(); const items = filterEquipmentCatalogItems(availableItems, { ...catalogPickerFilters, query }); const filtered = query || Object.values(catalogPickerFilters).some((value) => value !== 'all'); elements.catalogGrid.innerHTML = items.length ? items.map((item) => ``).join('') : `

${escapeHtml(filtered ? t('rods.catalog.noResult') : t('rods.catalog.nonePublished'))}

`; } function openCatalogPicker(kind) { if (busy || catalogItems(kind).length === 0) return; catalogPickerKind = kind; catalogPickerFilters = { brand: 'all', mechanism: 'all', modelYear: 'all', size: 'all', technique: 'all', }; elements.catalogSearch.value = ''; elements.catalogTitle.textContent = t(kind === 'rod' ? 'rods.catalog.chooseRod' : kind === 'line' ? 'rods.catalog.chooseLine' : kind === 'tip' ? 'rods.catalog.chooseTip' : 'rods.catalog.chooseReel'); renderCatalogPicker(); elements.catalogDialog.showModal(); elements.catalogSearch.focus(); } function selectCatalogItem(item) { if (item.kind === 'rod') { editorComponents.rod = { catalogId: item.id, name: item.name }; const previousKind = elements.reelOrTipKind.value; elements.reelOrTipKind.value = item.pairedKind ?? 'reel'; if (previousKind !== elements.reelOrTipKind.value) editorComponents.reelOrTip = null; if (!elements.technique.value && item.techniques[0]) elements.technique.value = item.techniques[0]; } else if (item.kind === 'line') { editorComponents.line = { catalogId: item.id, name: item.name }; } else { elements.reelOrTipKind.value = item.kind; editorComponents.reelOrTip = { catalogId: item.id, name: item.name }; } elements.catalogDialog.close(); catalogPickerKind = null; renderEditorComponents(); } function openEditor(rodId = null) { if (!session || busy) return; const rod = rodId ? rods.find((candidate) => candidate.id === rodId) : null; const slot = rod?.slot ?? nextRodSlot(rods); if (slot === null) return; editingRodId = rod?.id ?? null; elements.title.textContent = t(rod ? 'rods.editor.edit' : 'rods.editor.create'); elements.delete.hidden = !rod; elements.name.value = rod?.name ?? t('rods.editor.defaultName', { slot }); elements.technique.value = rod?.technique?.name ?? ''; elements.reelOrTipKind.value = rod?.reelOrTip?.kind ?? defaultReelOrTipKind(rod?.technique?.name); editorComponents = { rod: rod?.rod ?? null, reelOrTip: rod?.reelOrTip ?? null, line: rod?.line ?? null }; renderSlotOptions(slot, rod?.id ?? null); renderColorOptions(rod?.color ?? DEFAULT_USER_ROD_COLORS[slot - 1].hex); renderEditorComponents(); elements.dialog.showModal(); elements.name.focus(); } async function persistLocal(record, activeSession, revision) { const next = savePrivateRod(rods, record); await storage.saveInventory(activeSession.user.id, next); if (!isCurrentSession(activeSession, revision)) return false; rods = next; statusKey = 'rods.status.saved'; render(); return true; } function draftFromEditor(existing) { const techniqueName = elements.technique.value.trim(); const canonicalTechnique = canonicalRodTechnique(techniqueName); return { slot: Number(elements.slot.value), name: elements.name.value.trim(), color: new FormData(elements.form).get('color'), active: existing?.active ?? true, technique: techniqueName ? canonicalTechnique ?? { catalogId: existing?.technique?.name === techniqueName ? existing.technique.catalogId : null, name: techniqueName, } : null, rod: editorComponents.rod, reelOrTip: editorComponents.reelOrTip ? { ...editorComponents.reelOrTip, kind: elements.reelOrTipKind.value } : null, line: editorComponents.line, }; } async function saveEditor() { if (!session || busy || !elements.form.reportValidity()) return; const activeSession = session; const revision = loadRevision; const existing = editingRodId ? rods.find((rod) => rod.id === editingRodId) : null; const draft = draftFromEditor(existing); const record = existing ? updatePrivateRodRecord(rods, existing.id, draft) : createPrivateRodRecord(rods, draft); busy = true; render(); try { if (!await persistLocal(record, activeSession, revision)) return; elements.dialog.close(); editingRodId = null; } finally { if (isCurrentSession(activeSession, revision)) { busy = false; render(); } } if (!isCurrentSession(activeSession, revision)) return; await synchronize(); } async function deleteEditorRod() { if (!session || busy || !editingRodId) return; const activeSession = session; const revision = loadRevision; const rod = rods.find((candidate) => candidate.id === editingRodId); if (!rod || !window.confirm(t('rods.editor.deleteConfirm', { name: rod.name }))) return; busy = true; render(); try { // An unknown mirror record is queued from revision zero. A false result // therefore only means that the server mirror already contains a tombstone. await storage.queueDeletion(activeSession.user.id, rod.id); if (!isCurrentSession(activeSession, revision)) return; const next = removePrivateRod(rods, rod.id); await storage.saveInventory(activeSession.user.id, next); if (!isCurrentSession(activeSession, revision)) return; rods = next; elements.dialog.close(); editingRodId = null; statusKey = 'rods.status.saved'; } finally { if (isCurrentSession(activeSession, revision)) { busy = false; render(); } } if (!isCurrentSession(activeSession, revision)) return; await synchronize(); } async function synchronize({ automatic = false } = {}) { if (!session || busy) return; const revision = ++loadRevision; const activeSession = session; syncController?.abort(); const controller = new AbortController(); syncController = controller; busy = true; statusKey = automatic ? 'rods.status.loading' : 'rods.status.syncing'; render(); try { const localInventory = await storage.loadInventory(activeSession.user.id); if (!isCurrentSession(activeSession, revision)) return; rods = localInventory; render(); const config = await configPromise; if (!isCurrentSession(activeSession, revision)) return; const result = await synchronizeRodsForAccount(activeSession, websiteApiBase(window.location, config.apiBase), storage, { signal: controller.signal }); if (!isCurrentSession(activeSession, revision)) return; rods = result.inventory; statusKey = result.issues.length > 0 ? 'rods.status.slotConflict' : result.conflicts > 0 ? 'rods.status.conflict' : result.pending > 0 ? 'rods.status.pending' : 'rods.status.synced'; } catch (error) { if (!isCurrentSession(activeSession, revision)) return; const expired = error instanceof Error && error.message === 'algofish-server-401'; statusKey = expired ? 'rods.status.expired' : 'rods.status.offline'; if (expired) window.dispatchEvent(new CustomEvent('algofish:sessionexpired', { detail: { accountId: activeSession.user.id }, })); } finally { if (syncController === controller) syncController = null; if (revision === loadRevision) { busy = false; render(); } } } async function loadEquipmentCatalog() { const revision = ++catalogLoadRevision; catalogState = 'loading'; render(); if (elements.dialog.open) renderEditorComponents(); try { const config = await configPromise; const nextBaseUrl = websiteApiBase(window.location, config.apiBase); const response = await pullEquipmentCatalog(nextBaseUrl); if (revision !== catalogLoadRevision) return; catalogBaseUrl = nextBaseUrl; catalog = response.items; catalogState = 'ready'; } catch { if (revision !== catalogLoadRevision) return; catalog = []; catalogState = 'error'; } render(); if (elements.dialog.open) renderEditorComponents(); } async function replaceSession(nextSession) { syncController?.abort(); syncController = null; loadRevision += 1; session = nextSession; rods = []; busy = false; editingRodId = null; editorComponents = { rod: null, reelOrTip: null, line: null }; if (elements.dialog.open) elements.dialog.close(); if (elements.catalogDialog.open) elements.catalogDialog.close(); statusKey = session ? 'rods.status.local' : 'rods.status.disconnected'; render(); if (session) await synchronize({ automatic: true }); } elements.sync.addEventListener('click', () => void synchronize()); elements.add.addEventListener('click', () => openEditor()); elements.cancel.addEventListener('click', () => elements.dialog.close()); elements.delete.addEventListener('click', () => { const activeSession = session; const revision = loadRevision; void deleteEditorRod().catch(() => { if (!activeSession || !isCurrentSession(activeSession, revision)) return; statusKey = 'rods.status.saveFailed'; render(); }); }); elements.form.addEventListener('submit', (event) => { event.preventDefault(); const activeSession = session; const revision = loadRevision; void saveEditor().catch(() => { if (!activeSession || !isCurrentSession(activeSession, revision)) return; statusKey = 'rods.status.saveFailed'; render(); }); }); elements.technique.addEventListener('change', () => { const selectedRod = editorComponents.rod?.catalogId ? catalogItem(editorComponents.rod.catalogId, 'rod') : null; const nextKind = selectedRod?.pairedKind ?? defaultReelOrTipKind(elements.technique.value); if (nextKind !== elements.reelOrTipKind.value) editorComponents.reelOrTip = null; elements.reelOrTipKind.value = nextKind; renderEditorComponents(); }); elements.reelOrTipKind.addEventListener('change', () => { if (editorComponents.reelOrTip && catalogItem(editorComponents.reelOrTip.catalogId, elements.reelOrTipKind.value) === null) { editorComponents.reelOrTip = null; } renderEditorComponents(); }); elements.rod.addEventListener('click', () => openCatalogPicker('rod')); elements.reelOrTip.addEventListener('click', () => openCatalogPicker(elements.reelOrTipKind.value)); elements.line.addEventListener('click', () => openCatalogPicker('line')); elements.rodClear.addEventListener('click', () => { editorComponents.rod = null; renderEditorComponents(); }); elements.reelOrTipClear.addEventListener('click', () => { editorComponents.reelOrTip = null; renderEditorComponents(); }); elements.lineClear.addEventListener('click', () => { editorComponents.line = null; renderEditorComponents(); }); elements.catalogClose.addEventListener('click', () => elements.catalogDialog.close()); elements.catalogDialog.addEventListener('close', () => { catalogPickerKind = null; }); elements.catalogSearch.addEventListener('input', renderCatalogPicker); elements.catalogBrand.addEventListener('change', () => { catalogPickerFilters.brand = elements.catalogBrand.value; renderCatalogPicker(); }); elements.catalogModelYear.addEventListener('change', () => { catalogPickerFilters.modelYear = elements.catalogModelYear.value; renderCatalogPicker(); }); elements.catalogMechanism.addEventListener('change', () => { catalogPickerFilters.mechanism = elements.catalogMechanism.value; catalogPickerFilters.size = 'all'; renderCatalogPicker(); }); elements.catalogSize.addEventListener('change', () => { catalogPickerFilters.size = elements.catalogSize.value; renderCatalogPicker(); }); elements.catalogTechnique.addEventListener('change', () => { catalogPickerFilters.technique = elements.catalogTechnique.value; renderCatalogPicker(); }); elements.catalogReset.addEventListener('click', () => { catalogPickerFilters = { brand: 'all', mechanism: 'all', modelYear: 'all', size: 'all', technique: 'all', }; renderCatalogPicker(); }); elements.catalogGrid.addEventListener('click', (event) => { const button = event.target.closest('[data-catalog-item]'); const item = button ? catalogItem(button.dataset.catalogItem) : null; if (item) selectCatalogItem(item); }); elements.grid.addEventListener('click', (event) => { const button = event.target.closest('[data-rod-edit]'); if (button) openEditor(button.dataset.rodEdit); }); window.addEventListener('algofish:accountchange', (event) => { void replaceSession(event.detail?.session ?? null); }); window.addEventListener('online', () => { void synchronize({ automatic: true }); void loadEquipmentCatalog(); }); document.addEventListener('visibilitychange', () => { if (document.visibilityState !== 'visible') return; void synchronize({ automatic: true }); if (catalogState === 'error') void loadEquipmentCatalog(); }); window.setInterval(() => { if (!session || busy || document.visibilityState !== 'visible') return; void synchronize({ automatic: true }); }, ROD_SYNC_POLL_MILLISECONDS); window.addEventListener('algofish:localechange', () => { render(); if (elements.catalogDialog.open) renderCatalogPicker(); }); renderTackleOptions(); render(); void loadEquipmentCatalog(); if (session) void synchronize({ automatic: true });