import { createCatalogInventory } from '../data/catalog-inventory.mjs'; import { reelBookmarksStorageKey } from '../data/inventory-account-storage.mjs'; import { getCurrentAccountSession } from '../../account/ui/account-control.mjs'; import { REEL_CASTING_CLASSES, REEL_SIZE_CLASSES, REEL_TECHNIQUES, } from '../domain/reel-classification.mjs'; import { queryReels } from '../domain/reel-query.mjs'; import { getLocale, t } from '../../../shared/i18n.mjs'; import { safeExternalUrl } from '../../../shared/safe-url.mjs'; import { reelVisualMarkup } from './reel-visual.mjs'; import { localizeReelValue } from './reel-value-localization.mjs'; import { formatCapacityDual, formatForceDual, formatMassDual, formatRetrieveDual, } from './unit-format.mjs'; const elements = { catalog: document.querySelector('#catalog-grid'), catalogProgress: document.querySelector('#catalog-progress'), catalogProgressLabel: document.querySelector('#catalog-progress-label'), catalogLoadMore: document.querySelector('#catalog-load-more'), catalogSearch: document.querySelector('#catalog-search'), catalogSummary: document.querySelector('#catalog-summary'), catalogResultCount: document.querySelector('#catalog-result-count'), catalogTypeStrip: document.querySelector('#reel-type-strip'), catalogTypeFilters: document.querySelector('#catalog-type-filters'), catalogDragPositionControl: document.querySelector('#catalog-drag-position-control'), catalogDragPositionFilters: document.querySelector('#catalog-drag-position-filters'), catalogClassBrowser: document.querySelector('#reel-class-browser'), catalogClassTitle: document.querySelector('#reel-class-title'), catalogClassHelp: document.querySelector('#reel-class-help'), catalogClassStrip: document.querySelector('#reel-class-strip'), catalogClassControl: document.querySelector('#catalog-class-control'), catalogTechniqueFilters: document.querySelector('#catalog-technique-filters'), catalogBrandFilters: document.querySelector('#catalog-brand-filters'), catalogBrandTotal: document.querySelector('#catalog-brand-total'), catalogModelYear: document.querySelector('#catalog-model-year'), catalogClassFilter: document.querySelector('#catalog-class-filter'), catalogSort: document.querySelector('#catalog-sort'), catalogReset: document.querySelector('#catalog-reset'), catalogDetail: document.querySelector('#catalog-detail'), }; const catalog = createCatalogInventory().catalog; let inventoryAccountId = getCurrentAccountSession()?.user.id ?? null; let view = 'rods'; let selectedCatalogProductId = null; const CATALOG_BATCH_SIZE = 10; let catalogVisibleCount = CATALOG_BATCH_SIZE; let catalogQueryKey = ''; const catalogFilters = { mechanism: 'all', dragPosition: 'all', modelYear: 'all', classCode: 'all', techniques: new Set(), brands: new Set(), }; let catalogBookmarks = new Set(loadCatalogBookmarks(inventoryAccountId)); const REEL_TYPE_FILTERS = Object.freeze([ { id: 'all', color: '#10C8F4', representativeClass: '4000' }, { id: 'spincast', color: '#3B9BFF', representativeClass: 'CAPOTÉ' }, { id: 'casting', color: '#FF4D61', representativeClass: 'CASTING' }, { id: 'spinning', color: '#35D45B', representativeClass: '4000' }, ]); const DRAG_POSITION_FILTERS = Object.freeze(['all', 'front', 'rear']); function loadCatalogBookmarks(accountId = inventoryAccountId) { try { const stored = JSON.parse(localStorage.getItem(reelBookmarksStorageKey(accountId)) ?? '[]'); return Array.isArray(stored) ? stored.filter((id) => typeof id === 'string') : []; } catch { return []; } } function saveCatalogBookmarks() { try { localStorage.setItem(reelBookmarksStorageKey(inventoryAccountId), JSON.stringify([...catalogBookmarks])); } catch { // Les favoris restent facultatifs si le navigateur refuse le stockage local. } } function escapeHtml(value) { return String(value ?? '').replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"', })[character]); } function classLabel(code) { const key = `inventory.class.${code}`; const label = t(key); return label === key ? code : label; } const reelMechanismLabel = (mechanism = 'spinning') => t(`inventory.reelMechanism.${mechanism}`); const reelTypeLabel = (mechanism) => t(`inventory.catalog.type.${mechanism}`); const dragPositionLabel = (position) => t(`inventory.dragPosition.${position}`); const techniqueLabel = (key) => t(`inventory.technique.${key}`); function officialSourceLink(product) { const sourceUrl = safeExternalUrl(product?.sourceUrl); return sourceUrl ? `${escapeHtml(t('inventory.catalog.official'))}` : ''; } function equipmentVisual(product) { return product?.kind === 'reel' ? reelVisualMarkup(product) : '
'; } function catalogCardSpecifications(product) { const primary = []; if (Number.isFinite(product.ratio)) primary.push(`${t('inventory.property.ratio')} ${product.ratio}:1`); if (Number.isFinite(product.weightG)) primary.push(formatMassDual(product.weightG, getLocale())); const capacity = typeof product.monoCapacity === 'string' ? product.monoCapacity.split(';')[0].trim() : product.monoCapacity; return { primary: primary.join(' · '), capacity: formatCapacityDual(capacity, getLocale()) }; } function productProperties(product) { const localized = (value) => localizeReelValue(value, getLocale()); const compatibility = Object.entries(product.compatibility ?? {}) .map(([key, level]) => `${techniqueLabel(key)} : ${t(`inventory.compatibility.${level}`)}`) .join(' · '); const values = [ [t('inventory.property.brand'), product.brand], [t('inventory.property.model'), product.model], [t('inventory.property.reference'), product.sku], [t('inventory.property.use'), localized(product.use)], [t('inventory.property.market'), localized(product.market)], [t('inventory.property.modelYear'), product.modelYear], [t('inventory.property.size'), localized(product.manufacturerSize)], [t('inventory.property.class'), `${product.algofishClass} · ${classLabel(product.algofishClass)}`], [t('inventory.property.reelType'), reelMechanismLabel(product.reelMechanism)], [t('inventory.property.dragPosition'), product.reelMechanism === 'spinning' ? dragPositionLabel(product.dragPosition) : null], [t('inventory.property.ratio'), Number.isFinite(product.ratio) ? `${product.ratio}:1` : null], [t('inventory.property.retrieve'), Number.isFinite(product.retrieveCm) ? formatRetrieveDual(product.retrieveCm, getLocale()) : null], [t('inventory.property.drag'), localized(product.brake)], [t('inventory.property.dragPower'), Number.isFinite(product.dragKg) ? formatForceDual(product.dragKg, getLocale()) : null], [t('inventory.property.baitrunner'), product.baitrunner ? (getLocale() === 'fr' ? 'Oui' : 'Yes') : (getLocale() === 'fr' ? 'Non' : 'No')], [t('inventory.property.weight'), Number.isFinite(product.weightG) ? formatMassDual(product.weightG, getLocale()) : null], [t('inventory.property.bearings'), localized(product.bearings)], [t('inventory.property.mono'), localized(formatCapacityDual(product.monoCapacity, getLocale()))], [t('inventory.property.braid'), localized(formatCapacityDual(product.braidCapacity, getLocale()))], [t('inventory.property.spool'), localized(product.spool)], [t('inventory.property.body'), localized(product.body)], [t('inventory.property.lineClip'), localized(product.lineClip)], [t('inventory.property.spareSpool'), localized(product.spareSpool)], [t('inventory.property.technologies'), localized(product.technologies)], [t('inventory.property.compatibilities'), compatibility], [t('inventory.property.data'), localized(product.dataQuality)], [t('inventory.property.verified'), product.verifiedAt], ]; return values.filter(([, value]) => value !== null && value !== undefined && value !== ''); } function reelCatalogProducts() { return catalog.filter((product) => product.kind === 'reel' && (product.active2026 || product.catalogStatus === 'visual-candidate')); } function catalogTechniqueTags(product) { return Object.entries(product.compatibility ?? {}) .filter(([, level]) => level !== 'discouraged') .map(([key, level]) => `${escapeHtml(techniqueLabel(key))}`) .join(''); } function renderCatalogFilters(products) { const brandCounts = products.reduce((counts, product) => counts.set(product.brand, (counts.get(product.brand) ?? 0) + 1), new Map()); const modelYears = [...new Set(products .map((product) => Number.parseInt(product.modelYear, 10)) .filter(Number.isInteger))].sort((left, right) => right - left); const hasUnknownModelYear = products.some((product) => product.modelYear === null || product.modelYear === undefined || !Number.isInteger(Number.parseInt(product.modelYear, 10))); if (catalogFilters.modelYear !== 'all' && catalogFilters.modelYear !== 'unknown' && !modelYears.includes(Number(catalogFilters.modelYear))) catalogFilters.modelYear = 'all'; const spinningProducts = products.filter((product) => product.reelMechanism === 'spinning'); const showDragPosition = ['all', 'spinning'].includes(catalogFilters.mechanism); if (!showDragPosition) catalogFilters.dragPosition = 'all'; elements.catalogSummary.textContent = t('inventory.catalog.summary', { reels: products.length, brands: brandCounts.size, types: REEL_TYPE_FILTERS.length - 1, classes: REEL_SIZE_CLASSES.length + REEL_CASTING_CLASSES.length, }); elements.catalogTechniqueFilters.innerHTML = Object.keys(REEL_TECHNIQUES).map((key) => ``).join(''); elements.catalogTypeFilters.innerHTML = REEL_TYPE_FILTERS.map((type) => { const count = type.id === 'all' ? products.length : products.filter((product) => product.reelMechanism === type.id).length; return ``; }).join(''); elements.catalogDragPositionControl.hidden = !showDragPosition; elements.catalogDragPositionFilters.innerHTML = showDragPosition ? DRAG_POSITION_FILTERS.map((position) => { const count = position === 'all' ? spinningProducts.length : spinningProducts.filter((product) => product.dragPosition === position).length; return ``; }).join('') : ''; elements.catalogBrandTotal.textContent = `(${brandCounts.size})`; elements.catalogBrandFilters.innerHTML = [...brandCounts.entries()] .sort(([left], [right]) => left.localeCompare(right, getLocale())) .map(([brand, count]) => ``).join(''); elements.catalogModelYear.innerHTML = `${modelYears.map((year) => ``).join('')}${hasUnknownModelYear ? `` : ''}`; elements.catalogTypeStrip.innerHTML = REEL_TYPE_FILTERS.map((type) => { const count = type.id === 'all' ? products.length : products.filter((product) => product.reelMechanism === type.id).length; const visual = type.id === 'all' ? '' : equipmentVisual({ kind: 'reel', algofishClass: type.representativeClass, classColor: type.color, genericImageId: `type-${type.id}`, reelMechanism: type.id }); return ``; }).join(''); const showSizes = ['all', 'spinning', 'casting'].includes(catalogFilters.mechanism); const classItems = catalogFilters.mechanism === 'casting' ? REEL_CASTING_CLASSES : REEL_SIZE_CLASSES; const classMechanism = catalogFilters.mechanism === 'casting' ? 'casting' : 'spinning'; if (!showSizes || !classItems.some((item) => item.code === catalogFilters.classCode)) { catalogFilters.classCode = 'all'; } elements.catalogClassBrowser.hidden = !showSizes; elements.catalogClassControl.hidden = !showSizes; elements.catalogClassTitle.textContent = t(classMechanism === 'casting' ? 'inventory.catalog.castingClasses' : 'inventory.catalog.fixedClasses'); elements.catalogClassHelp.textContent = t(classMechanism === 'casting' ? 'inventory.catalog.castingClassesHelp' : 'inventory.catalog.fixedClassesHelp'); elements.catalogClassStrip.dataset.mode = classMechanism === 'casting' ? 'casting' : 'fixed'; elements.catalogClassStrip.style.setProperty('--class-count', classItems.length); elements.catalogClassFilter.disabled = !showSizes; elements.catalogClassFilter.innerHTML = `${classItems.map((item) => ``).join('')}`; elements.catalogClassStrip.innerHTML = classItems.map((item) => { const sample = { kind: 'reel', algofishClass: item.code, classColor: item.color, genericImageId: item.imageId, size: item.nominalSize ?? item.code, reelMechanism: classMechanism }; const count = products.filter((product) => product.algofishClass === item.code).length; return ``; }).join(''); } function filteredCatalogProducts(products) { return queryReels(products, { brands: catalogFilters.brands, classCode: catalogFilters.classCode, dragPosition: catalogFilters.dragPosition, locale: getLocale(), mechanism: catalogFilters.mechanism, modelYear: catalogFilters.modelYear, query: elements.catalogSearch.value, sort: elements.catalogSort.value, techniques: catalogFilters.techniques, searchText: (product) => { const compatibility = Object.entries(product.compatibility ?? {}) .map(([key, level]) => `${techniqueLabel(key)} ${t(`inventory.compatibility.${level}`)}`) .join(' '); return `${product.brand} ${product.model} ${product.name} ${product.type ?? ''} ${product.use ?? ''} ${localizeReelValue(product.type, getLocale()) ?? ''} ${localizeReelValue(product.use, getLocale()) ?? ''} ${product.algofishClass ?? ''} ${compatibility}`; }, }); } function renderCatalogDetail(product) { if (!product) { elements.catalogDetail.innerHTML = `
${escapeHtml(t('inventory.catalog.noResults'))}
`; return; } const excludedLabels = [t('inventory.property.brand'), t('inventory.property.model'), t('inventory.property.compatibilities')]; const properties = productProperties(product).filter(([label]) => !excludedLabels.includes(label)); elements.catalogDetail.innerHTML = `

${escapeHtml(t('inventory.catalog.details'))}

${escapeHtml(product.algofishClass)}
${equipmentVisual(product)}

${escapeHtml(product.name)}

${escapeHtml(product.brand)}${escapeHtml(product.range ?? product.model)}

${escapeHtml(t('inventory.catalog.characteristics'))}

${properties.slice(0, 13).map(([label, value]) => `
${escapeHtml(label)}
${escapeHtml(value)}
`).join('')}

${escapeHtml(t('inventory.catalog.techniques'))}

${catalogTechniqueTags(product)}

${escapeHtml(t('inventory.catalog.identification'))}

${escapeHtml(t('inventory.catalog.manufacturerReference'))}
${escapeHtml(product.sku)}
${escapeHtml(t('inventory.catalog.verifiedAt'))}
${escapeHtml(product.verifiedAt ?? t('inventory.catalog.candidate'))}
${officialSourceLink(product)}`; } function currentCatalogQueryKey() { return JSON.stringify({ search: elements.catalogSearch.value.trim().toLocaleLowerCase('fr'), sort: elements.catalogSort.value, mechanism: catalogFilters.mechanism, dragPosition: catalogFilters.dragPosition, modelYear: catalogFilters.modelYear, classCode: catalogFilters.classCode, techniques: [...catalogFilters.techniques].sort(), brands: [...catalogFilters.brands].sort(), }); } function revealNextCatalogBatch() { const filteredCount = filteredCatalogProducts(reelCatalogProducts()).length; if (catalogVisibleCount >= filteredCount) return; catalogVisibleCount = Math.min(catalogVisibleCount + CATALOG_BATCH_SIZE, filteredCount); renderCatalog(); } function renderCatalog() { const products = reelCatalogProducts(); renderCatalogFilters(products); const filtered = filteredCatalogProducts(products); const nextQueryKey = currentCatalogQueryKey(); if (nextQueryKey !== catalogQueryKey) { catalogQueryKey = nextQueryKey; catalogVisibleCount = CATALOG_BATCH_SIZE; } const visibleProducts = filtered.slice(0, catalogVisibleCount); elements.catalogResultCount.textContent = t('inventory.catalog.resultCount', { count: filtered.length, reelSuffix: filtered.length === 1 ? '' : 's', foundSuffix: getLocale() === 'fr' && filtered.length !== 1 ? 's' : '', }); if (!filtered.some((product) => product.id === selectedCatalogProductId)) { selectedCatalogProductId = filtered[0]?.id ?? null; } elements.catalog.innerHTML = filtered.length ? visibleProducts.map((product) => { const specifications = catalogCardSpecifications(product); const bookmarked = catalogBookmarks.has(product.id); return `
${equipmentVisual(product)}
${escapeHtml(product.algofishClass)}
${escapeHtml(product.brand)}

${escapeHtml(product.model)}

${escapeHtml(specifications.primary)}

${escapeHtml(t('inventory.catalog.capacityShort'))} ${escapeHtml(specifications.capacity)}

${catalogTechniqueTags(product)}
`; }).join('') : `
${escapeHtml(t('inventory.catalog.noResults'))}
`; const hasMore = visibleProducts.length < filtered.length; elements.catalogProgress.hidden = !hasMore; elements.catalogProgressLabel.textContent = hasMore ? t('inventory.catalog.progress', { visible: visibleProducts.length, total: filtered.length }) : ''; renderCatalogDetail(filtered.find((product) => product.id === selectedCatalogProductId) ?? null); } function renderViews() { document.body.dataset.inventoryView = view; document.querySelectorAll('[data-view-panel]').forEach((panel) => { panel.hidden = panel.dataset.viewPanel !== view; }); document.querySelectorAll('[data-view]').forEach((button) => { const active = button.dataset.view === view; button.classList.toggle('active', active); button.setAttribute('aria-selected', String(active)); button.tabIndex = active ? 0 : -1; }); } function render() { renderViews(); renderCatalog(); } function enableTabKeyboardNavigation(tabList) { tabList.addEventListener('keydown', (event) => { if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; const tabs = [...tabList.querySelectorAll('[role="tab"]')]; const currentIndex = tabs.indexOf(document.activeElement); if (currentIndex < 0) return; event.preventDefault(); const nextIndex = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (currentIndex + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length; tabs[nextIndex].focus(); tabs[nextIndex].click(); }); } document.querySelectorAll('[data-view]').forEach((button) => button.addEventListener('click', () => { view = button.dataset.view; renderViews(); })); document.querySelectorAll('[role="tablist"]').forEach(enableTabKeyboardNavigation); document.body.addEventListener('click', (event) => { const bookmarkButton = event.target.closest('[data-catalog-bookmark]'); const detailButton = event.target.closest('[data-catalog-detail], [data-catalog-product]'); if (bookmarkButton) { const productId = bookmarkButton.dataset.catalogBookmark; if (catalogBookmarks.has(productId)) catalogBookmarks.delete(productId); else catalogBookmarks.add(productId); saveCatalogBookmarks(); renderCatalog(); } else if (detailButton) { selectedCatalogProductId = detailButton.dataset.catalogDetail ?? detailButton.dataset.catalogProduct; renderCatalog(); } }); elements.catalogSearch.addEventListener('input', renderCatalog); elements.catalogSort.addEventListener('change', renderCatalog); elements.catalogLoadMore.addEventListener('click', revealNextCatalogBatch); elements.catalogModelYear.addEventListener('change', () => { catalogFilters.modelYear = elements.catalogModelYear.value; renderCatalog(); }); elements.catalogClassFilter.addEventListener('change', () => { catalogFilters.classCode = elements.catalogClassFilter.value; renderCatalog(); }); elements.catalogTypeStrip.addEventListener('click', (event) => { const button = event.target.closest('[data-catalog-type]'); if (!button) return; const type = button.dataset.catalogType; catalogFilters.mechanism = catalogFilters.mechanism === type && type !== 'all' ? 'all' : type; catalogFilters.classCode = 'all'; renderCatalog(); }); elements.catalogTypeFilters.addEventListener('change', (event) => { const input = event.target.closest('[data-catalog-type-filter]'); if (!input) return; catalogFilters.mechanism = input.dataset.catalogTypeFilter; catalogFilters.classCode = 'all'; renderCatalog(); }); elements.catalogDragPositionFilters.addEventListener('change', (event) => { const input = event.target.closest('[data-catalog-drag-position]'); if (!input) return; catalogFilters.dragPosition = input.dataset.catalogDragPosition; renderCatalog(); }); elements.catalogClassStrip.addEventListener('click', (event) => { const button = event.target.closest('[data-catalog-class]'); if (!button) return; catalogFilters.classCode = catalogFilters.classCode === button.dataset.catalogClass ? 'all' : button.dataset.catalogClass; renderCatalog(); }); elements.catalogTechniqueFilters.addEventListener('change', (event) => { const input = event.target.closest('[data-catalog-technique]'); if (!input) return; if (input.checked) catalogFilters.techniques.add(input.dataset.catalogTechnique); else catalogFilters.techniques.delete(input.dataset.catalogTechnique); renderCatalog(); }); elements.catalogBrandFilters.addEventListener('change', (event) => { const input = event.target.closest('[data-catalog-brand]'); if (!input) return; if (input.checked) catalogFilters.brands.add(input.dataset.catalogBrand); else catalogFilters.brands.delete(input.dataset.catalogBrand); renderCatalog(); }); elements.catalogReset.addEventListener('click', () => { catalogFilters.mechanism = 'all'; catalogFilters.dragPosition = 'all'; catalogFilters.modelYear = 'all'; catalogFilters.classCode = 'all'; catalogFilters.techniques.clear(); catalogFilters.brands.clear(); elements.catalogSearch.value = ''; elements.catalogSort.value = 'class'; renderCatalog(); }); if ('IntersectionObserver' in window) { const observer = new IntersectionObserver((entries) => { if (entries.some((entry) => entry.isIntersecting) && !elements.catalogProgress.hidden) { revealNextCatalogBatch(); } }, { rootMargin: '320px 0px' }); observer.observe(elements.catalogProgress); } window.addEventListener('algofish:localechange', render); window.addEventListener('algofish:accountdeleted', (event) => { if (event.detail?.accountId !== inventoryAccountId) return; inventoryAccountId = null; catalogBookmarks = new Set(loadCatalogBookmarks(null)); selectedCatalogProductId = null; renderCatalog(); }); window.addEventListener('algofish:accountchange', (event) => { const nextAccountId = event.detail?.session?.user?.id ?? null; if (nextAccountId === inventoryAccountId) return; inventoryAccountId = nextAccountId; catalogBookmarks = new Set(loadCatalogBookmarks(inventoryAccountId)); selectedCatalogProductId = null; renderCatalog(); }); render();