'use client' import { useEffect, useState } from 'react' import Link from 'next/link' import { cloneStorefrontHomepageContent, resolveStorefrontHomepageSections, type StorefrontHomepageConfig, type StorefrontHomepageContent, type StorefrontHomepageSectionType, type StorefrontLanguage, } from '@rentaldrivego/types' import { useAdminI18n } from '@/components/I18nProvider' import { ADMIN_API_BASE } from '@/lib/api' interface Company { id: string name: string slug: string status: string email: string brand: { displayName: string | null } | null } const STATUS_COLORS: Record = { ACTIVE: 'text-emerald-400 bg-emerald-900/30', TRIALING: 'text-sky-400 bg-sky-900/30', SUSPENDED: 'text-red-400 bg-red-900/30', PENDING: 'text-orange-400 bg-orange-900/30', CANCELLED: 'text-zinc-400 bg-zinc-800', } const INPUT_CLASS = 'w-full rounded-xl border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500' const LABEL_CLASS = 'mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-zinc-500' function cloneHomepageContent(content: StorefrontHomepageConfig) { const cloned = JSON.parse(JSON.stringify(content)) as StorefrontHomepageConfig ;(['en', 'fr', 'ar'] as StorefrontLanguage[]).forEach((language) => { cloned[language].sections = resolveStorefrontHomepageSections(cloned[language].sections) }) return cloned } const HOMEPAGE_SECTIONS: StorefrontHomepageSectionType[] = [ 'hero', 'surface', 'pillars', 'audiences', 'features', 'steps', 'closing', ] export default function AdminSiteConfigPage() { const { language, dict } = useAdminI18n() const copy = { en: { title: 'Site configuration', description: 'Edit the main storefront homepage here, or jump into a company to manage its branded public homepage and menu.', homepageTitle: 'Main website homepage', homepageDescription: 'This controls the storefront homepage shown on the main RentalDriveGo website.', saveHomepage: 'Save homepage', savingHomepage: 'Saving…', homepageSaved: 'Storefront homepage saved.', search: 'Search by company or slug…', loading: 'Loading…', empty: 'No companies found', company: 'Company', slug: 'Slug', status: 'Status', actions: 'Actions', configure: 'Configure site', manageCompany: 'Open company', companiesTitle: 'Company branded sites', languageLabel: 'Language', hero: 'Hero', surface: 'Surface', companySection: 'Operator card', renterSection: 'Renter card', valueSection: 'Value blocks', featureSection: 'Feature list', stepsSection: 'Launch steps', closingSection: 'Closing call to action', previewTitle: 'Live preview', previewDescription: 'Draft changes appear here before you save them.', homepageSections: 'Homepage sections', homepageSectionsDescription: 'Add or remove blocks from the main storefront homepage.', addSection: 'Add', removeSection: 'Remove', expand: 'Expand', collapse: 'Collapse', }, fr: { title: 'Configuration du site', description: 'Modifiez ici la page d’accueil principale de la storefront, ou ouvrez une entreprise pour gérer sa page publique et son menu.', homepageTitle: 'Page d’accueil du site principal', homepageDescription: 'Cette section contrôle la page d’accueil storefront affichée sur le site principal de RentalDriveGo.', saveHomepage: 'Enregistrer la page d’accueil', savingHomepage: 'Enregistrement…', homepageSaved: 'Page d’accueil storefront enregistrée.', search: 'Rechercher par entreprise ou slug…', loading: 'Chargement…', empty: 'Aucune entreprise trouvée', company: 'Entreprise', slug: 'Slug', status: 'Statut', actions: 'Actions', configure: 'Configurer le site', manageCompany: 'Ouvrir l’entreprise', companiesTitle: 'Sites de marque des entreprises', languageLabel: 'Langue', hero: 'Bloc principal', surface: 'Bloc storefront', companySection: 'Bloc opérateur', renterSection: 'Bloc client', valueSection: 'Blocs de valeur', featureSection: 'Liste des fonctionnalités', stepsSection: 'Étapes de lancement', closingSection: 'Appel à l’action final', previewTitle: 'Aperçu en direct', previewDescription: 'Les brouillons apparaissent ici avant l’enregistrement.', homepageSections: 'Sections de la page d’accueil', homepageSectionsDescription: 'Ajoutez ou retirez des blocs de la page d’accueil storefront principale.', addSection: 'Ajouter', removeSection: 'Retirer', expand: 'Ouvrir', collapse: 'Réduire', }, ar: { title: 'إعدادات الموقع', description: 'عدّل الصفحة الرئيسية للموقع الرئيسي هنا، أو افتح شركة لإدارة صفحتها العامة وقائمة التنقل الخاصة بها.', homepageTitle: 'الصفحة الرئيسية للموقع الرئيسي', homepageDescription: 'هذا القسم يتحكم في الصفحة الرئيسية للمنصة على موقع RentalDriveGo الرئيسي.', saveHomepage: 'حفظ الصفحة الرئيسية', savingHomepage: 'جارٍ الحفظ…', homepageSaved: 'تم حفظ الصفحة الرئيسية للمنصة.', search: 'ابحث باسم الشركة أو slug…', loading: 'جارٍ التحميل…', empty: 'لم يتم العثور على شركات', company: 'الشركة', slug: 'Slug', status: 'الحالة', actions: 'الإجراءات', configure: 'إعداد الموقع', manageCompany: 'فتح الشركة', companiesTitle: 'المواقع العامة للشركات', languageLabel: 'اللغة', hero: 'البطاقة الرئيسية', surface: 'قسم المنصة', companySection: 'بطاقة المشغل', renterSection: 'بطاقة المستأجر', valueSection: 'عناصر القيمة', featureSection: 'قائمة الميزات', stepsSection: 'خطوات الإطلاق', closingSection: 'الدعوة الختامية', previewTitle: 'معاينة مباشرة', previewDescription: 'تظهر التغييرات هنا قبل الحفظ.', homepageSections: 'أقسام الصفحة الرئيسية', homepageSectionsDescription: 'أضف أو احذف كتل الصفحة الرئيسية للمنصة.', addSection: 'إضافة', removeSection: 'إزالة', expand: 'توسيع', collapse: 'طي', }, }[language] const [companies, setCompanies] = useState([]) const [filtered, setFiltered] = useState([]) const [search, setSearch] = useState('') const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [homepage, setHomepage] = useState(cloneStorefrontHomepageContent()) const [homepageLanguage, setHomepageLanguage] = useState(language) const [homepageSaving, setHomepageSaving] = useState(false) const [homepageMessage, setHomepageMessage] = useState(null) const [homepageExpanded, setHomepageExpanded] = useState(false) useEffect(() => { setHomepageLanguage(language) }, [language]) useEffect(() => { async function fetchData() { try { const [companiesRes, homepageRes] = await Promise.all([ fetch(`${ADMIN_API_BASE}/admin/companies`, { credentials: 'include', cache: 'no-store', }), fetch(`${ADMIN_API_BASE}/admin/site-config/storefront-homepage`, { credentials: 'include', cache: 'no-store', }), ]) const companiesJson = await companiesRes.json() if (!companiesRes.ok) throw new Error(companiesJson?.message ?? 'Failed to fetch companies') setCompanies(companiesJson.data?.data ?? []) setFiltered(companiesJson.data?.data ?? []) const homepageJson = await homepageRes.json() if (homepageRes.ok && homepageJson?.data) { setHomepage(cloneHomepageContent(homepageJson.data as StorefrontHomepageConfig)) } } catch (err: any) { setError(err.message) } finally { setLoading(false) } } fetchData() }, []) useEffect(() => { const q = search.toLowerCase() setFiltered( companies.filter((company) => company.name.toLowerCase().includes(q) || company.slug.toLowerCase().includes(q) || company.email.toLowerCase().includes(q), ), ) }, [search, companies]) function updateHomepageContent(patch: Partial) { setHomepage((current) => ({ ...current, [homepageLanguage]: { ...current[homepageLanguage], ...patch, }, })) } function updateMetric(index: number, label: string) { const metrics = homepage[homepageLanguage].metrics.map((metric, metricIndex) => ( metricIndex === index ? { ...metric, label } : metric )) updateHomepageContent({ metrics }) } function updatePillar(index: number, patch: { title?: string; body?: string }) { const pillars = homepage[homepageLanguage].pillars.map((pillar, pillarIndex) => ( pillarIndex === index ? { ...pillar, ...patch } : pillar )) updateHomepageContent({ pillars }) } function updateStep(index: number, patch: { title?: string; body?: string }) { const steps = homepage[homepageLanguage].steps.map((step, stepIndex) => ( stepIndex === index ? { ...step, ...patch } : step )) updateHomepageContent({ steps }) } function getActiveSections() { return resolveStorefrontHomepageSections(activeContent.sections) } function addHomepageSection(section: StorefrontHomepageSectionType) { const sections = getActiveSections() if (sections.includes(section)) return updateHomepageContent({ sections: [...sections, section] }) } function removeHomepageSection(section: StorefrontHomepageSectionType) { const sections = getActiveSections().filter((item) => item !== section) if (sections.length === 0) return updateHomepageContent({ sections }) } async function saveHomepage() { setHomepageSaving(true) setHomepageMessage(null) try { const res = await fetch(`${ADMIN_API_BASE}/admin/site-config/storefront-homepage`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ homepage }), }) const json = await res.json() if (!res.ok) throw new Error(json?.message ?? 'Failed to save homepage') setHomepage(cloneHomepageContent(json.data as StorefrontHomepageConfig)) setHomepageMessage(copy.homepageSaved) } catch (err: any) { setError(err.message) } finally { setHomepageSaving(false) } } const activeContent = homepage[homepageLanguage] const activeSections = getActiveSections() const availableSections = HOMEPAGE_SECTIONS.filter((section) => !activeSections.includes(section)) const sectionLabels: Record = { hero: copy.hero, surface: copy.surface, pillars: copy.valueSection, audiences: `${copy.companySection} / ${copy.renterSection}`, features: copy.featureSection, howitworks: language === 'fr' ? 'Fonctionnement' : language === 'ar' ? 'كيفية العمل' : 'How it works', steps: copy.stepsSection, testimonials: language === 'fr' ? 'Témoignages' : language === 'ar' ? 'الشهادات' : 'Testimonials', closing: copy.closingSection, } return (

{dict.platform}

{copy.title}

{copy.description}

setSearch(event.target.value)} />
{error ?
{error}
: null}

{copy.homepageTitle}

{copy.homepageDescription}

{copy.languageLabel} {(['en', 'fr', 'ar'] as StorefrontLanguage[]).map((value) => ( ))}
{homepageExpanded ? ( <> {homepageMessage ?
{homepageMessage}
: null}

{copy.homepageSections}

{copy.homepageSectionsDescription}

{activeSections.map((section) => (
{sectionLabels[section]}
))}
{availableSections.length ? (
{availableSections.map((section) => ( ))}
) : null}

{copy.previewTitle}

{copy.previewDescription}

{homepageLanguage.toUpperCase()}

{activeContent.heroKicker}

rentaldrivego.com

{activeContent.metrics.map((metric) => ( {metric.label} ))}
{activeSections.includes('hero') ?

{activeContent.heroTitle}

{activeContent.heroBody}

{activeContent.startTrial} {activeContent.exploreVehicles}
{activeSections.includes('surface') ? (
{activeContent.surfaceLabel} {activeContent.liveLabel}
{activeContent.surfaceTitle}

{activeContent.surfaceBody}

{[activeContent.trustedFleets, activeContent.brandedFlows, activeContent.multiTenant].map((item, index) => (
{item}
))}
) : null}
: null} {activeSections.includes('surface') && !activeSections.includes('hero') ? (
{activeContent.surfaceLabel} {activeContent.liveLabel}
{activeContent.surfaceTitle}

{activeContent.surfaceBody}

) : null} {activeSections.includes('pillars') ?
{activeContent.pillars.map((pillar, index) => (

0{index + 1}

{pillar.title}

{pillar.body}

))}
: null} {activeSections.includes('audiences') ?

{activeContent.companyKicker}

{activeContent.companyTitle}

{activeContent.companyBody}

{activeContent.renterKicker}

{activeContent.renterTitle}

{activeContent.renterBody}

: null} {(activeSections.includes('features') || activeSections.includes('steps')) ?
{activeSections.includes('features') ? (

{activeContent.featureLabel}

{activeContent.features.map((feature, index) => (
{index + 1}

{feature}

))}
) :
} {activeSections.includes('steps') ? (

{activeContent.readyKicker}

{activeContent.stepsTitle}
{activeContent.steps.map((step) => (

{activeContent.stepLabel} {step.step}

{step.title}

{step.body}

))}
) :
}
: null} {activeSections.includes('closing') ?

{activeContent.readyKicker}

{activeContent.readyTitle}

{activeContent.readyBody}

{activeContent.viewPricing} {activeContent.createWorkspace}
: null}