'use client';

import { useState, useEffect, useRef } from 'react';
import { Loader2, Save, Image, Palette, Type, Upload, X, Monitor, FileText, Eye, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { useBranding } from '@client/contexts/BrandingContext';
import DemoDisabled from '@client/components/demo/DemoDisabled';

interface BrandingData {
  site_logo_url: string;
  site_favicon_url: string;
  site_primary_color: string;
  site_font_family: string;
  site_title: string;
  site_tagline: string;
  site_support_email: string;
  site_marketing_url: string;
}

const FONT_OPTIONS = [
  { label: 'Inter (default)', value: 'Inter' },
  { label: 'Poppins', value: 'Poppins' },
  { label: 'Roboto', value: 'Roboto' },
  { label: 'DM Sans', value: 'DM Sans' },
  { label: 'Plus Jakarta Sans', value: 'Plus Jakarta Sans' },
  { label: 'Nunito', value: 'Nunito' },
  { label: 'Lato', value: 'Lato' },
  { label: 'Montserrat', value: 'Montserrat' },
];

const COLOR_PRESETS = [
  { label: 'Orange', value: '#f97316' },
  { label: 'Sky', value: '#0ea5e9' },
  { label: 'Violet', value: '#8b5cf6' },
  { label: 'Emerald', value: '#10b981' },
  { label: 'Red', value: '#ef4444' },
  { label: 'Amber', value: '#f59e0b' },
  { label: 'Indigo', value: '#6366f1' },
  { label: 'Pink', value: '#ec4899' },
  { label: 'Teal', value: '#14b8a6' },
  { label: 'Slate', value: '#64748b' },
];

const DEFAULT_BRANDING: BrandingData = {
  site_logo_url: '',
  site_favicon_url: '',
  site_primary_color: '#f97316',
  site_font_family: 'Inter',
  site_title: 'RestroAgent',
  site_tagline: 'AI-powered restaurant management, simplified.',
  site_support_email: '',
  site_marketing_url: '',
};

function SectionHeader({ icon, title, description }: { icon: React.ReactNode; title: string; description: string }) {
  return (
    <div className="flex items-center gap-3 mb-5">
      <div className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
        {icon}
      </div>
      <div>
        <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{title}</p>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{description}</p>
      </div>
    </div>
  );
}

function ImageField({
  label,
  hint,
  value,
  uploadType,
  onChange,
  t,
  showPreview = false,
}: {
  label: string;
  hint: string;
  value: string;
  uploadType: 'logo' | 'favicon';
  onChange: (url: string) => void;
  t: (key: string, fallback: string) => string;
  showPreview?: boolean;
}) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('type', uploadType);
      fd.append('file', file);
      const res = await fetch('/api/admin/branding-upload', { method: 'POST', body: fd });
      const data = await res.json() as { url?: string; error?: string };
      if (!res.ok) throw new Error(data.error || t('admin.branding.uploadFailed', 'Upload failed'));
      onChange(data.url!);
      toast.success(t('admin.branding.uploaded', '{label} uploaded').replace('{label}', label));
    } catch (err: any) {
      toast.error(err.message || t('admin.branding.uploadFailed', 'Upload failed'));
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = '';
    }
  }

  return (
    <div>
      <p className="text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{label}</p>
      <p className="text-xs mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{hint}</p>
      <div className="flex gap-2">
        <input
          type="url"
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={t('admin.branding.imageUrlPlaceholder', 'https://example.com/image.png')}
          className="flex-1 min-w-0 px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
          style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
        />
        <button
          type="button"
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="flex items-center gap-1.5 px-3 py-2.5 rounded-xl text-xs font-semibold shrink-0 transition-all hover:-translate-y-0.5 disabled:opacity-60"
          style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
        >
          {uploading ? <Loader2 size={13} className="animate-spin" /> : <Upload size={13} />}
          {uploading ? t('admin.branding.uploading', 'Uploading…') : t('admin.branding.upload', 'Upload')}
        </button>
        <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
      </div>
      {value && showPreview && (
        <div className="mt-3 flex items-center gap-3 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))' }}>
          <img
            src={value}
            alt={`${label} preview`}
            className="h-10 max-w-[140px] object-contain rounded"
            onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
          />
          <div className="flex-1 min-w-0">
            <p className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.branding.preview', 'Preview')}</p>
            <p className="text-xs truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{value}</p>
          </div>
          <button
            type="button"
            onClick={() => onChange('')}
            className="shrink-0 p-1 rounded-lg hover:bg-black/5 transition-colors"
            title={t('admin.branding.remove', 'Remove')}
          >
            <X size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
          </button>
        </div>
      )}
      {value && !showPreview && (
        <div className="mt-2 flex items-center gap-2">
          <p className="text-xs truncate flex-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{value}</p>
          <button type="button" onClick={() => onChange('')} className="shrink-0" title={t('admin.branding.remove', 'Remove')}>
            <X size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
          </button>
        </div>
      )}
    </div>
  );
}

export default function AdminBrandingPage() {
  const { t } = useLanguage();
  const { refreshBranding } = useBranding();
  usePageHeader(t('admin.branding.pageTitle', 'Branding'), t('admin.branding.pageDescription', 'Customize platform identity, colors, and typography'));

  const [branding, setBranding] = useState<BrandingData>(DEFAULT_BRANDING);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const colorInputRef = useRef<HTMLInputElement>(null);

  const [demoEnabled, setDemoEnabled] = useState<boolean | null>(null);
  const [demoWritable, setDemoWritable] = useState(true);
  const [demoSaving, setDemoSaving] = useState(false);
  const [demoNeedsRestart, setDemoNeedsRestart] = useState(false);
  const [demoRestarting, setDemoRestarting] = useState(false);
  const [demoRestartFailed, setDemoRestartFailed] = useState(false);

  useEffect(() => { fetchBranding(); fetchDemoMode(); }, []);

  async function fetchDemoMode() {
    try {
      const res = await fetch('/api/admin/demo-mode');
      if (res.ok) {
        const data = await res.json() as { enabled: boolean; writable: boolean };
        setDemoEnabled(data.enabled);
        setDemoWritable(data.writable);
      }
    } catch {
      /* silent — section just won't render the toggle state */
    }
  }

  async function confirmDemoModeLive(expected: boolean, budgetMs: number): Promise<boolean> {
    const deadline = Date.now() + budgetMs;
    while (Date.now() < deadline) {
      try {
        const res = await fetch('/api/admin/demo-mode', { cache: 'no-store' });
        if (res.ok) {
          const data = (await res.json()) as { enabled?: boolean };
          if (data.enabled === expected) return true;
        }
      } catch {
        /* keep polling — server may still be settling */
      }
      await new Promise(r => setTimeout(r, 500));
    }
    return false;
  }

  async function waitForServerHealth(budgetMs: number): Promise<boolean> {
    const deadline = Date.now() + budgetMs;
    // Wait briefly so the existing process has a chance to exit before we start polling.
    await new Promise(r => setTimeout(r, 800));
    while (Date.now() < deadline) {
      try {
        const res = await fetch('/api/health', { cache: 'no-store' });
        if (res.ok) return true;
      } catch {
        /* server is mid-restart — keep polling */
      }
      await new Promise(r => setTimeout(r, 500));
    }
    return false;
  }

  async function toggleDemoMode(next: boolean) {
    setDemoSaving(true);
    setDemoRestartFailed(false);
    try {
      const res = await fetch('/api/admin/demo-mode', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: next }),
      });
      const data = await res.json() as {
        enabled?: boolean;
        error?: string;
        restartScheduled?: boolean;
      };
      if (!res.ok) {
        toast.error(data.error || t('admin.demoMode.failedToSave', 'Failed to update Demo Mode'));
        return;
      }
      setDemoEnabled(data.enabled ?? next);

      if (data.restartScheduled) {
        setDemoRestarting(true);
        const healthy = await waitForServerHealth(30_000);
        if (healthy) {
          // Verify the new env value is actually live on the re-spawned
          // process before reloading, so we don't reload onto a stale
          // bundle if the first health 200 happened to come from the old
          // process.
          const confirmed = await confirmDemoModeLive(next, 15_000);
          if (confirmed) {
            window.location.reload();
            return;
          }
          setDemoRestarting(false);
          setDemoRestartFailed(true);
          setDemoNeedsRestart(true);
          toast.error(t('admin.demoMode.restartTimeout', 'Server did not respond after restart. Please restart the workflow manually.'));
          return;
        }
        setDemoRestarting(false);
        setDemoRestartFailed(true);
        setDemoNeedsRestart(true);
        toast.error(t('admin.demoMode.restartTimeout', 'Server did not respond after restart. Please restart the workflow manually.'));
        return;
      }

      setDemoNeedsRestart(true);
      toast.success(t('admin.demoMode.saved', 'Saved. Restart (and on production, rebuild) the server for the change to take effect.'));
    } catch {
      toast.error(t('admin.demoMode.failedToSave', 'Failed to update Demo Mode'));
    } finally {
      setDemoSaving(false);
    }
  }

  async function fetchBranding() {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/branding');
      if (res.ok) {
        const data = await res.json() as { branding: Partial<BrandingData> };
        setBranding(prev => ({ ...prev, ...data.branding }));
      }
    } catch {
      toast.error(t('admin.branding.failedToLoad', 'Failed to load branding settings'));
    } finally {
      setLoading(false);
    }
  }

  async function handleSave() {
    setSaving(true);
    try {
      const res = await fetch('/api/admin/branding', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(branding),
      });
      if (res.ok) {
        toast.success(t('admin.branding.saved', 'Branding settings saved'));
        void refreshBranding();
      } else {
        const data = await res.json() as { error?: string };
        toast.error(data.error || t('admin.branding.failedToSave', 'Failed to save branding'));
      }
    } catch {
      toast.error(t('admin.branding.failedToSave', 'Failed to save branding settings'));
    } finally {
      setSaving(false);
    }
  }

  function set(key: keyof BrandingData, value: string) {
    setBranding(prev => ({ ...prev, [key]: value }));
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 size={24} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />
      </div>
    );
  }

  const tabPreview = [branding.site_tagline, branding.site_title].filter(Boolean).join(' — ') || 'RestroAgent';

  return (
    <div className="max-w-2xl mx-auto px-4 py-6 space-y-6">

      {/* ── Identity ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Image size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.identity', 'Identity')}
          description={t('admin.branding.identityDescription', 'Logo and favicon shown across the platform and public pages')}
        />
        <div className="space-y-5">
          <ImageField
            label={t('admin.branding.platformLogo', 'Platform Logo')}
            hint={t('admin.branding.platformLogoHint', 'Shown in the navbar, login page, and sidebar. SVG or PNG recommended.')}
            value={branding.site_logo_url}
            uploadType="logo"
            onChange={v => set('site_logo_url', v)}
            t={t}
            showPreview
          />
          <div className="border-t" style={{ borderColor: 'hsl(var(--border))' }} />
          <ImageField
            label={t('admin.branding.favicon', 'Favicon')}
            hint={t('admin.branding.faviconHint', 'Browser tab icon. PNG 32×32 or WEBP recommended. Provide a URL for ICO/SVG. Leave blank to use the platform logo.')}
            value={branding.site_favicon_url}
            uploadType="favicon"
            onChange={v => set('site_favicon_url', v)}
            t={t}
            showPreview={false}
          />
          {branding.site_favicon_url && (
            <button
              type="button"
              onClick={() => set('site_favicon_url', '')}
              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors hover:bg-black/5"
              style={{ color: 'hsl(var(--muted-foreground))', border: '1px solid hsl(var(--border))' }}
              title={t('admin.branding.clearFaviconHint', 'Removes the custom favicon so the platform logo is used in browser tabs')}
            >
              <X size={12} />
              {t('admin.branding.clearFavicon', 'Clear favicon (use logo)')}
            </button>
          )}
        </div>
      </div>

      {/* ── Site Info ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Monitor size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.siteInfo', 'Site Info')}
          description={t('admin.branding.siteInfoDescription', 'Title and tagline shown in browser tabs and public pages')}
        />
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.siteTitle', 'Site Title')}</label>
            <input
              type="text"
              value={branding.site_title}
              onChange={e => set('site_title', e.target.value)}
              placeholder={t('admin.branding.siteTitlePlaceholder', 'RestroAgent')}
              maxLength={60}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.tagline', 'Tagline')}</label>
            <input
              type="text"
              value={branding.site_tagline}
              onChange={e => set('site_tagline', e.target.value)}
              placeholder={t('admin.branding.taglinePlaceholder', 'AI-powered restaurant management, simplified.')}
              maxLength={120}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.supportEmail', 'Support Email')}</label>
            <input
              type="email"
              value={branding.site_support_email}
              onChange={e => set('site_support_email', e.target.value)}
              placeholder={t('admin.branding.supportEmailPlaceholder', 'support@example.com')}
              maxLength={120}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
            <p className="mt-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.branding.supportEmailHint', 'Used in legal pages, support links, and outbound email "from" fallback. Leave empty to omit.')}
            </p>
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.marketingUrl', 'Marketing Site URL')}</label>
            <input
              type="url"
              value={branding.site_marketing_url}
              onChange={e => set('site_marketing_url', e.target.value)}
              placeholder={t('admin.branding.marketingUrlPlaceholder', 'https://your-site.com')}
              maxLength={200}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
            <p className="mt-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.branding.marketingUrlHint', 'Used by the "Powered by" link in chat widgets. Defaults to this deployment\'s URL when empty.')}
            </p>
          </div>
          <div className="flex items-center gap-2 px-3 py-2 rounded-xl" style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))' }}>
            <FileText size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.branding.browserTabPreview', 'Browser tab preview')}: <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{tabPreview}</span>
            </p>
          </div>
        </div>
      </div>

      {/* ── Appearance ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Palette size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.appearance', 'Appearance')}
          description={t('admin.branding.appearanceDescription', 'Primary brand color used across landing pages, buttons, and accents')}
        />
        <div className="flex items-center gap-3 mb-3">
          <button
            type="button"
            onClick={() => colorInputRef.current?.click()}
            className="w-11 h-11 rounded-xl border-2 flex-shrink-0 transition-transform hover:scale-105 shadow-sm"
            style={{ backgroundColor: branding.site_primary_color, borderColor: 'hsl(var(--border))' }}
            title={t('admin.branding.openColorPicker', 'Open color picker')}
          />
          <input
            ref={colorInputRef}
            type="color"
            value={branding.site_primary_color}
            onChange={e => set('site_primary_color', e.target.value)}
            className="sr-only"
          />
          <input
            type="text"
            value={branding.site_primary_color}
            onChange={e => set('site_primary_color', e.target.value)}
            placeholder="#f97316"
            maxLength={7}
            className="flex-1 px-3 py-2.5 rounded-xl text-sm font-mono transition-all duration-200"
            style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
          />
        </div>
        <div className="flex flex-wrap gap-2">
          {COLOR_PRESETS.map(({ label, value }) => (
            <button
              key={value}
              type="button"
              onClick={() => set('site_primary_color', value)}
              className="w-7 h-7 rounded-lg border-2 transition-all hover:scale-110"
              style={{
                backgroundColor: value,
                borderColor: branding.site_primary_color === value ? 'hsl(var(--foreground))' : 'transparent',
                boxShadow: branding.site_primary_color === value ? '0 0 0 2px white, 0 0 0 3px ' + value : undefined,
              }}
              title={label}
            />
          ))}
        </div>
      </div>

      {/* ── Typography ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Type size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.typography', 'Typography')}
          description={t('admin.branding.typographyDescription', 'Primary typeface applied to the landing pages and public-facing UI')}
        />
        <select
          value={branding.site_font_family}
          onChange={e => set('site_font_family', e.target.value)}
          className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
          style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
        >
          {FONT_OPTIONS.map(f => (
            <option key={f.value} value={f.value}>{f.label}</option>
          ))}
        </select>
        <p className="mt-3 text-sm px-1" style={{ fontFamily: branding.site_font_family, color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.branding.typographyPreview', 'Preview: The quick brown fox jumps over the lazy dog.')}
        </p>
      </div>

      {/* ── Demo Mode ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Eye size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.demoMode.title', 'Demo Mode')}
          description={t('admin.demoMode.description', 'Show public /demo and demo discoverability (login hints, home CTA, self-bootstrap seeding).')}
        />
        <div className="flex items-start gap-4">
          <div className="flex-1 min-w-0">
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.demoMode.help', 'When on, the public /demo page is reachable, demo credentials appear on the login screen, and the home hero shows a “See it in action” CTA. Leave off for buyer deployments.')}
            </p>
            {!demoWritable && (
              <p className="mt-2 text-xs font-medium" style={{ color: 'hsl(var(--destructive, 0 84% 60%))' }}>
                {t('admin.demoMode.envWriteDisabled', 'Editing the .env file is disabled on this deployment (DISABLE_ENV_WRITE=1).')}
              </p>
            )}
          </div>
          <button
            type="button"
            role="switch"
            aria-checked={demoEnabled === true}
            disabled={demoEnabled === null || demoSaving || demoRestarting || !demoWritable}
            onClick={() => toggleDemoMode(!demoEnabled)}
            className="relative inline-flex items-center h-7 w-12 rounded-full shrink-0 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
            style={{ backgroundColor: demoEnabled ? 'hsl(var(--primary))' : 'hsl(var(--border))' }}
          >
            <span
              className="inline-block h-5 w-5 rounded-full bg-white shadow transform transition-transform"
              style={{ transform: demoEnabled ? 'translateX(22px)' : 'translateX(4px)' }}
            />
            {demoSaving && (
              <Loader2 size={12} className="animate-spin absolute -right-5 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
            )}
          </button>
        </div>
        {demoRestarting && (
          <div className="mt-4 flex items-start gap-2 px-3 py-2.5 rounded-xl" style={{ backgroundColor: 'hsl(210 100% 97%)', border: '1px solid hsl(210 90% 80%)' }}>
            <Loader2 size={14} className="animate-spin mt-0.5 shrink-0" style={{ color: 'hsl(210 80% 45%)' }} />
            <p className="text-xs" style={{ color: 'hsl(210 60% 25%)' }}>
              {t('admin.demoMode.restartingBanner', 'Restarting server… this usually takes a few seconds. The page will reload automatically when ready.')}
            </p>
          </div>
        )}
        {demoNeedsRestart && !demoRestarting && (
          <div className="mt-4 flex items-start gap-2 px-3 py-2.5 rounded-xl" style={{ backgroundColor: 'hsl(48 100% 96%)', border: '1px solid hsl(45 90% 75%)' }}>
            <AlertTriangle size={14} style={{ color: 'hsl(35 90% 40%)' }} className="mt-0.5 shrink-0" />
            <p className="text-xs" style={{ color: 'hsl(35 60% 25%)' }}>
              {demoRestartFailed
                ? t('admin.demoMode.restartFailedBanner', 'Auto-restart did not complete in time. Please restart the workflow manually for the change to take effect.')
                : t('admin.demoMode.restartBanner', 'Restart the server for this change to take effect. On production deployments, a rebuild/redeploy is required because NEXT_PUBLIC_DEMO_MODE is inlined into the client bundle at build time. On Replit, also update the matching Repl secret so the value survives rebuilds.')}
            </p>
          </div>
        )}
      </div>

      {/* ── Save ── */}
      <div className="flex items-center justify-between pt-1">
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.branding.saveNotice', 'Changes apply to public-facing pages after save.')}
        </p>
        <DemoDisabled>
          <button
            onClick={handleSave}
            disabled={saving}
            className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200 hover:-translate-y-0.5 disabled:opacity-60 disabled:cursor-not-allowed"
            style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}
          >
            {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
            {saving ? t('admin.branding.saving', 'Saving…') : t('admin.branding.saveBranding', 'Save Branding')}
          </button>
        </DemoDisabled>
      </div>
    </div>
  );
}
