import { computed, nextTick, ref, watch } from 'vue' import type { Price } from '@/models/home' import { fetchZaanboxPriceHistory, type LandingHistoryRange, type LandingHistorySample, } from '@/api/zaarboxPriceHistory' import useAxios from '@/utils/useAxios' import { applyLastPricePayload } from '@/utils/price' import { getPriceDisplayState, hasLivePriceQuote, isStoreClosed } from '@/utils/storeHours' import { formatSignedPercentChange, usePriceWithoutType } from '@/utils/usePrice' import { applyChartPriceOffset, resolvePriceOffsetRatio } from '@/utils/productPrice' import { getProductsCatalog, getProductsCatalogRef } from '@/composables/useProductsCatalog' import type { Product } from '@/models/products' import { CHART_METAL_MARKUP_RATIO, type ChartMetalType, usePriceChart, } from './usePriceChart' const LIVE_CHART_WIDTH = 560 const LIVE_CHART_HEIGHT = 160 const CHART_PAD = 10 const MAX_CHART_POINTS = 48 const PRICE_POLL_MS = 30_000 type ChartHoverState = { xPercent: number yPercent: number priceLabel: string timeLabel: string } export const LIVE_CHART_RANGE_OPTIONS: Array<{ value: LandingHistoryRange shortLabel: string label: string }> = [ { value: 'DAILY', shortLabel: '۲۴ ساعت', label: 'نمودار ۲۴ ساعت گذشته' }, { value: 'WEEKLY', shortLabel: 'هفته', label: 'نمودار هفته گذشته' }, { value: 'MONTHLY', shortLabel: 'ماه', label: 'نمودار ماه گذشته' }, ] const activeProductId = ref(null) const catalogProducts = getProductsCatalogRef() const liveChartRange = ref('DAILY') const dailyRawPoints = ref([]) const liveRangeRawPoints = ref([]) const liveChartLoading = ref(false) const liveChartHover = ref(null) const liveChartDrawn = ref(false) const liveChartPlotEl = ref(null) let pricePollTimer: ReturnType | undefined let liveChartObserver: IntersectionObserver | undefined let initialized = false let initPromise: Promise | null = null function isListedChartProduct(product: Product) { return !product.deleted_at } const chartProductTabs = computed(() => catalogProducts.value.filter(isListedChartProduct)) const selectedChartProduct = computed( () => chartProductTabs.value.find((product) => product.id === activeProductId.value) ?? null, ) function metalFromProductTitle(title: string): ChartMetalType { if (title.includes('شمش')) return 'shamsh' if (title.includes('مفتول')) return 'maftol' return 'katod' } watch(chartProductTabs, (tabs) => { if (!tabs.length) { activeProductId.value = null return } if (!tabs.some((product) => product.id === activeProductId.value)) { activeProductId.value = tabs[0].id } }) function markupPriceForProduct(basePrice: number, product: Product | null) { if (!product || !basePrice) return basePrice if (resolvePriceOffsetRatio(product.price_offset_percent)) { return applyChartPriceOffset(basePrice, product.price_offset_percent) } const metalRatio = CHART_METAL_MARKUP_RATIO[metalFromProductTitle(product.title)] if (!metalRatio) return basePrice return Math.round(basePrice + basePrice * metalRatio) } function applyMarkupToSeries( points: LandingHistorySample[], product: Product | null, ): LandingHistorySample[] { return points .map((point) => ({ timeMs: point.timeMs, price: markupPriceForProduct(point.price, product), })) .filter((point) => Number.isFinite(point.price) && point.price > 0) } function downsampleSamples(points: LandingHistorySample[], maxPoints: number) { if (points.length <= maxPoints) return points const result: LandingHistorySample[] = [] const lastIndex = points.length - 1 for (let i = 0; i < maxPoints; i += 1) { const index = Math.round((i / (maxPoints - 1)) * lastIndex) result.push(points[index]) } return result } function formatChartTimeLabel(timeMs: number) { try { return new Intl.DateTimeFormat('fa-IR', { timeZone: 'Asia/Tehran', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', }).format(new Date(timeMs)) } catch { return new Date(timeMs).toLocaleString('fa-IR') } } type ChartPlotSample = { x: number; y: number; price: number; timeMs: number } function buildLandingChartPaths( points: LandingHistorySample[], width = LIVE_CHART_WIDTH, height = LIVE_CHART_HEIGHT, ) { const empty = { hasData: false, linePath: '', areaPath: '', lastX: 0, lastY: height / 2, samples: [] as ChartPlotSample[], } if (points.length < 2) return empty const sampled = downsampleSamples(points, MAX_CHART_POINTS) const prices = sampled.map((point) => point.price) const min = Math.min(...prices) const max = Math.max(...prices) const range = max - min || 1 const usableHeight = height - CHART_PAD * 2 const plotSamples = sampled.map((point, index) => { const x = (index / (sampled.length - 1)) * width const y = CHART_PAD + (1 - (point.price - min) / range) * usableHeight return { x, y, price: point.price, timeMs: point.timeMs } }) const linePath = plotSamples .map((point, index) => `${index === 0 ? 'M' : 'L'}${point.x.toFixed(2)} ${point.y.toFixed(2)}`) .join(' ') const last = plotSamples[plotSamples.length - 1] const areaPath = `${linePath} L${width} ${height} L0 ${height} Z` return { hasData: true, linePath, areaPath, lastX: last.x, lastY: last.y, samples: plotSamples, } } const chartPoints = computed(() => applyMarkupToSeries(dailyRawPoints.value, selectedChartProduct.value), ) const chartValues = computed(() => chartPoints.value.map((point) => point.price)) const liveSectionChartPoints = computed(() => { const raw = liveChartRange.value === 'DAILY' && liveRangeRawPoints.value.length < 2 ? dailyRawPoints.value : liveRangeRawPoints.value return applyMarkupToSeries(raw, selectedChartProduct.value) }) const motionPoints = ref(null) let chartMotionFrame = 0 function prefersReducedMotion() { return typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches } function sampleSeriesAt(points: LandingHistorySample[], index: number, count: number) { if (points.length <= 1) return points[0] const ratio = count <= 1 ? 0 : index / (count - 1) const position = ratio * (points.length - 1) const start = Math.floor(position) const blend = position - start const from = points[start] const to = points[Math.min(start + 1, points.length - 1)] return from.price + (to.price - from.price) * blend } function easeOutQuart(progress: number) { return 1 - (1 - progress) ** 4 } function animateChartSeries(next: LandingHistorySample[]) { cancelAnimationFrame(chartMotionFrame) const from = motionPoints.value if (!from || from.length < 2 || next.length < 2 || prefersReducedMotion()) { motionPoints.value = next return } const startedAt = performance.now() const duration = 340 const tick = (now: number) => { const progress = Math.min(1, (now - startedAt) / duration) const eased = easeOutQuart(progress) motionPoints.value = next.map((point, index) => { const origin = sampleSeriesAt(from, index, next.length) return { timeMs: point.timeMs, price: origin + (point.price - origin) * eased, } }) if (progress < 1) chartMotionFrame = requestAnimationFrame(tick) } chartMotionFrame = requestAnimationFrame(tick) } watch(activeProductId, () => { liveChartHover.value = null const next = liveSectionChartPoints.value if (next.length >= 2 && motionPoints.value?.length) { animateChartSeries(next) return } motionPoints.value = next.length ? next : null }) watch(liveSectionChartPoints, (next, prev) => { if (!prev?.length) { motionPoints.value = next return } const prevLast = prev[prev.length - 1] const nextLast = next[next.length - 1] const unchanged = prev.length === next.length && prev[0]?.timeMs === next[0]?.timeMs && prevLast?.timeMs === nextLast?.timeMs && prevLast?.price === nextLast?.price if (unchanged) return animateChartSeries(next) }) const displayedChartPoints = computed(() => motionPoints.value ?? liveSectionChartPoints.value) const liveSectionChart = computed(() => buildLandingChartPaths(displayedChartPoints.value)) const baseBuyPrice = computed(() => { const lastDaily = dailyRawPoints.value[dailyRawPoints.value.length - 1]?.price if (Number.isFinite(lastDaily) && lastDaily > 0) return lastDaily const lastLive = liveRangeRawPoints.value[liveRangeRawPoints.value.length - 1]?.price if (Number.isFinite(lastLive) && lastLive > 0) return lastLive return 0 }) const liveUnitPrice = computed(() => markupPriceForProduct(baseBuyPrice.value, selectedChartProduct.value), ) const formattedLivePrice = computed(() => { if (!liveUnitPrice.value) return '—' return usePriceWithoutType(liveUnitPrice.value) }) const liveMarketState = computed(() => { if (isStoreClosed()) return 'closed' as const const state = getPriceDisplayState() if (state === 'open') return 'open' as const if (baseBuyPrice.value > 0) return 'open' as const if (!hasLivePriceQuote()) return 'no_quote' as const return 'closed' as const }) const liveMarketStatusLabel = computed(() => { if (liveMarketState.value === 'open') return 'بازار باز است' if (liveMarketState.value === 'no_quote') return 'در انتظار قیمت' return 'بازار بسته است' }) const liveMarketStatusIcon = computed(() => { if (liveMarketState.value === 'open') return 'vuesax-linear:tick-circle' if (liveMarketState.value === 'no_quote') return 'vuesax-linear:info-circle' return 'vuesax-linear:lock' }) const liveMarketStatusColor = computed(() => { if (liveMarketState.value === 'open') return '#16a34a' if (liveMarketState.value === 'no_quote') return '#94a3b8' return '#dc2626' }) const liveUpdateLabel = computed(() => { if (liveMarketState.value === 'open') return 'به‌روزرسانی لحظه‌ای' if (liveMarketState.value === 'closed') return 'خارج از ساعت معامله' return 'قیمت دریافت نشده' }) const liveProductLabel = computed(() => selectedChartProduct.value?.title ?? '') const liveChartRangeLabel = computed( () => LIVE_CHART_RANGE_OPTIONS.find((option) => option.value === liveChartRange.value)?.label ?? 'نمودار ۲۴ ساعت گذشته', ) const dayChangePercent = computed(() => { const values = chartValues.value if (values.length >= 2 && values[0] > 0) { return ((values[values.length - 1] - values[0]) / values[0]) * 100 } return 0 }) const dayChangeAmountLabel = computed(() => { const values = chartValues.value if (values.length < 2) return '' const delta = Math.round(values[values.length - 1] - values[0]) if (!delta) return '' const abs = usePriceWithoutType(Math.abs(delta)) return `${delta > 0 ? '+' : '−'}${abs} ریال` }) function isPointRecordedToday(timeMs: number): boolean { try { const tehranFormatter = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Tehran', year: 'numeric', month: '2-digit', day: '2-digit', }) return tehranFormatter.format(new Date(timeMs)) === tehranFormatter.format(new Date()) } catch { return Date.now() - timeMs < 24 * 60 * 60 * 1000 } } const todayChartPoints = computed(() => { const points = chartPoints.value const todayOnly = points.filter((p) => isPointRecordedToday(p.timeMs)) return todayOnly.length >= 2 ? todayOnly : points }) const todayChartValues = computed(() => todayChartPoints.value.map((p) => p.price).filter((p) => Number.isFinite(p) && p > 0), ) const dayRange = computed(() => { const values = todayChartValues.value const current = Number.isFinite(liveUnitPrice.value) && liveUnitPrice.value > 0 ? liveUnitPrice.value : 0 const allValues = current > 0 ? [...values, current] : values if (!allValues.length) { return { high: current, low: current } } return { high: Math.max(...allValues), low: Math.min(...allValues), } }) const dayHighPrice = computed(() => dayRange.value.high) const dayLowPrice = computed(() => dayRange.value.low) function resolveHoverFromEvent( event: PointerEvent, chart: { samples: ChartPlotSample[]; hasData: boolean }, width: number, height: number, ): ChartHoverState | null { if (!chart.hasData || chart.samples.length < 2) return null const target = event.currentTarget as HTMLElement | null if (!target) return null const rect = target.getBoundingClientRect() if (rect.width <= 0 || rect.height <= 0) return null const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)) const index = Math.round(ratio * (chart.samples.length - 1)) const sample = chart.samples[index] if (!sample) return null return { xPercent: (sample.x / width) * 100, yPercent: (sample.y / height) * 100, priceLabel: `${usePriceWithoutType(sample.price)} ریال`, timeLabel: formatChartTimeLabel(sample.timeMs), } } async function loadLandingMarketStatus() { try { const data = await useAxios.get('/api/price/last', { meta: { errorMessage: 'none' }, }) if (data) applyLastPricePayload(data) } catch { /* optional */ } } async function loadDailyHistory() { try { const series = await fetchZaanboxPriceHistory('DAILY') if (series.length >= 2) { dailyRawPoints.value = series if (liveChartRange.value === 'DAILY') liveRangeRawPoints.value = series } } catch (error) { console.error('Home live chart daily history failed:', error) } } async function loadLiveRangeHistory(range: LandingHistoryRange) { liveChartLoading.value = true try { const series = await fetchZaanboxPriceHistory(range) liveRangeRawPoints.value = series.length >= 2 ? series : [] if (range === 'DAILY' && series.length >= 2) dailyRawPoints.value = series } catch (error) { console.error(`Home live chart ${range} history failed:`, error) liveRangeRawPoints.value = [] } finally { liveChartLoading.value = false } } async function loadLandingChart() { liveChartLoading.value = true try { await loadDailyHistory() if (liveChartRange.value !== 'DAILY') { await loadLiveRangeHistory(liveChartRange.value) } else if (liveRangeRawPoints.value.length < 2) { liveRangeRawPoints.value = dailyRawPoints.value } } finally { liveChartLoading.value = false } } function setupLiveChartDraw() { if (liveChartDrawn.value || !liveChartPlotEl.value) return if (typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { liveChartDrawn.value = true return } if (typeof IntersectionObserver === 'undefined') { liveChartDrawn.value = true return } liveChartObserver?.disconnect() const observer = new IntersectionObserver( (entries) => { if (entries.some((entry) => entry.isIntersecting)) { liveChartDrawn.value = true observer.disconnect() liveChartObserver = undefined } }, { threshold: 0.35 }, ) liveChartObserver = observer observer.observe(liveChartPlotEl.value) } watch( selectedChartProduct, (product) => { if (product) { const { setChartMetal } = usePriceChart() setChartMetal(metalFromProductTitle(product.title)) } }, { immediate: true }, ) function setLiveProduct(productId: number) { const targetProduct = chartProductTabs.value.find((product) => product.id === productId) if (!targetProduct) return activeProductId.value = productId liveChartHover.value = null const { setChartMetal } = usePriceChart() setChartMetal(metalFromProductTitle(targetProduct.title)) } async function setLiveChartRange(range: LandingHistoryRange) { if (liveChartRange.value === range && liveRangeRawPoints.value.length >= 2) return liveChartRange.value = range liveChartHover.value = null await loadLiveRangeHistory(range) } function onLiveChartPointerMove(event: PointerEvent) { liveChartHover.value = resolveHoverFromEvent( event, liveSectionChart.value, LIVE_CHART_WIDTH, LIVE_CHART_HEIGHT, ) } function onLiveChartPointerLeave() { liveChartHover.value = null } watch( () => liveSectionChart.value.hasData, async (hasData) => { if (!hasData || liveChartDrawn.value) return await nextTick() setupLiveChartDraw() }, ) export async function initHomeLandingLiveChart() { if (initPromise) return initPromise initPromise = (async () => { if (initialized) return await getProductsCatalog() const firstProduct = chartProductTabs.value[0] if (firstProduct) setLiveProduct(firstProduct.id) await loadLandingMarketStatus() await loadLandingChart() if (!pricePollTimer) { pricePollTimer = setInterval(() => { void loadLandingMarketStatus() void loadDailyHistory() if (liveChartRange.value !== 'DAILY') void loadLiveRangeHistory(liveChartRange.value) }, PRICE_POLL_MS) } initialized = true await nextTick() setupLiveChartDraw() })() return initPromise } export function resetHomeLandingLiveChart() { initialized = false initPromise = null if (pricePollTimer) { clearInterval(pricePollTimer) pricePollTimer = undefined } liveChartObserver?.disconnect() liveChartObserver = undefined cancelAnimationFrame(chartMotionFrame) motionPoints.value = null dailyRawPoints.value = [] liveRangeRawPoints.value = [] liveChartHover.value = null liveChartDrawn.value = false activeProductId.value = null liveChartRange.value = 'DAILY' } export function bindLiveChartDraw() { void nextTick(() => setupLiveChartDraw()) } export function useLandingLiveChart() { return { activeProductId, chartProductTabs, liveChartRange, liveChartRangeOptions: LIVE_CHART_RANGE_OPTIONS, liveChartLoading, liveChartHover, liveChartDrawn, liveChartPlotEl, liveSectionChart, formattedLivePrice, liveUnitPrice, dayHighPrice, dayLowPrice, liveProductLabel, liveChartRangeLabel, liveMarketState, liveMarketStatusLabel, liveMarketStatusIcon, liveMarketStatusColor, liveUpdateLabel, dayChangePercent, dayChangeAmountLabel, formatSignedPercentChange, setLiveProduct, setLiveChartRange, onLiveChartPointerMove, onLiveChartPointerLeave, initHomeLandingLiveChart, } }