// StorefrontRenderer — the ONE engine behind all 20 templates.
// Maps a template's section order to shared components; presentation is
// driven entirely by the template's tokens + the business's own brand data.
// Navigation is derived from what this business ACTUALLY has — never dead links.

import Link from 'next/link'
import { StoreTemplate } from '@/lib/storefront/templates'
import {
  HeroSection, CategoryShowcase, PromoBanner, StatsStrip, EmptyCatalog,
  StoreBusinessData, StoreContent, PublicProductLite,
  headingClass, bodyClass, animClass, ProductGridClasses, RADIUS_CLASS,
  sectionSpacing, PreviewNote,
} from './sections'
import {
  AboutStory, StorySection, TestimonialsSection, FaqSection,
  TrustSignals, ContactSection, FooterPro,
} from './sections2'
import { StoreProductCard } from './StoreProductCard'
import { StorefrontNav, NavItem } from './StorefrontNav'

const ANIM_ROOT: Record<StoreTemplate['tokens']['animation'], string> = {
  subtle: 'store-anim-subtle',
  'slow-reveal': 'store-anim-slow-reveal',
  snappy: 'store-anim-snappy',
  cinematic: 'store-anim-cinematic',
  editorial: 'store-anim-editorial',
  none: '',
}

function deriveNavItems(
  template: StoreTemplate,
  business: StoreBusinessData,
  content: StoreContent,
  hasProducts: boolean,
  hasCategories: boolean,
): NavItem[] {
  const labels = template.labels || {}
  const items: NavItem[] = [{ label: 'Home', href: '#' }]
  if (hasProducts) items.push({ label: labels.products || 'Products', href: '#products' })
  if (hasCategories) items.push({ label: labels.categories || 'Categories', href: '#categories' })
  if ((business.description || '').trim()) items.push({ label: 'About', href: '#about' })
  if ((content.story_body || '').trim() || (content.story_title || '').trim()) {
    items.push({ label: 'Our Story', href: '#story' })
  }
  const hasContact = Boolean(business.phone || business.email || business.whatsapp || business.address || content.opening_hours)
  if (hasContact) items.push({ label: 'Contact', href: '#contact' })
  return items.slice(0, 6)
}

export function StorefrontRenderer({
  template, business, content, products, currency, previewMode = false,
}: {
  template: StoreTemplate
  business: StoreBusinessData
  content: StoreContent
  products: PublicProductLite[]
  currency: string
  previewMode?: boolean
}) {
  const categories = Array.from(
    new Set(products.map((p) => (p.category || '').trim()).filter(Boolean)),
  )
  const featured = products.filter((p) => p.available_quantity > 0).slice(0, 8)
  const gridCls = ProductGridClasses(template)
  const cardRadius = RADIUS_CLASS[template.tokens.radius]
  const h = headingClass(template)
  const promo = (content.promo_text || '').trim()
  const labels = template.labels || {}
  const hasContact = Boolean(business.phone || business.email || business.whatsapp || business.address || content.opening_hours)
  const navItems = deriveNavItems(template, business, content, products.length > 0, categories.length > 0)

  const renderSection = (key: string) => {
    switch (key) {
      case 'promo':
        return promo ? <PromoBanner key="promo" template={template} text={promo} /> : null
      case 'hero':
        return <HeroSection key="hero" template={template} business={business} content={content} previewMode={previewMode} hasContact={hasContact} />
      case 'categories':
        if (categories.length === 0) return previewMode ? (
          <div key="cat-preview" id="categories" className="text-sm opacity-60 border-2 border-dashed border-current/30 rounded-lg p-4 text-center">
            [Preview] Categories — publish at least one product with a category.
          </div>
        ) : null
        return (
          <section key="categories" id="categories">
            <h2 className={`text-2xl md:text-3xl font-bold mb-8 ${h}`}>{labels.categories || 'Shop by Category'}</h2>
            <CategoryShowcase template={template} categories={categories} />
          </section>
        )
      case 'featured':
        if (featured.length === 0) return null
        return (
          <div key="featured">
            <div className="flex items-end justify-between mb-6">
              <h2 className={`text-2xl md:text-4xl font-bold ${h}`}>{labels.featured || 'Featured'}</h2>
              <Link href="#products" className="text-sm font-semibold hover:underline underline-offset-4" style={{ color: 'var(--store-primary)' }}>
                View all →
              </Link>
            </div>
            <div className="flex gap-5 overflow-x-auto pb-3 -mx-1 px-1 snap-x snap-mandatory store-scrollbar">
              {featured.map((p) => (
                <div key={p.id} className="w-64 sm:w-72 flex-shrink-0 snap-start">
                  <StoreProductCard product={p} businessSlug={business.slug} template={template} currency={currency} />
                </div>
              ))}
            </div>
          </div>
        )
      case 'products':
        if (products.length === 0) return <EmptyCatalog key="products-empty" template={template} />
        return (
          <div key="products" id="products">
            <h2 className={`text-2xl md:text-4xl font-bold mb-8 ${h}`}>{labels.products || 'All Products'}</h2>
            <div className={`grid gap-6 ${gridCls}`}>
              {products.map((p) => (
                <div key={p.id} className={ANIM_ROOT[template.tokens.animation]}>
                  <StoreProductCard product={p} businessSlug={business.slug} template={template} currency={currency} />
                </div>
              ))}
            </div>
          </div>
        )
      case 'about':
        return <AboutStory key="about" template={template} business={business} content={content} previewMode={previewMode} />
      case 'story':
        return <StorySection key="story" template={template} content={content} businessName={business.name} previewMode={previewMode} />
      case 'stats': {
        const stats = content.stats || []
        if (stats.length === 0) {
          if (!previewMode) return null
          return <PreviewNote key="stats-preview" label="Stats strip" />
        }
        return <StatsStrip key="stats" template={template} stats={stats} />
      }
      case 'testimonials': {
        if ((content.testimonials || []).length === 0) {
          if (!previewMode) return null
          return <PreviewNote key="testi-preview" label="Customer testimonials" />
        }
        return <TestimonialsSection key="testimonials" template={template} content={content} />
      }
      case 'faq':
        if ((content.faqs || []).length === 0) {
          if (!previewMode) return null
          return <PreviewNote key="faq-preview" label="FAQ section" />
        }
        return <FaqSection key="faq" template={template} content={content} />
      case 'trust':
        return <TrustSignals key="trust" template={template} content={content} />
      case 'contact':
        return <ContactSection key="contact" template={template} business={business} content={content} />
      default:
        return null
    }
  }

  const dividerStyle = template.tokens.dividerStyle || 'none'
  const rhythm = template.tokens.sectionRhythm || 'alternating'

  const Divider = () => {
    if (dividerStyle === 'none') return null
    if (dividerStyle === 'gradient') return <div className="h-px w-full opacity-30" style={{ background: `linear-gradient(90deg, transparent, var(--store-primary), transparent)` }} aria-hidden />
    if (dividerStyle === 'dots') return <div className="flex items-center justify-center gap-2 py-2" aria-hidden><span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--store-border)' }} /><span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--store-primary)', opacity: 0.6 }} /><span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--store-border)' }} /></div>
    if (dividerStyle === 'shape') return <div className="flex justify-center py-2" aria-hidden><div className="w-10 h-1 rounded-full" style={{ background: 'var(--store-accent)' }} /></div>
    return <div className="h-px w-full" style={{ background: 'var(--store-border)', opacity: 0.5 }} aria-hidden />
  }

  // Sections that render their own full-bleed band (w-full bg + inner max-w-7xl).
  // Wrapping these again in the outer container double-applies the horizontal
  // gutters and constrains their tinted background to the content column instead
  // of the viewport — the root cause of content floating toward/off the edges.
  const FULL_BLEED: Record<string, boolean> = { trust: true, contact: true }

  // Wrap each section — normal: contained max-w-7xl; alt: full-bleed tinted bg with inner max-w-7xl (so bg matches body, no visible edge)
  const wrapWithRhythm = (node: React.ReactNode, idx: number, key: string) => {
    if (!node) return null
    if (FULL_BLEED[key]) {
      // Full-bleed sections control their own vertical rhythm and gutters.
      return (
        <div key={`wrap-${idx}`} className="w-full">
          {node}
        </div>
      )
    }
    const isAlt = rhythm === 'alternating' && idx % 2 === 1
    const rhythmClass = rhythm === 'minimal' ? 'py-6' : rhythm === 'editorial' ? 'py-12 md:py-16' : rhythm === 'progressive' ? (idx === 0 ? 'pt-2' : idx === 1 ? 'pt-6' : 'pt-10') : ''
    if (!isAlt) {
      return (
        <div key={`wrap-${idx}`} className={`mx-auto w-full max-w-7xl px-4 sm:px-6 lg:px-8 ${rhythmClass}`}>
          {node}
        </div>
      )
    }
    return (
      <div key={`wrap-${idx}`} className={`w-full px-4 sm:px-6 lg:px-8 py-8 ${rhythmClass}`} style={{ backgroundColor: 'color-mix(in srgb, var(--store-surface) 50%, transparent)' }}>
        <div className="mx-auto w-full max-w-7xl">{node}</div>
      </div>
    )
  }

  const rendered = template.sections.map((key, idx) => {
    const node = renderSection(key)
    if (!node) return null
    return (
      <div key={`sec-${key}-${idx}`}>
        {wrapWithRhythm(node, idx, key)}
        {idx < template.sections.length - 1 && <Divider />}
      </div>
    )
  })

  return (
    <div
      data-store-template={template.id}
      data-preview={previewMode ? 'true' : undefined}
      className={`w-full max-w-full overflow-x-hidden ${previewMode ? 'space-y-14' : sectionSpacing(template)} pb-6 store-root ${bodyClass(template)} ${animClass(template)} bg-[var(--store-background)]`}
    >
      <StorefrontNav
        template={template}
        businessName={business.name}
        businessSlug={business.slug}
        logoUrl={business.logo_url ?? null}
        navItems={navItems}
        phone={business.phone ?? null}
        whatsapp={business.whatsapp ?? null}
        email={business.email ?? null}
        address={business.address ?? null}
        hours={(content.opening_hours || '').trim() || null}
      />
      {rendered}
      <FooterPro
        template={template}
        business={business}
        content={content}
        categories={categories}
      />
    </div>
  )
}
