export type PageType = | "homepage" | "category" | "product" | "search" | "cart" | "other"; export interface PageContext { page_link: string; page_type: PageType; h1: string; } function detectPageType(): PageType { if (typeof window === "undefined" || typeof document === "undefined") { return "other"; } const url = window.location.href.toLowerCase(); const path = window.location.pathname.toLowerCase(); const bodyClasses = document.body.className.toLowerCase(); // Homepage detection if ( path === "/" || path === "" || bodyClasses.includes("home") || bodyClasses.includes("front-page") ) { return "homepage"; } // Cart detection if ( path.includes("/cart") || path.includes("/basket") || bodyClasses.includes("woocommerce-cart") ) { return "cart"; } // Checkout detection - map to cart since API doesn't have checkout if ( path.includes("/checkout") || bodyClasses.includes("woocommerce-checkout") ) { return "cart"; } // Search detection if ( path.includes("/search") || url.includes("?s=") || url.includes("?q=") || bodyClasses.includes("search-results") || bodyClasses.includes("search") ) { return "search"; } // Product page detection if ( path.includes("/product/") || path.includes("/products/") || bodyClasses.includes("single-product") || bodyClasses.includes("product-template") || document.querySelector("[data-product-id]") || document.querySelector(".product-single") || document.querySelector("form.cart") ) { return "product"; } // Category detection if ( path.includes("/category/") || path.includes("/collection/") || path.includes("/collections/") || path.includes("/product-category/") || path.includes("/shop/") || bodyClasses.includes("archive") || bodyClasses.includes("tax-product_cat") || bodyClasses.includes("post-type-archive-product") || bodyClasses.includes("collection-template") ) { return "category"; } return "other"; } function getPageH1(): string { if (typeof document === "undefined") { return ""; } const h1 = document.querySelector("h1"); return h1?.textContent?.trim() || document.title || ""; } export function getPageContext(): PageContext { return { page_link: typeof window !== "undefined" ? window.location.href : "", page_type: detectPageType(), h1: getPageH1(), }; } /** * Builds a context string to prepend to user messages * This provides the AI with page context for better responses * Format is LLM-friendly with clear markers and only includes available data */ export function buildPageContextString(): string { const context = getPageContext(); // Build context parts, only including fields that have meaningful values const parts: string[] = []; if (context.page_type && context.page_type !== "other") { parts.push(`page_type: ${context.page_type}`); } if (context.h1) { parts.push(`page_title: ${context.h1}`); } if (context.page_link) { parts.push(`url: ${context.page_link}`); } // If no meaningful context, return empty string if (parts.length === 0) { return ""; } return `[USER_PAGE_CONTEXT: ${parts.join(" | ")}]\n\n`; }