'use client'; import { useState, useEffect } from 'react'; import Link from 'next/link'; import { settingsApi, type AboutInfo, type StoreSettings } from '@/lib/api-client'; type FormData = StoreSettings; const TABS = [ { id: 'general', label: 'General', icon: '⚙️' }, { id: 'social', label: 'Redes sociales', icon: '🌐' }, { id: 'footer', label: 'Footer', icon: '📄' }, { id: 'ai', label: 'IA para SEO', icon: '✨' }, { id: 'smtp', label: 'SMTP / Email', icon: '✉️' }, { id: 'couriers', label: 'Transportistas', icon: '🚚' }, { id: 'about', label: 'About', icon: 'ℹ️' }, ] as const; type TabId = (typeof TABS)[number]['id']; export default function SettingsPage() { const [data, setData] = useState(null); const [form, setForm] = useState(null); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [msg, setMsg] = useState(''); const [err, setErr] = useState(''); const [tab, setTab] = useState('general'); const [couriersText, setCouriersText] = useState(''); const [about, setAbout] = useState(null); const [aboutLoading, setAboutLoading] = useState(false); const loadAbout = async () => { setAboutLoading(true); try { setAbout(await settingsApi.about()); } catch { setErr('Error al cargar información del sistema'); } finally { setAboutLoading(false); } }; useEffect(() => { Promise.all([ settingsApi.get().then(d => { setData(d); setForm(d); setCouriersText((d.couriers ?? []).join('\n')); }), loadAbout(), ]).catch(() => setErr('Error al cargar ajustes')).finally(() => setLoading(false)); }, []); const handleCouriersChange = (text: string) => { setCouriersText(text); const list = text.split('\n').map(c => c.trim()).filter(Boolean).slice(0, 30); setForm(f => f ? { ...f, couriers: list } : f); }; const formatDuration = (seconds: number) => { const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor((seconds % 3600) / 60); if (days > 0) return `${days}d ${hours}h ${minutes}m`; if (hours > 0) return `${hours}h ${minutes}m`; return `${minutes}m`; }; const infoRow = (label: string, value: string | number) => (

{label}

{value}

); const handleSave = async (e: React.FormEvent) => { e.preventDefault(); if (!form) return; setSaving(true); setErr(''); setMsg(''); try { const { aiApiKey, smtpPass, ...settingsWithoutSecrets } = form; const updated = await settingsApi.update({ ...settingsWithoutSecrets, ...(aiApiKey ? { aiApiKey } : {}), ...(smtpPass ? { smtpPass } : {}), }); setData(updated); setForm(updated); setMsg('Cambios guardados correctamente'); setTimeout(() => setMsg(''), 4000); } catch (er) { setErr(er instanceof Error ? er.message : 'Error al guardar'); } finally { setSaving(false); } }; const field = (key: Exclude, label: string, opts?: { type?: string; placeholder?: string; rows?: number; hint?: string }) => (
{opts?.rows ? (