// Adapted from legacy singleProduct.vue's own fetch (GET /product/:id). // The new API has no single-product-detail endpoint (only GET // /catalog/products, the flat list) — apps/api is out of scope for this port, // so this fetches the full list and finds the matching product client-side. // Wasteful for a large catalog, but honest: no fabricated endpoint, no silent // behavior change. // // `initial` seeds the page with the ProductSummary the tapped card already // holds — the same shape, from the same endpoint — so the detail view renders // complete on its first frame instead of mounting blank and jumping when the // fetch lands. The fetch still runs, silently, and only replaces the product // if the server's copy actually differs (stock moved since the list loaded). // // The silent refresh waits until the opening morph (ProductMorph.vue, ≤420ms) // is over: the response is the whole catalogue, and parsing it — or swapping // the product and re-rendering — mid-animation drops frames. import { ref } from 'vue' import { api, type ProductSummary } from '../api/client' const SEEDED_REFRESH_DELAY_MS = 600 export function useProductDetail(id: string, initial?: ProductSummary | null) { const loading = ref(false) const flag = ref(Boolean(initial)) const notFound = ref(false) const productRef = ref(initial ?? null) const load = async () => { const seeded = productRef.value !== null if (seeded) await new Promise((resolve) => setTimeout(resolve, SEEDED_REFRESH_DELAY_MS)) else loading.value = true try { const products = await api.listProducts() const found = products.find((p) => p.id === id) ?? null if (seeded) { if (found && JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found } else { productRef.value = found notFound.value = !found } flag.value = true } catch (e) { console.log(e) } finally { loading.value = false } } return { loading, flag, notFound, productRef, load } }