import React, { useEffect, useRef, useState } from 'react' import { Paintbrush, Eye, LayoutDashboard, Sun, Moon, Monitor, RotateCcw } from 'lucide-react' import { useTranslation } from '../../i18n' import { useSettingsStore } from '../../store/settingsStore' import { useToast } from '../shared/Toast' import Section from './Section' import ToggleSwitch from './ToggleSwitch' import { applyAppearance } from '../../theme/applyAppearance' import { APPEARANCE_SCHEMES, CUSTOM_ACCENT_PRESETS } from '../../theme/schemes' import { DEFAULT_APPEARANCE, normalizeAppearance, APPEARANCE_SCALE_MIN, APPEARANCE_SCALE_MAX, type AppearanceConfig, } from '@trek/shared' // ── WCAG contrast helpers (for the custom-accent legibility hint) ──────────── function channelLum(v: number): number { return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4) } function relLuminance(hex: string): number { const c = hex.replace('#', '') const full = c.length === 3 ? c.split('').map((x) => x + x).join('') : c const r = channelLum(Number.parseInt(full.slice(0, 2), 16) / 255) const g = channelLum(Number.parseInt(full.slice(2, 4), 16) / 255) const b = channelLum(Number.parseInt(full.slice(4, 6), 16) / 255) return 0.2126 * r + 0.7152 * g + 0.0722 * b } function contrastRatio(a: string, b: string): number { const la = relLuminance(a) const lb = relLuminance(b) const [hi, lo] = la > lb ? [la, lb] : [lb, la] return (hi + 0.05) / (lo + 0.05) } const isHex = (v: string) => /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(v) type DesktopWidgetKey = keyof AppearanceConfig['dashboard']['desktop'] type MobileWidgetKey = keyof AppearanceConfig['dashboard']['mobile'] const WIDGET_LABELS: Record = { sidebar: 'Right sidebar', currency: 'Currency', collections: 'Collections', timezones: 'Timezones', upcomingReservations: 'Upcoming reservations', atlas: 'Atlas / countries', tripsTotal: 'Trips total', daysTraveled: 'Days traveled', distanceFlown: 'Distance flown', } // Grouped by where the widgets actually sit on the dashboard. The right sidebar // has a master toggle (off → no sidebar, layout centers); its individual // widgets only matter while the sidebar is shown. const DESKTOP_GROUPS: { id: string; fallback: string; master?: DesktopWidgetKey; keys: DesktopWidgetKey[] }[] = [ { id: 'belowHero', fallback: 'Below the hero', keys: ['atlas', 'tripsTotal', 'daysTraveled', 'distanceFlown'] }, { id: 'rightSidebar', fallback: 'Right sidebar', master: 'sidebar', keys: ['currency', 'collections', 'timezones', 'upcomingReservations'] }, ] const MOBILE_GROUPS: { id: string; fallback: string; keys: MobileWidgetKey[] }[] = [ { id: 'belowHero', fallback: 'Below the hero', keys: ['tripsTotal', 'daysTraveled'] }, { id: 'bottomOfPage', fallback: 'Bottom of page', keys: ['currency', 'collections', 'timezones', 'upcomingReservations'] }, ] // shared segmented-button style (matches DisplaySettingsTab) function segStyle(active: boolean): React.CSSProperties { return { display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center', padding: '10px 14px', borderRadius: 10, cursor: 'pointer', flex: '1 1 0', minWidth: 0, fontFamily: 'inherit', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 500, border: active ? '2px solid var(--text-primary)' : '2px solid var(--border-primary)', background: active ? 'var(--bg-hover)' : 'var(--bg-card)', color: 'var(--text-primary)', transition: 'all 0.15s', } } export default function AppearanceSettingsTab(): React.ReactElement { const { settings, updateSetting } = useSettingsStore() const { t } = useTranslation() const toast = useToast() const tr = (key: string, fallback: string) => t(key) || fallback const [cfg, setCfg] = useState(() => normalizeAppearance(settings.appearance)) const persistTimer = useRef(undefined) // What the pending timer would have written, so leaving the tab inside the // debounce window still saves instead of silently dropping the change. const pendingWrite = useRef(null) // Re-sync when settings change elsewhere (e.g. server reconcile / another tab). useEffect(() => { setCfg(normalizeAppearance(settings.appearance)) }, [settings.appearance]) // Flush any pending persist on unmount. useEffect(() => () => { if (!persistTimer.current) return window.clearTimeout(persistTimer.current) // The component is gone, so a failure has nowhere to be shown. if (pendingWrite.current) updateSetting('appearance', pendingWrite.current).catch(() => {}) }, [updateSetting]) const isDark = settings.dark_mode === true || settings.dark_mode === 'dark' || (settings.dark_mode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) // Live preview now (DOM), persist after a short debounce (API). const update = (patch: Partial) => { const next = { ...cfg, ...patch } setCfg(next) applyAppearance({ darkMode: settings.dark_mode, appearance: next, isSharedPage: false }) if (persistTimer.current) window.clearTimeout(persistTimer.current) pendingWrite.current = next persistTimer.current = window.setTimeout(() => { pendingWrite.current = null updateSetting('appearance', next).catch((e: unknown) => toast.error(e instanceof Error ? e.message : t('common.error')) ) }, 350) } const setMode = async (mode: string) => { try { await updateSetting('dark_mode', mode) } catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('common.error')) } } const setWidget = (device: 'desktop' | 'mobile', key: string, on: boolean) => { update({ dashboard: { ...cfg.dashboard, [device]: { ...cfg.dashboard[device], [key]: on }, }, }) } const resetAll = () => update({ ...DEFAULT_APPEARANCE }) const accentLight = cfg.accent?.light ?? '#4f46e5' const accentDark = cfg.accent?.dark ?? '#6366f1' const customRatio = contrastRatio(isDark ? accentDark : accentLight, isDark ? '#ffffff' : '#ffffff') return ( <> {/* ── Theme ───────────────────────────────────────────────── */}
{/* Color mode */}
{[ { value: 'light', label: tr('settings.light', 'Light'), icon: Sun }, { value: 'dark', label: tr('settings.dark', 'Dark'), icon: Moon }, { value: 'auto', label: tr('settings.auto', 'Auto'), icon: Monitor }, ].map((opt) => { const cur = settings.dark_mode const active = cur === opt.value || (opt.value === 'light' && cur === false) || (opt.value === 'dark' && cur === true) return ( ) })}
{/* Color scheme swatches */}
{APPEARANCE_SCHEMES.map((s) => { const active = cfg.schemeId === s.id const dot = isDark ? s.swatch.dark : s.swatch.light return ( ) })} {/* Custom */}
{/* Custom accent picker */} {cfg.schemeId === 'custom' && (
{CUSTOM_ACCENT_PRESETS.map((c) => (
= 4.5 ? 'var(--success-soft)' : 'var(--warning-soft)', color: customRatio >= 4.5 ? 'var(--success)' : 'var(--warning)' }} > {customRatio >= 4.5 ? `${tr('settings.appearance.contrastOk', 'Good contrast')} (${customRatio.toFixed(1)}:1)` : `${tr('settings.appearance.contrastLow', 'Low contrast')} (${customRatio.toFixed(1)}:1)`}
)}
{/* ── Readability ─────────────────────────────────────────── */}
{tr('settings.appearance.experimental', 'Experimental')} } > update({ transparency: !cfg.transparency })} /> update({ reduceMotion: !cfg.reduceMotion })} /> {/* Density */}
{[ { value: 'comfortable', label: tr('settings.appearance.comfortable', 'Comfortable') }, { value: 'compact', label: tr('settings.appearance.compact', 'Compact') }, ].map((opt) => ( ))}

{tr('settings.appearance.densityHint', 'Compact tightens spacing and padding for a denser layout that fits more on screen.')}

{/* Text size — global, plus an always-visible row per size class with a live sample and an example of what each size affects. */}
update({ fontScale: v })} />
update({ typeScale: { ...cfg.typeScale, title: v } })} /> update({ typeScale: { ...cfg.typeScale, subtitle: v } })} /> update({ typeScale: { ...cfg.typeScale, body: v } })} /> update({ typeScale: { ...cfg.typeScale, caption: v } })} />
{/* ── Dashboard widgets ───────────────────────────────────── */}

{tr('settings.appearance.dashboardWidgetsHint', 'Choose which widgets appear on the dashboard — independently for desktop and mobile.')}

{tr('settings.appearance.desktop', 'Desktop')}
{DESKTOP_GROUPS.map((g) => { const masterOn = g.master ? cfg.dashboard.desktop[g.master] : true return (
{g.master ? ( setWidget('desktop', g.master as string, !masterOn)} /> ) : (
{tr(`settings.appearance.group.${g.id}`, g.fallback)}
)}
{g.keys.map((k) => ( setWidget('desktop', k, !cfg.dashboard.desktop[k])} /> ))}
) })}
{tr('settings.appearance.mobile', 'Mobile')}
{MOBILE_GROUPS.map((g) => (
{tr(`settings.appearance.group.${g.id}`, g.fallback)}
{g.keys.map((k) => ( setWidget('mobile', k, !cfg.dashboard.mobile[k])} /> ))}
))}
) } function schemeFallback(id: string): string { const map: Record = { default: 'Default', highContrast: 'High contrast', indigo: 'Indigo', teal: 'Teal', rose: 'Rose', amber: 'Amber', violet: 'Violet', } return map[id] || id } function ToggleRow({ label, hint, on, onToggle }: { label: string; hint?: string; on: boolean; onToggle: () => void }) { return (
{label}
{hint &&
{hint}
}
) } function SliderRow({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) { return (
{label} {Math.round(value * 100)}%
onChange(Number(e.target.value))} className="trek-range" style={{ '--fill': `${((value - APPEARANCE_SCALE_MIN) / (APPEARANCE_SCALE_MAX - APPEARANCE_SCALE_MIN)) * 100}%` } as React.CSSProperties} />
) } function SizeRow({ sampleClass, name, example, sample, value, onChange }: { sampleClass: string; name: string; example: string; sample: string; value: number; onChange: (v: number) => void }) { return (
{sample}
{name} · {example}
{Math.round(value * 100)}%
onChange(Number(e.target.value))} className="trek-range" style={{ '--fill': `${((value - APPEARANCE_SCALE_MIN) / (APPEARANCE_SCALE_MAX - APPEARANCE_SCALE_MIN)) * 100}%` } as React.CSSProperties} />
) }