// Public storefront — URL represents the BUSINESS, never the template.
// The selected template is resolved server-side; ?preview=<template-id> is
// honored only for an authenticated ADMIN OF THIS business (verified via the
// agent service), so customers can never trigger alternate presentations.

import { createServerClient } from '@/lib/supabase/server'
import { getStoreTemplate, resolvePaletteVars } from '@/lib/storefront/templates'
import { StorefrontRenderer } from '@/components/storefront/StorefrontRenderer'
import type { StoreBusinessData, StoreContent } from '@/components/storefront/sections'
import { AGENT_API_URL, PUBLIC_APP_URL } from '@/lib/api/config'

const API_BASE = AGENT_API_URL
const APP_URL = PUBLIC_APP_URL

async function isAdminOfBusiness(businessSlug: string): Promise<boolean> {
  try {
    const supabase = await createServerClient()
    const { data: { session } } = await supabase.auth.getSession()
    const token = session?.access_token
    if (!token) return false
    const res = await fetch(`${API_BASE}/store/settings`, {
      headers: { Authorization: `Bearer ${token}` },
      cache: 'no-store',
    })
    if (!res.ok) return false
    const body = await res.json()
    return body?.success === true && body?.data?.slug === businessSlug
  } catch {
    return false
  }
}

export default async function ShopPage({
  params,
  searchParams,
}: {
  params: Promise<{ businessSlug: string }>
  searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
  const { businessSlug } = await params
  const sp = await searchParams
  const previewParam = typeof sp.preview === 'string' ? sp.preview : undefined

  // Load initial data on server (a failed fetch degrades to the not-found view
  // instead of crashing server rendering).
  const [businessRes, productsRes] = await Promise.all([
    fetch(`${PUBLIC_APP_URL}/api/shop/business/${businessSlug}`)
      .then(r => r.json())
      .catch(() => ({ success: false })),
    fetch(`${PUBLIC_APP_URL}/api/shop/products/${businessSlug}`)
      .then(r => r.json())
      .catch(() => ({ success: false })),
  ])

  const business = businessRes.success ? businessRes.data : null
  const products = productsRes.success ? productsRes.data.products : []

  if (!business) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950">
        <div className="text-center">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-4">Shop Not Found</h1>
          <p className="text-gray-500 dark:text-gray-400">The storefront you're looking for doesn't exist.</p>
        </div>
      </div>
    )
  }

  const savedTemplateId: string = business.store_template || 'modern-retail'
  let templateId = savedTemplateId
  let previewMode = false

  if (previewParam && previewParam !== savedTemplateId) {
    const allowed = await isAdminOfBusiness(businessSlug)
    if (allowed) {
      const candidate = getStoreTemplate(previewParam)
      if (candidate.id === previewParam) {
        templateId = candidate.id
        previewMode = true
      }
    }
  }

  const template = getStoreTemplate(templateId)
  const content: StoreContent =
    business.storefront_config && typeof business.storefront_config === 'object'
      ? business.storefront_config
      : {}
  const paletteVars = resolvePaletteVars(template, business.brand_color, content.accent_color)
  const businessData: StoreBusinessData = {
    slug: business.slug,
    name: business.name,
    description: business.description,
    phone: business.phone,
    email: business.email,
    logo_url: business.logo_url,
    hero_title: business.hero_title,
    hero_subtitle: business.hero_subtitle,
    brand_color: business.brand_color,
    address: business.address,
    whatsapp: business.whatsapp,
    website_url: business.website_url,
    maps_url: business.maps_url,
  }

  // Structured data (JSON-LD) — only for the published live store, never for
  // template previews or unpublished storefronts.
  const showStructuredData = business.store_published && !previewMode
  const jsonLd = showStructuredData
    ? {
        '@context': 'https://schema.org',
        '@graph': [
          {
            '@type': 'Organization',
            '@id': `${APP_URL}/shop/${business.slug}#organization`,
            name: business.name,
            url: `${APP_URL}/shop/${business.slug}`,
            ...(business.logo_url ? { logo: business.logo_url } : {}),
            ...(business.description ? { description: business.description } : {}),
            ...(business.email ? { email: business.email } : {}),
            ...(business.phone ? { telephone: business.phone } : {}),
            ...(business.address ? { address: business.address } : {}),
          },
          {
            '@type': 'WebSite',
            '@id': `${APP_URL}/shop/${business.slug}#website`,
            url: `${APP_URL}/shop/${business.slug}`,
            name: business.name,
            inLanguage: 'en',
            publisher: { '@id': `${APP_URL}/shop/${business.slug}#organization` },
          },
        ],
      }
    : null

  return (
    <div style={paletteVars as React.CSSProperties} className="min-h-screen bg-[var(--store-background)] text-[var(--store-text)]">
      {jsonLd && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
          }}
        />
      )}
      {previewMode && (
        <div className="mx-auto mt-4 w-full max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="px-4 py-2 rounded-lg text-sm font-medium text-white bg-slate-900/90 text-center">
            Template preview — {template.name}. This is how your store will look.{' '}
            <a href={`/shop/${businessSlug}`} className="underline">Back to live store</a>
          </div>
        </div>
      )}
      {!business.store_published && !previewMode && (
        <div className="mx-auto mt-4 w-full max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="px-4 py-2 rounded-lg text-sm text-center bg-amber-100 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200">
            This store is not published yet.
          </div>
        </div>
      )}
      <StorefrontRenderer
        template={template}
        business={businessData}
        content={content}
        products={products}
        currency={business.currency || 'USD'}
        previewMode={previewMode}
      />
    </div>
  )
}
