(function () { 'use strict'; const normalize = value => String(value || '').toLocaleLowerCase('ko-KR').replace(/\s+/g, ''); const searchable = (store, query) => !normalize(query) || normalize(store.name + ' ' + store.address).includes(normalize(query)); const mapAddress = address => { const clean = String(address || '').replace(/^\s*\(\d{5}\)\s*/, '').replace(/\([^)]*\)/g, ' ').replace(/\s+/g, ' ').trim(); return clean.match(/^(.+?(?:대로|로|길)\s*\d+(?:-\d+)?)(?=\s|$)/)?.[1] || clean; }; const sameBusinessName = partner => { const name = String(partner?.partnerName ?? '').trim(), company = String(partner?.companyName ?? '').trim(); return !!name && !!company && name === company; }; const publicStores = (partners, config, policy) => partners .filter(p => p.contractStatus === 'ACTIVE' && sameBusinessName(p) && policy.capabilities(p, config).storeDirectory) .map(p => { const profile = config.partnerProfiles?.[String(p.partnerNo)] || {}; const firstAddress = String(profile.visitingAddress || p.officeAddressLabel || '').split(//i)[0]; const parsed = new DOMParser().parseFromString(firstAddress, 'text/html'); return { id: Number(p.partnerNo), name: p.partnerName, address: parsed.body.textContent.trim(), phone: p.phoneNo || '', geocodeAddress: profile.mapAddress || mapAddress(parsed.body.textContent), lat: Number.isFinite(profile.latitude) && Math.abs(profile.latitude) <= 90 ? profile.latitude : null, lng: Number.isFinite(profile.longitude) && Math.abs(profile.longitude) <= 180 ? profile.longitude : null, image: profile.imageUrl || '', }; }); function element(tag, className, text) { const el = document.createElement(tag); if (className) el.className = className; if (text !== undefined) el.textContent = text; return el; } function storeUrl(id) { return '/cyclemoa-list.html?' + new URLSearchParams({ mode: 'seller', partnerNo: id, cmrev: '20261115-category-nav-v2' }); } async function getPartners() { return window.CMPartnerDirectory.load(); } let sdkPromise; function loadMapSdk(key) { if (!key) return Promise.reject(Error('Map configuration pending')); if (sdkPromise) return sdkPromise; sdkPromise = new Promise((resolve, reject) => { if (window.kakao?.maps?.services && window.kakao.maps.MarkerClusterer) return resolve(window.kakao.maps); const script = document.createElement('script'); const timeout = setTimeout(() => { script.remove(); reject(Error('Map loading timed out')); }, 15000); // Kakao reads this list directly from the script URL without decoding commas. script.src = 'https://dapi.kakao.com/v2/maps/sdk.js?' + new URLSearchParams({ appkey: key, autoload: 'false' }) + '&libraries=services,clusterer'; script.onload = () => { if (!window.kakao?.maps?.load) { clearTimeout(timeout); reject(Error('Map authorization unavailable')); return; } window.kakao.maps.load(() => { clearTimeout(timeout); resolve(window.kakao.maps); }); }; script.onerror = () => { clearTimeout(timeout); script.remove(); reject(Error('Map loading unavailable')); }; document.head.append(script); }).catch(error => { sdkPromise = null; throw error; }); return sdkPromise; } async function init(host, config) { if (host.dataset.storeFinderReady) return; host.dataset.storeFinderReady = 'true'; host.className = 'cm-store-finder'; host.replaceChildren(); const state = { stores: [], matches: [], map: null, sdk: null, markers: new Map(), selected: null, status: 'loading' }; window.CMStoreFinder.state = state; const searchForm = element('form', 'cm-store-search'); searchForm.setAttribute('role', 'search'); const label = element('label', 'cm-store-search-label', '매장명 또는 지역 검색'); label.htmlFor = 'cm-store-query'; const input = element('input', 'cm-store-query'); input.id = 'cm-store-query'; input.type = 'search'; input.placeholder = '매장명 또는 지역을 입력하세요'; input.autocomplete = 'off'; const submit = element('button', 'cm-store-search-button', '검색'); submit.type = 'submit'; searchForm.append(label, input, submit); const toolbar = element('div', 'cm-store-toolbar'); const count = element('p', 'cm-store-count', '매장 정보를 불러오는 중입니다.'); count.setAttribute('role', 'status'); const views = element('div', 'cm-store-view-options'); views.setAttribute('aria-label', '매장 보기 방식'); const both = element('button', '', '지도'), listView = element('button', '', '목록'); both.type = listView.type = 'button'; both.setAttribute('aria-pressed', 'true'); listView.setAttribute('aria-pressed', 'false'); views.append(both, listView); toolbar.append(count, views); const layout = element('div', 'cm-store-layout'); const list = element('div', 'cm-store-results'); list.setAttribute('aria-label', '입점 매장 목록'); const mapPanel = element('section', 'cm-store-map-panel'); mapPanel.setAttribute('aria-label', '입점 매장 지도'); const canvas = element('div', 'cm-store-map'); canvas.id = 'cm-store-map'; const mapMessage = element('div', 'cm-store-map-message', '지도를 불러오는 중입니다.'); mapMessage.setAttribute('role', 'status'); const reset = element('button', 'cm-store-map-reset', '전국 보기'); reset.type = 'button'; reset.hidden = true; mapPanel.append(canvas, mapMessage, reset); layout.append(list, mapPanel); host.append(searchForm, toolbar, layout); let clusterer, infoWindow, queryTimer; function koreaBounds() { const m = state.sdk; return new m.LatLngBounds(new m.LatLng(33.05, 125.05), new m.LatLng(38.35, 129.65)); } function nationwide() { if (state.map) { infoWindow?.close(); state.map.setBounds(koreaBounds(), 0, 0, 0, 0); } } function fitMatches() { if (!state.map) return; const places = state.matches.filter(s => state.markers.has(s.id)); if (!normalize(input.value) || !places.length) { nationwide(); return; } if (places.length === 1) { state.map.setLevel(5); state.map.panTo(new state.sdk.LatLng(places[0].lat, places[0].lng)); return; } const bounds = new state.sdk.LatLngBounds(); places.forEach(s => bounds.extend(new state.sdk.LatLng(s.lat, s.lng))); state.map.setBounds(bounds); } function selectStore(store, fromMap = false) { state.selected = store.id; list.querySelectorAll('.cm-store-card-row').forEach(row => row.classList.toggle('is-selected', Number(row.dataset.storeId) === store.id)); if (fromMap) list.querySelector('[data-store-id="' + store.id + '"]')?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); const marker = state.markers.get(store.id); if (!state.map || !marker) return; clusterer.clear(); clusterer.addMarkers([marker]); if (host.dataset.view === 'list') showView('map'); state.map.setLevel(4); state.map.panTo(marker.getPosition()); const box = element('div', 'cm-store-map-card'), name = element('strong', '', store.name), address = element('p', '', store.address); const link = element('a', '', '매장 상품 보기'); link.href = storeUrl(store.id); box.append(name, address, link); infoWindow.setContent(box); infoWindow.open(state.map, marker); } function renderList() { list.replaceChildren(); count.textContent = normalize(input.value) ? '검색 결과 ' + state.matches.length + '개 매장' : '입점 매장 ' + state.matches.length + '곳'; if (!state.matches.length) { list.append(element('p', 'cm-store-empty', normalize(input.value) ? '검색된 매장이 없습니다. 매장명이나 지역을 다시 확인해 주세요.' : '새로운 입점 매장을 준비하고 있습니다.')); return; } for (const store of state.matches) { const row = element('article', 'cm-store-card-row'); row.dataset.storeId = store.id; const title = element('button', 'cm-store-focus', store.name); title.type = 'button'; title.onclick = () => selectStore(store); const address = element('p', 'cm-store-address', store.address || '방문 주소를 확인하고 있습니다.'); const actions = element('div', 'cm-store-card-actions'), shop = element('a', 'cm-store-shop-link', '매장 상품 보기'); shop.href = storeUrl(store.id); actions.append(shop); if (store.phone) { const phone = element('a', 'cm-store-phone', store.phone); phone.href = 'tel:' + store.phone.replace(/[^+\d]/g, ''); actions.append(phone); } row.append(title, address, actions); list.append(row); } } function filter(zoom = true) { state.selected = null; state.matches = state.stores.filter(s => searchable(s, input.value)); infoWindow?.close(); renderList(); if (clusterer) { clusterer.clear(); clusterer.addMarkers(state.matches.map(s => state.markers.get(s.id)).filter(Boolean)); } if (zoom) fitMatches(); } function showView(view) { host.dataset.view = view; both.setAttribute('aria-pressed', String(view === 'map')); listView.setAttribute('aria-pressed', String(view === 'list')); if (view === 'map' && state.map) requestAnimationFrame(() => { state.map.relayout(); fitMatches(); }); } both.onclick = () => showView('map'); listView.onclick = () => showView('list'); searchForm.onsubmit = event => { event.preventDefault(); clearTimeout(queryTimer); filter(); }; input.addEventListener('input', () => { clearTimeout(queryTimer); queryTimer = setTimeout(filter, 150); }); reset.onclick = () => { input.value = ''; filter(); }; host.dataset.view = 'map'; async function loadStores() { const partners = await getPartners(); state.stores = publicStores(partners, config, window.CMPartnerPolicy); filter(false); } const [storesResult, sdkResult] = await Promise.allSettled([loadStores(), loadMapSdk(config.kakaoMap?.javascriptKey)]); if (storesResult.status === 'rejected') { count.textContent = '매장 정보를 불러오지 못했습니다.'; list.replaceChildren(); const retry = element('button', 'cm-store-retry', '다시 불러오기'); retry.type = 'button'; retry.onclick = () => location.reload(); list.append(retry); } if (sdkResult.status === 'rejected') { state.status = config.kakaoMap?.javascriptKey ? 'map-error' : 'map-setup-pending'; mapMessage.textContent = config.kakaoMap?.javascriptKey ? '지도를 불러오지 못했습니다. 매장 목록에서 주소를 확인해 주세요.' : '매장 지도를 준비하고 있습니다. 목록에서 매장 정보를 확인해 주세요.'; return; } const m = state.sdk = sdkResult.value; state.map = new m.Map(canvas, { center: new m.LatLng(36.2, 127.8), level: 13 }); state.map.addControl(new m.ZoomControl(), m.ControlPosition.RIGHT); infoWindow = new m.InfoWindow({ removable: true, zIndex: 5 }); clusterer = new m.MarkerClusterer({ map: state.map, averageCenter: true, minLevel: 8, gridSize: 60, styles: [{ width: '44px', height: '44px', background: '#171717', color: '#fff', textAlign: 'center', lineHeight: '44px', fontWeight: '700', borderRadius: '50%' }] }); state.clusterer = clusterer; const geocoder = new m.services.Geocoder(); const locate = store => new Promise(resolve => { if (store.lat !== null && store.lng !== null) return resolve(); if (!store.geocodeAddress) return resolve(); let settled = false; const timer = setTimeout(() => { settled = true; resolve(); }, 8000); geocoder.addressSearch(store.geocodeAddress, (rows, status) => { if (settled) return; clearTimeout(timer); if (status === m.services.Status.OK && rows.length) { store.lat = Number(rows[0].y); store.lng = Number(rows[0].x); } resolve(); }); }); // Resolve only approved, public stores; never mix in the map provider's place-search results. const queue = [...state.stores]; await Promise.all(Array.from({ length: Math.min(4, queue.length) }, async () => { while (queue.length) await locate(queue.shift()); })); for (const store of state.stores) { if (store.lat === null || store.lng === null || !Number.isFinite(store.lat) || !Number.isFinite(store.lng)) continue; const marker = new m.Marker({ position: new m.LatLng(store.lat, store.lng), title: store.name }); state.markers.set(store.id, marker); m.event.addListener(marker, 'click', () => selectStore(store, true)); } state.status = 'ready'; mapMessage.hidden = true; reset.hidden = false; filter(); let resizeTimer; const resize = new ResizeObserver(() => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { state.map.relayout(); if (!state.selected) fitMatches(); }, 120); }); resize.observe(canvas); } window.CMStoreFinder = { init, searchable, publicStores, mapAddress }; })();