Files
homaroma/apps/website/src/components/dynamic/DynamicPageRenderer.tsx
T
2026-06-21 07:04:03 -04:00

926 lines
40 KiB
TypeScript

"use client"
import Image from 'next/image'
import Link from '../LocalizedLink'
import { Clock, Mail, MapPin, MessageCircle, Send } from 'lucide-react'
import { useState } from 'react'
import type { Category, PageSection, Product } from '@homaroma/types'
import { getCategoryImage } from '@homaroma/types'
import ProductCard from '../ProductCard'
import { localizedFromRecord, resolveCategoryName, resolveLocalized, toRecord } from '../../lib/localization'
import { useLang } from '../../hooks/useLang'
import { Swiper, SwiperSlide } from 'swiper/react'
import { Autoplay } from 'swiper/modules'
import 'swiper/css'
type DynamicPageRendererProps = {
sections: PageSection[]
categories: Category[]
lang?: string // optional override; defaults to i18n.language
}
function categoryName(category: Category, lang: string) {
return resolveCategoryName(category, lang)
}
function getProducts(payload: Record<string, unknown>): Product[] {
return Array.isArray(payload.products) ? payload.products as Product[] : []
}
function getCategoriesFromPayload(payload: Record<string, unknown>): Category[] {
return Array.isArray(payload.categories) ? payload.categories as Category[] : []
}
function localizedValue(value: unknown, lang: string) {
return resolveLocalized(value as never, lang)
}
function optionalText(value: unknown, lang: string) {
if (Array.isArray(value)) return value.map(v => localizedValue(v, lang)).filter(Boolean).join(', ')
return localizedValue(value, lang)
}
function renderAccentTitle(text: string, accentClassName = 'ui-accent-text not-italic') {
if (!text.includes('[') || !text.includes(']')) return text
return text.split('[').map((part, index) => {
if (!part.includes(']')) return <span key={index}>{part}</span>
const [accent, rest] = part.split(']')
return (
<span key={index}>
<span className={accentClassName}>{accent}</span>
{rest}
</span>
)
})
}
function heroLearnMoreText(lang: string) {
const labels: Record<string, string> = {
th: 'ดูรายละเอียดเพิ่มเติม',
en: 'Learn More',
ja: '詳しく見る',
zh: '了解更多',
vi: 'Tìm hiểu thêm',
ko: '자세히 보기',
}
return labels[lang] ?? labels.en
}
function AnnouncementBar({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const slides = Array.isArray(payload.slides) ? payload.slides : []
const backgroundColor = typeof payload.backgroundColor === 'string' ? payload.backgroundColor : undefined
const textColor = typeof payload.textColor === 'string' ? payload.textColor : undefined
const speed = typeof payload.speed === 'number' ? payload.speed : 3000
if (!slides.length) return null
return (
<section
className={`announcement-bar absolute left-0 top-0 z-[60] w-full overflow-hidden px-4 py-3 text-center text-sm font-semibold tracking-wide ${backgroundColor ? '' : 'bg-text-main'} ${textColor ? '' : 'text-surface-card'}`}
style={{ backgroundColor, color: textColor }}
>
<Swiper
modules={[Autoplay]}
autoplay={{ delay: speed, disableOnInteraction: false }}
loop={slides.length > 1}
className="w-full select-none"
>
{slides.map((slide, index) => (
<SwiperSlide key={index} className="flex items-center justify-center">
<span className="inline-block truncate max-w-full">
{localizedFromRecord({ slide }, 'slide', resolvedLang)}
</span>
</SwiperSlide>
))}
</Swiper>
</section>
)
}
function HeroSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const tagline = localizedFromRecord(payload, 'tagline', resolvedLang)
const title = localizedFromRecord(payload, 'title', resolvedLang)
const description = localizedFromRecord(payload, 'description', resolvedLang)
const buttonText = localizedFromRecord(payload, 'buttonText', resolvedLang)
const imageUrl = typeof payload.imageUrl === 'string' ? payload.imageUrl : '/images/hero.png'
const buttonLink = typeof payload.buttonLink === 'string' ? payload.buttonLink : '/shop'
return (
<section className="ui-hero-shell">
<Image
src={imageUrl}
alt={title || ''}
fill
unoptimized
className="absolute inset-0 h-full w-full scale-[1.02] object-cover"
/>
<div className="ui-hero-overlay" />
<div className="ui-hero-overlay-strong" />
<div className="relative z-10 mx-auto mt-16 w-full max-w-4xl space-y-6 px-8 text-center md:mt-0">
<div className="space-y-6">
{tagline && (
<p className="text-xs font-semibold uppercase tracking-[0.3em] text-[#EAEFEA] drop-shadow-md md:text-sm">
{tagline}
</p>
)}
<h1 className="ui-hero-title">
{renderAccentTitle(title || '', 'text-[#D4AF37] font-medium italic')}
</h1>
{description && (
<p className="ui-hero-copy">
{description}
</p>
)}
<div className="flex flex-col items-center justify-center gap-6 sm:flex-row">
<Link
href={buttonLink}
className="ui-hero-button"
>
{buttonText || 'Explore Collection'}
</Link>
<a
href="#categories"
className="ui-hero-link group"
>
{heroLearnMoreText(resolvedLang)}
<span className="transition-transform group-hover:translate-x-1">→</span>
</a>
</div>
</div>
</div>
</section>
)
}
function CategoriesSection({
payload,
categories,
lang,
}: {
payload: Record<string, unknown>
categories: Category[]
lang: string
}) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang) || 'Our Collections'
const subtitle = localizedFromRecord(payload, 'subtitle', resolvedLang)
const categoryIds = Array.isArray(payload.categoryIds) ? payload.categoryIds.map(Number) : []
const payloadCategories = getCategoriesFromPayload(payload)
const sourceCategories = payloadCategories.length ? payloadCategories : categories
const displayed = categoryIds.length ? sourceCategories.filter((category) => categoryIds.includes(category.id)) : sourceCategories
const productsLabel: Record<string, string> = {
th: 'สินค้า',
en: 'Products',
ja: '商品',
zh: '商品',
vi: 'Sản phẩm',
ko: '상품',
}
return (
<section id="categories" className="bg-surface-page ui-section-band">
<div className="ui-section-shell space-y-14">
<div className="mx-auto max-w-2xl space-y-4 text-center">
<h2 className="ui-section-title">{title}</h2>
{subtitle && <p className="ui-section-subtitle">{subtitle}</p>}
</div>
<div className="grid grid-cols-2 gap-5 md:grid-cols-5">
{displayed.map((category) => {
const name = categoryName(category, resolvedLang)
return (
<Link
key={category.id}
href={`/category/${category.id}`}
className="group relative h-72 overflow-hidden rounded-2xl shadow-card transition hover:-translate-y-1 hover:shadow-card-hover"
>
<Image
src={category.imageUrl || getCategoryImage(name)}
alt={name}
fill
unoptimized
className="absolute inset-0 h-full w-full object-cover transition duration-700 group-hover:scale-105"
/>
<div className="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent z-10 opacity-80 group-hover:opacity-100 transition-opacity" />
<div className="absolute bottom-5 left-5 right-5 z-20 text-white">
<span className="block text-lg font-semibold">{name}</span>
{category._count && (
<span className="text-sm text-white/90">
{category._count.products} {productsLabel[resolvedLang] ?? productsLabel.en}
</span>
)}
</div>
</Link>
)
})}
</div>
</div>
</section>
)
}
function ProductsSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang) || 'Featured Picks'
const subtitle = localizedFromRecord(payload, 'subtitle', resolvedLang)
const products = getProducts(payload)
const viewAllLabel: Record<string, string> = {
th: 'ดูทั้งหมด →',
en: 'View All Collection →',
ja: 'すべて見る →',
zh: '查看全部 →',
vi: 'Xem tất cả →',
ko: '전체 보기 →',
}
const emptyLabel: Record<string, string> = {
th: 'ไม่พบสินค้าในหมวดนี้',
en: 'No products found in this section.',
ja: 'このセクションには商品がありません。',
zh: '此区域中没有找到产品。',
vi: 'Không tìm thấy sản phẩm nào trong mục này.',
ko: '이 섹션에서 찾을 수 있는 상품이 없습니다.',
}
return (
<section className="bg-surface-page ui-section-band">
<div className="ui-section-shell space-y-10">
<div className="flex flex-col gap-4 border-b border-line-primary/20 pb-6 md:flex-row md:items-end md:justify-between">
<div>
<h2 className="ui-section-title">{title}</h2>
{subtitle && <p className="mt-2 ui-section-subtitle">{subtitle}</p>}
</div>
<Link href="/shop" className="ui-section-link">
{viewAllLabel[resolvedLang] ?? viewAllLabel.en}
</Link>
</div>
{products.length ? (
<div className="grid grid-cols-1 gap-8 md:grid-cols-3">
{products.map((product) => <ProductCard key={product.id} product={product} />)}
</div>
) : (
<p className="ui-section-card bg-surface-card p-8 text-center text-muted-text">
{emptyLabel[resolvedLang] ?? emptyLabel.en}
</p>
)}
</div>
</section>
)
}
function BannerSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang)
const description = localizedFromRecord(payload, 'description', resolvedLang)
const buttonText = localizedFromRecord(payload, 'buttonText', resolvedLang)
const imageUrl = typeof payload.imageUrl === 'string' ? payload.imageUrl : '/images/hero.png'
const linkUrl = typeof payload.linkUrl === 'string' ? payload.linkUrl : ''
const content = (
<div className="ui-banner-shell">
<Image src={imageUrl} alt={title || 'Banner'} fill unoptimized className="absolute inset-0 h-full w-full object-cover" />
<div className="ui-banner-overlay" />
<div className="ui-banner-content">
{title && <h2 className="text-3xl font-semibold md:text-5xl">{title}</h2>}
{description && <p className="text-surface-card">{description}</p>}
{buttonText && <span className="inline-flex rounded-full bg-surface-card px-6 py-3 font-semibold text-text-main">{buttonText}</span>}
</div>
</div>
)
return <section className="bg-surface-page ui-section-band">{linkUrl ? <Link href={linkUrl}>{content}</Link> : content}</section>
}
function TextSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang)
const content = localizedFromRecord(payload, 'content', resolvedLang)
const alignClass = payload.textAlign === 'center'
? 'text-center'
: payload.textAlign === 'right'
? 'text-right'
: 'text-left'
return (
<section className="bg-surface-page ui-section-band">
<div className={`mx-auto max-w-4xl space-y-6 ${alignClass}`}>
{title && <h2 className="text-3xl font-semibold text-text-main md:text-4xl">{title}</h2>}
{content && <div className="leading-relaxed text-muted-text" dangerouslySetInnerHTML={{ __html: content }} />}
</div>
</section>
)
}
function NewsletterSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang) || 'Stay in touch'
const description = localizedFromRecord(payload, 'description', resolvedLang)
const buttonText = localizedFromRecord(payload, 'buttonText', resolvedLang) || 'Subscribe'
const placeholder = typeof payload.placeholderText === 'string' ? payload.placeholderText : 'you@example.com'
return (
<section className="ui-section-dark">
<div className="mx-auto grid max-w-5xl gap-8 md:grid-cols-[1fr_auto] md:items-end">
<div className="space-y-3">
<h2 className="text-3xl font-semibold text-surface-card md:text-4xl">{title}</h2>
{description && <p className="max-w-2xl text-surface-card">{description}</p>}
</div>
<form className="flex flex-col gap-3 sm:flex-row">
<input className="ui-form-shell min-w-0 rounded-full" placeholder={placeholder} type="email" />
<button className="ui-button-brand rounded-full" type="button">
{buttonText}
</button>
</form>
</div>
</section>
)
}
function EditorialTileSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang)
const description = localizedFromRecord(payload, 'description', resolvedLang)
const buttonText = localizedFromRecord(payload, 'buttonText', resolvedLang)
const buttonLink = typeof payload.buttonLink === 'string' ? payload.buttonLink : ''
const imageUrl = typeof payload.imageUrl === 'string' ? payload.imageUrl : ''
const imagePosition = payload.imagePosition === 'right' ? 'right' : 'left'
const backgroundColor = typeof payload.backgroundColor === 'string' ? payload.backgroundColor : undefined
const textColor = typeof payload.textColor === 'string' ? payload.textColor : undefined
return (
<section className="overflow-hidden bg-surface-page ui-section-band" style={{ backgroundColor, color: textColor }}>
<div className="mx-auto grid max-w-7xl gap-12 md:grid-cols-2 md:items-center">
{imageUrl && (
<div className={`group relative aspect-square overflow-hidden rounded-3xl shadow-card ${imagePosition === 'left' ? 'md:order-1' : 'md:order-2'}`}>
<Image
src={imageUrl}
alt={title || 'Editorial'}
fill
unoptimized
className="h-full w-full object-cover transition duration-700 group-hover:scale-105"
/>
</div>
)}
<div className={`space-y-6 ${imagePosition === 'left' ? 'md:order-2' : 'md:order-1'}`}>
{title && (
<h2 className="text-4xl font-semibold leading-tight text-text-main md:text-6xl" style={{ color: textColor }}>
{renderAccentTitle(title)}
</h2>
)}
<div className="h-px w-14 bg-brand-primary" />
{description && <p className="whitespace-pre-line text-base leading-relaxed text-muted-text md:text-lg" style={{ color: textColor }}>{description}</p>}
{buttonText && buttonLink && (
<Link href={buttonLink} className="ui-section-link inline-flex rounded-full border border-current px-8 py-3 text-xs font-bold uppercase tracking-[0.22em] transition hover:bg-brand-primary hover:text-surface-card">
{buttonText}
</Link>
)}
</div>
</div>
</section>
)
}
function EditorialCarouselSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang)
const slides = Array.isArray(payload.slides) ? payload.slides.map(toRecord) : []
if (!slides.length) return null
return (
<section className="ui-section-dark">
<div className="mx-auto max-w-7xl space-y-12">
{title && (
<div className="mx-auto max-w-3xl space-y-4 text-center">
<h2 className="text-4xl font-semibold text-surface-card md:text-5xl">{renderAccentTitle(title, 'ui-accent-text not-italic')}</h2>
<div className="mx-auto h-px w-16 bg-brand-accent" />
</div>
)}
<div className="grid gap-6 md:grid-cols-3">
{slides.map((slide, index) => {
const slideTitle = localizedFromRecord(slide, 'title', resolvedLang)
const description = localizedFromRecord(slide, 'description', resolvedLang)
const category = localizedFromRecord(slide, 'category', resolvedLang)
const buttonText = localizedFromRecord(slide, 'buttonText', resolvedLang)
const buttonLink = typeof slide.buttonLink === 'string' ? slide.buttonLink : ''
const imageUrl = typeof slide.imageUrl === 'string' ? slide.imageUrl : ''
return (
<article key={index} className="ui-section-dark-card group">
{imageUrl && (
<div className="relative aspect-[4/3] overflow-hidden">
<Image
src={imageUrl}
alt={slideTitle || 'Editorial slide'}
fill
unoptimized
className="h-full w-full object-cover transition duration-700 group-hover:scale-105"
/>
</div>
)}
<div className="space-y-4 p-6">
{category && <p className="text-[10px] font-bold uppercase tracking-[0.24em] text-brand-accent">{category}</p>}
{slideTitle && <h3 className="ui-section-dark-card-title">{renderAccentTitle(slideTitle)}</h3>}
{description && <p className="ui-section-dark-card-copy">{description}</p>}
{buttonText && buttonLink && (
<Link href={buttonLink} className="ui-section-dark-link">
{buttonText} &rarr;
</Link>
)}
</div>
</article>
)
})}
</div>
</div>
</section>
)
}
function HeroArticleSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang) || 'Scent Guide Article'
const subtitle = localizedFromRecord(payload, 'subtitle', resolvedLang)
const author = localizedFromRecord(payload, 'author', resolvedLang)
const category = localizedFromRecord(payload, 'category', resolvedLang)
const imageUrl = typeof payload.imageUrl === 'string'
? payload.imageUrl
: typeof payload.backgroundImageUrl === 'string'
? payload.backgroundImageUrl
: ''
const date = typeof payload.date === 'string'
? payload.date
: typeof payload.publishDate === 'string'
? payload.publishDate
: ''
const authorPrefix: Record<string, string> = {
th: 'โดย',
en: 'By',
ja: '著者',
zh: '作者',
vi: 'Bởi',
ko: '작성자',
}
return (
<section className="ui-hero-shell min-h-[60vh] px-6 py-24 text-center md:min-h-[76vh]">
{imageUrl && (
<>
<Image src={imageUrl} alt={title} fill unoptimized className="absolute inset-0 h-full w-full object-cover" />
<div className="ui-hero-overlay" />
</>
)}
<div className="relative z-10 mx-auto max-w-4xl space-y-6">
{category && <p className="text-xs font-bold uppercase tracking-[0.28em] text-brand-accent">{category}</p>}
<h1 className="ui-hero-title">{title}</h1>
{subtitle && <p className="mx-auto max-w-2xl text-lg text-surface-card md:text-xl">{subtitle}</p>}
{(author || date) && (
<p className="text-xs font-bold uppercase tracking-[0.22em] text-surface-card">
{[author && `${authorPrefix[resolvedLang] ?? authorPrefix.en} ${author}`, date].filter(Boolean).join(' / ')}
</p>
)}
</div>
</section>
)
}
function ScentNotesBreakdownSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const title = localizedFromRecord(payload, 'title', resolvedLang) || 'Scent Notes'
const description = localizedFromRecord(payload, 'description', resolvedLang)
const noteLabels: Record<string, Record<string, string>> = {
th: { top: 'กลิ่นเปิด', heart: 'กลิ่นกลาง', base: 'กลิ่นฐาน' },
en: { top: 'Top Notes', heart: 'Heart Notes', base: 'Base Notes' },
ja: { top: 'トップノート', heart: 'ミドルノート', base: 'ベースノート' },
zh: { top: '前调', heart: '中调', base: '后调' },
vi: { top: 'Hương đầu', heart: 'Hương giữa', base: 'Hương cuối' },
ko: { top: '탑 노트', heart: '미들 노트', base: '베이스 노트' },
}
const labels = noteLabels[resolvedLang] ?? noteLabels.en
const notes = [
[labels.top, optionalText(payload.topNotes, resolvedLang) || 'The initial, lighter smells of the fragrance.'],
[labels.heart, optionalText(payload.heartNotes ?? payload.middleNotes, resolvedLang) || 'The core of the fragrance, emerging just after the top notes.'],
[labels.base, optionalText(payload.baseNotes, resolvedLang) || 'The deepest, richest scents that linger the longest.'],
]
return (
<section className="bg-surface-page ui-section-band">
<div className="mx-auto max-w-6xl space-y-12 text-center">
<div className="mx-auto max-w-3xl space-y-4">
<h2 className="ui-section-title">{title}</h2>
{description && <p className="text-muted-text">{description}</p>}
</div>
<div className="grid gap-6 md:grid-cols-3">
{notes.map(([label, value]) => (
<article key={label} className="ui-section-card p-8 text-left">
<h3 className="mb-4 text-xs font-bold uppercase tracking-[0.24em] text-brand-primary">{label}</h3>
<p className="leading-relaxed text-muted-text">{value}</p>
</article>
))}
</div>
</div>
</section>
)
}
function QuoteCalloutSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const quote = localizedFromRecord(payload, 'quote', resolvedLang)
const author = localizedFromRecord(payload, 'author', resolvedLang)
const role = localizedFromRecord(payload, 'role', resolvedLang)
if (!quote) return null
return (
<section className="bg-surface-page px-6 py-24">
<div className="mx-auto max-w-4xl text-center">
<p className="mb-8 text-7xl leading-none text-brand-primary/25">&quot;</p>
<blockquote className="text-3xl font-semibold italic leading-relaxed text-text-main md:text-5xl">
{quote}
</blockquote>
{(author || role) && (
<p className="mt-8 text-xs font-bold uppercase tracking-[0.24em] text-muted-text">
{[author, role].filter(Boolean).join(' / ')}
</p>
)}
</div>
</section>
)
}
function AccordionSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const categories = Array.isArray(payload.categories) ? payload.categories.map(toRecord) : []
if (!categories.length) return null
const sectionTitle = localizedFromRecord(payload, 'title', resolvedLang)
return (
<section className="bg-surface-page ui-section-band">
<div className="mx-auto max-w-4xl space-y-10">
{sectionTitle && <h2 className="ui-section-title">{sectionTitle}</h2>}
{categories.map((category, categoryIndex) => {
const questions = Array.isArray(category.questions) ? category.questions.map(toRecord) : []
const name = localizedFromRecord(category, 'name', resolvedLang)
const icon = typeof category.icon === 'string' ? category.icon : ''
return (
<div key={categoryIndex} className="space-y-5">
{name && (
<h2 className="flex items-center gap-3 text-2xl font-semibold text-text-main">
{icon && <span className="text-brand-primary">{icon}</span>}
{name}
</h2>
)}
<div className="space-y-4">
{questions.map((item, itemIndex) => {
const question = localizedFromRecord(item, 'q', resolvedLang)
const answer = localizedFromRecord(item, 'a', resolvedLang)
if (!question || !answer) return null
return (
<details key={itemIndex} className="group rounded-2xl bg-surface-card p-5 shadow-card">
<summary className="cursor-pointer list-none text-lg font-semibold text-text-main marker:hidden">
{question}
</summary>
<p className="mt-4 whitespace-pre-wrap leading-relaxed text-muted-text">{answer}</p>
</details>
)
})}
</div>
</div>
)
})}
</div>
</section>
)
}
function ContactInfoSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const labels: Record<string, Record<string, string>> = {
th: { address: 'ที่อยู่', email: 'อีเมล', line: 'Line', hours: 'เวลาทำการ' },
en: { address: 'Address', email: 'Email', line: 'Line', hours: 'Business Hours' },
ja: { address: '住所', email: 'メール', line: 'Line', hours: '営業時間' },
zh: { address: '地址', email: '电子邮件', line: 'Line', hours: '营业时间' },
vi: { address: 'Địa chỉ', email: 'Email', line: 'Line', hours: 'Giờ làm việc' },
ko: { address: '주소', email: '이메일', line: 'Line', hours: '운영 시간' },
}
const resolvedLabels = labels[resolvedLang] ?? labels.en
const title = localizedFromRecord(payload, 'title', resolvedLang)
const address = localizedFromRecord(payload, 'address', resolvedLang)
const email = typeof payload.email === 'string' ? payload.email : ''
const line = typeof payload.line === 'string' ? payload.line : ''
const hours = localizedFromRecord(payload, 'hours', resolvedLang)
const items = [
{ key: 'address', label: resolvedLabels.address, value: address, Icon: MapPin },
{ key: 'email', label: resolvedLabels.email, value: email, Icon: Mail },
{ key: 'line', label: resolvedLabels.line, value: line, Icon: MessageCircle },
{ key: 'hours', label: resolvedLabels.hours, value: hours, Icon: Clock },
] as const
return (
<section className="bg-surface-page ui-section-band">
<div className="mx-auto grid max-w-6xl gap-6 md:grid-cols-2 lg:grid-cols-4">
{title && (
<div className="col-span-full mb-2">
<h2 className="ui-section-title">{title}</h2>
</div>
)}
{items.map(({ key, label, value, Icon }) => {
if (!value) return null
return (
<article key={key} className="ui-section-card-muted p-6 text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-surface-card text-brand-primary">
<Icon className="h-6 w-6" />
</div>
<h3 className="mb-2 text-lg font-semibold text-text-main">{label}</h3>
{key === 'email' ? (
<a className="break-words text-muted-text transition hover:text-brand-primary" href={`mailto:${value}`}>
{value}
</a>
) : (
<p className="whitespace-pre-wrap break-words text-muted-text">{value}</p>
)}
</article>
)
})}
</div>
</section>
)
}
function ContactFormSection({ payload, lang }: { payload: Record<string, unknown>, lang: string }) {
const i18nLang = useLang()
const resolvedLang = lang === 'all' ? i18nLang : lang
const [formData, setFormData] = useState({ name: '', email: '', message: '' })
const [isSubmitting, setIsSubmitting] = useState(false)
const [isSuccess, setIsSuccess] = useState(false)
const title = localizedFromRecord(payload, 'title', resolvedLang)
const subtitle = localizedFromRecord(payload, 'subtitle', resolvedLang)
const labels: Record<string, Record<string, string>> = {
th: {
title: 'ติดต่อเรา',
subtitle: 'ส่งข้อความถึงทีมงานของเรา เรายินดีให้บริการและพร้อมตอบทุกข้อสงสัย',
successTitle: 'ส่งข้อความสำเร็จ',
successBody: 'ขอบคุณที่ติดต่อเรา ทีมงานจะรีบตอบกลับโดยเร็วที่สุด',
name: 'ชื่อ-นามสกุล',
namePlaceholder: 'กรอกชื่อของคุณ',
email: 'อีเมล',
message: 'ข้อความ',
messagePlaceholder: 'พิมพ์ข้อความของคุณที่นี่...',
submit: 'ส่งข้อความ',
},
en: {
title: 'Contact Us',
subtitle: 'Send a message to our team and we will get back to you soon.',
successTitle: 'Message sent successfully',
successBody: 'Thanks for reaching out. Our team will reply as soon as possible.',
name: 'Full Name',
namePlaceholder: 'Enter your name',
email: 'Email',
message: 'Message',
messagePlaceholder: 'Type your message here...',
submit: 'Send Message',
},
ja: {
title: 'お問い合わせ',
subtitle: 'チームへメッセージをお送りください。できるだけ早くご返信します。',
successTitle: '送信に成功しました',
successBody: 'お問い合わせありがとうございます。担当者ができるだけ早く返信します。',
name: '氏名',
namePlaceholder: 'お名前を入力してください',
email: 'メール',
message: 'メッセージ',
messagePlaceholder: 'ここにメッセージを入力してください...',
submit: '送信',
},
zh: {
title: '联系我们',
subtitle: '给我们的团队留言,我们会尽快回复您。',
successTitle: '发送成功',
successBody: '感谢您的联系,我们会尽快回复。',
name: '姓名',
namePlaceholder: '请输入您的姓名',
email: '邮箱',
message: '留言',
messagePlaceholder: '在这里输入您的留言...',
submit: '发送消息',
},
vi: {
title: 'Liên hệ',
subtitle: 'Gửi tin nhắn cho đội ngũ của chúng tôi, chúng tôi sẽ phản hồi sớm nhất.',
successTitle: 'Gửi tin nhắn thành công',
successBody: 'Cảm ơn bạn đã liên hệ, đội ngũ của chúng tôi sẽ phản hồi sớm nhất có thể.',
name: 'Họ và tên',
namePlaceholder: 'Nhập tên của bạn',
email: 'Email',
message: 'Tin nhắn',
messagePlaceholder: 'Nhập tin nhắn của bạn tại đây...',
submit: 'Gửi tin nhắn',
},
ko: {
title: '문의하기',
subtitle: '팀에 메시지를 보내주시면 최대한 빨리 답변드리겠습니다.',
successTitle: '메시지 전송 완료',
successBody: '문의해 주셔서 감사합니다. 가능한 빨리 답변드리겠습니다.',
name: '이름',
namePlaceholder: '이름을 입력하세요',
email: '이메일',
message: '메시지',
messagePlaceholder: '여기에 메시지를 입력하세요...',
submit: '메시지 보내기',
}
}
const copy = labels[resolvedLang] ?? labels.en
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
setIsSubmitting(true)
// Simulate API call
setTimeout(() => {
setIsSubmitting(false)
setIsSuccess(true)
setFormData({ name: '', email: '', message: '' })
// Reset success message after 3 seconds
setTimeout(() => setIsSuccess(false), 3000)
}, 1000)
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
}
return (
<section className="ui-section-band bg-surface-page px-4 py-20 md:px-8">
<div className="mx-auto max-w-3xl">
<div className="mb-12 text-center">
<h2 className="mb-4 text-3xl font-semibold text-text-main md:text-4xl">
{title || copy.title}
</h2>
<p className="mx-auto max-w-xl text-lg text-muted-text">
{subtitle || copy.subtitle}
</p>
</div>
<div className="rounded-3xl border border-line-primary/20 bg-surface-card p-8 shadow-card md:p-12">
{isSuccess ? (
<div className="py-12 text-center">
<div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-brand-success/20 text-brand-success">
<Send size={32} />
</div>
<h3 className="mb-2 text-2xl font-semibold text-text-main">{copy.successTitle}</h3>
<p className="text-muted-text">{copy.successBody}</p>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div className="space-y-2">
<label htmlFor="name" className="block text-sm font-medium text-text-main">
{copy.name}
</label>
<input
type="text"
id="name"
name="name"
required
value={formData.name}
onChange={handleChange}
className="w-full rounded-xl border border-line-primary/30 bg-surface-page px-4 py-3 text-text-main outline-none transition-all focus:border-brand-primary focus:ring-2 focus:ring-brand-primary/20"
placeholder={copy.namePlaceholder}
/>
</div>
<div className="space-y-2">
<label htmlFor="email" className="block text-sm font-medium text-text-main">
{copy.email}
</label>
<input
type="email"
id="email"
name="email"
required
value={formData.email}
onChange={handleChange}
className="w-full rounded-xl border border-line-primary/30 bg-surface-page px-4 py-3 text-text-main outline-none transition-all focus:border-brand-primary focus:ring-2 focus:ring-brand-primary/20"
placeholder="example@email.com"
/>
</div>
</div>
<div className="space-y-2">
<label htmlFor="message" className="block text-sm font-medium text-text-main">
{copy.message}
</label>
<textarea
id="message"
name="message"
required
value={formData.message}
onChange={handleChange}
rows={5}
className="w-full resize-none rounded-xl border border-line-primary/30 bg-surface-page px-4 py-3 text-text-main outline-none transition-all focus:border-brand-primary focus:ring-2 focus:ring-brand-primary/20"
placeholder={copy.messagePlaceholder}
/>
</div>
<button
type="submit"
disabled={isSubmitting}
className="flex w-full items-center justify-center gap-2 rounded-xl bg-brand-primary px-6 py-4 font-semibold text-white transition-colors hover:bg-brand-primary-hover disabled:cursor-not-allowed disabled:opacity-70"
>
{isSubmitting ? (
<span className="h-6 w-6 animate-spin rounded-full border-2 border-white/30 border-t-white" />
) : (
<>
<Send size={18} />
{copy.submit}
</>
)}
</button>
</form>
)}
</div>
</div>
</section>
)
}
export default function DynamicPageRenderer({ sections, categories, lang: langProp }: DynamicPageRendererProps) {
const i18nLang = useLang()
// Use i18n.language reactively — switches immediately when user changes language
const lang = langProp ?? i18nLang
return (
<div className="flex w-full flex-col">
{sections.map((section) => {
if (!section.isActive) return null
const payload = toRecord(section.payload)
const type = section.type.toUpperCase()
switch (type) {
case 'ANNOUNCEMENT_BAR':
return <AnnouncementBar key={section.id} payload={payload} lang={lang} />
case 'HERO':
return <HeroSection key={section.id} payload={payload} lang={lang} />
case 'CATEGORIES':
return <CategoriesSection key={section.id} payload={payload} categories={categories} lang={lang} />
case 'PRODUCTS':
case 'PRODUCT_CAROUSEL':
return <ProductsSection key={section.id} payload={payload} lang={lang} />
case 'BANNER':
return <BannerSection key={section.id} payload={payload} lang={lang} />
case 'TEXT':
return <TextSection key={section.id} payload={payload} lang={lang} />
case 'NEWSLETTER':
return <NewsletterSection key={section.id} payload={payload} lang={lang} />
case 'EDITORIAL_TILE':
return <EditorialTileSection key={section.id} payload={payload} lang={lang} />
case 'EDITORIAL_CAROUSEL':
return <EditorialCarouselSection key={section.id} payload={payload} lang={lang} />
case 'HERO_ARTICLE':
return <HeroArticleSection key={section.id} payload={payload} lang={lang} />
case 'RICH_TEXT':
return <TextSection key={section.id} payload={payload} lang={lang} />
case 'SCENT_NOTES_BREAKDOWN':
return <ScentNotesBreakdownSection key={section.id} payload={payload} lang={lang} />
case 'QUOTE_CALLOUT':
return <QuoteCalloutSection key={section.id} payload={payload} lang={lang} />
case 'ACCORDION':
return <AccordionSection key={section.id} payload={payload} lang={lang} />
case 'CONTACT_INFO':
return <ContactInfoSection key={section.id} payload={payload} lang={lang} />
case 'CONTACT_FORM':
return <ContactFormSection key={section.id} payload={payload} lang={lang} />
default:
if (process.env.NODE_ENV !== 'production') {
console.warn(`[DynamicPageRenderer] Unsupported section type: ${section.type}`)
}
return null
}
})}
</div>
)
}