'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import {
  Copy, Check, Palette, RefreshCw,
  Loader2, Bot, Zap, Code, Info,
  Sparkles, AlertCircle, CheckCircle2, Upload, X,
} from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@client/contexts/AuthContext';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface WidgetSettings {
  primary_color: string;
  welcome_message: string;
  placeholder_text: string;
  position: string;
  auto_open_delay: number;
  bot_name: string;
  is_enabled: boolean;
  agent_id: string | null;
  icon_url?: string | null;
}

interface Agent {
  id: string;
  name: string;
  description?: string;
  is_default: boolean;
  model_id?: string;
  channels: string[];
  branch_id?: string;
}

const DEFAULT_SETTINGS: WidgetSettings = {
  primary_color: '#f97316',
  welcome_message: 'Hi! How can we help you today? 👋',
  placeholder_text: 'Type your message...',
  position: 'bottom-right',
  auto_open_delay: 0,
  bot_name: 'AI Assistant',
  is_enabled: true,
  agent_id: null,
  icon_url: null,
};

const PRESET_COLORS = [
  '#f97316', '#ef4444', '#8b5cf6', '#3b82f6', '#10b981',
  '#f59e0b', '#ec4899', '#14b8a6', '#6366f1', '#84cc16',
];

export default function WidgetSettingsPage() {
  const { t } = useLanguage();
  usePageHeader(t('widgetSettings.title', 'Chat Widget'), t('widgetSettings.subtitle', 'Embed an AI chat assistant on your restaurant website'));
  const { restaurantId } = useAuth();

  const [settings, setSettings] = useState<WidgetSettings>(DEFAULT_SETTINGS);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const [activeTab, setActiveTab] = useState<'settings' | 'agent' | 'embed'>('settings');
  const [previewKey, setPreviewKey] = useState(0);
  const [iconUploading, setIconUploading] = useState(false);
  const iconInputRef = useRef<HTMLInputElement>(null);

  const loadSettings = useCallback(async () => {
    if (!restaurantId) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/widget/settings?restaurantId=${restaurantId}&includeAgents=true`);
      if (res.ok) {
        const data = await res.json();
        if (data.settings) setSettings({ ...DEFAULT_SETTINGS, ...data.settings });
        if (data.agents) setAgents(data.agents);
      }
    } catch {
    } finally {
      setLoading(false);
    }
  }, [restaurantId]);

  useEffect(() => { loadSettings(); }, [loadSettings]);

  const handleSave = async () => {
    if (!restaurantId) return;
    setSaving(true);
    try {
      const res = await fetch('/api/widget/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(settings),
      });
      if (!res.ok) throw new Error('Failed to save');
      toast.success(t('widgetSettings.saved', 'Widget settings saved'));
    } catch (err: any) {
      toast.error(t('widgetSettings.failedToSave', 'Failed to save') + ': ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleIconUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) {
      toast.error(t('widgetSettings.imageTooLarge', 'Image must be 2 MB or smaller'));
      return;
    }
    setIconUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch('/api/widget/icon-upload', { method: 'POST', body: fd });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || 'Upload failed');
      }
      const { url } = await res.json();
      setSettings(s => ({ ...s, icon_url: url }));
      toast.success(t('widgetSettings.iconUploaded', 'Icon uploaded — save to apply'));
    } catch (err: any) {
      toast.error(err.message || 'Upload failed');
    } finally {
      setIconUploading(false);
      if (iconInputRef.current) iconInputRef.current.value = '';
    }
  };

  const origin = typeof window !== 'undefined' ? window.location.origin : '';
  const embedCode = restaurantId
    ? `<script src="${origin}/api/widget/embed.js?rid=${restaurantId}" async></script>`
    : '';

  const handleCopy = () => {
    const single = embedCode.replace(/\n/g, ' ').replace(/\s+/g, ' ');
    navigator.clipboard.writeText(single).then(() => {
      setCopied(true);
      toast.success(t('widgetSettings.embedCopied', 'Embed code copied!'));
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const selectedAgent = agents.find(a => a.id === settings.agent_id);

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

  const tabs = [
    { key: 'settings', label: t('widgetSettings.tabs.appearance', 'Appearance'), icon: Palette },
    { key: 'agent', label: t('widgetSettings.tabs.behavior', 'AI Agent'), icon: Bot },
    { key: 'embed', label: t('widgetSettings.tabs.installation', 'Embed'), icon: Code },
  ] as const;

  return (
    <div className="flex flex-col xl:flex-row gap-6">
      {/* Left panel — controls */}
      <div className="flex-1 min-w-0 space-y-5">

        {/* Status banner */}
        <div
          className="flex items-center justify-between p-4 rounded-2xl"
          style={{
            backgroundColor: settings.is_enabled ? 'hsl(var(--success-bg))' : 'hsl(var(--muted))',
            border: `1px solid ${settings.is_enabled ? 'hsl(var(--success-border))' : 'hsl(var(--border))'}`,
          }}
        >
          <div className="flex items-center gap-3">
            {settings.is_enabled
              ? <CheckCircle2 size={18} style={{ color: 'hsl(var(--success))' }} />
              : <AlertCircle size={18} style={{ color: 'hsl(var(--muted-foreground))' }} />}
            <div>
              <p className="text-sm font-semibold" style={{ color: settings.is_enabled ? 'hsl(var(--success))' : 'hsl(var(--foreground))' }}>
                {settings.is_enabled ? t('widgetSettings.status.enabled', 'Widget is enabled') : t('widgetSettings.status.disabled', 'Widget is disabled')}
              </p>
              <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {settings.is_enabled ? t('widgetSettings.status.enabledSubtitle', 'Visitors on your website will see the chat bubble') : t('widgetSettings.status.disabledSubtitle', 'The widget will not appear on your website')}
              </p>
            </div>
          </div>
          <label className="relative inline-flex items-center cursor-pointer flex-shrink-0">
            <input type="checkbox" checked={settings.is_enabled} onChange={e => setSettings(s => ({ ...s, is_enabled: e.target.checked }))} className="sr-only" />
            <div className="w-11 h-6 rounded-full transition-colors relative" style={{ backgroundColor: settings.is_enabled ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
              <div className="absolute top-1 w-4 h-4 bg-white rounded-full shadow transition-transform" style={{ left: settings.is_enabled ? '24px' : '4px' }} />
            </div>
          </label>
        </div>

        {/* Tab nav */}
        <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {tabs.map(tab => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium flex-1 justify-center transition-all"
                style={{
                  backgroundColor: activeTab === tab.key ? 'white' : 'transparent',
                  color: activeTab === tab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))',
                  boxShadow: activeTab === tab.key ? 'var(--shadow-sm)' : 'none',
                }}
              >
                <Icon size={13} /> {tab.label}
              </button>
            );
          })}
        </div>

        {/* ── APPEARANCE tab ── */}
        {activeTab === 'settings' && (
          <div className="space-y-4">
            <div className="card p-5 space-y-5">
              <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.brandingTitle', 'Branding')}</h3>

              <div>
                <label className="text-xs font-medium mb-2 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.botNameLabel', 'Bot / Widget Name')}</label>
                <input className="input-base" value={settings.bot_name} onChange={e => setSettings(s => ({ ...s, bot_name: e.target.value }))} placeholder={t('widgetSettings.appearance.botNamePlaceholder', 'AI Assistant')} maxLength={50} />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('widgetSettings.appearance.botNameSubtitle', 'Displayed in the chat header')}</p>
              </div>

              <div>
                <label className="text-xs font-medium mb-2 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.botIconLabel', 'Bot Icon')}</label>
                <div className="flex items-center gap-4">
                  <div
                    className="w-12 h-12 rounded-full flex items-center justify-center text-2xl flex-shrink-0 overflow-hidden"
                    style={{ background: settings.icon_url ? 'transparent' : settings.primary_color + '22', border: `2px solid ${settings.primary_color}` }}
                  >
                    {settings.icon_url
                      ? <img src={settings.icon_url} alt={t('widgetSettings.appearance.botIconAlt', 'Bot icon')} className="w-full h-full object-cover rounded-full" />
                      : <span>&#x1F37D;&#xFE0F;</span>}
                  </div>
                  <div className="flex flex-col gap-2">
                    <input
                      ref={iconInputRef}
                      type="file"
                      accept="image/png,image/jpeg,image/gif,image/webp"
                      className="hidden"
                      onChange={handleIconUpload}
                    />
                    <button
                      className="btn-ghost text-xs flex items-center gap-1.5 px-3 py-1.5"
                      onClick={() => iconInputRef.current?.click()}
                      disabled={iconUploading}
                    >
                      {iconUploading ? <Loader2 size={12} className="animate-spin" /> : <Upload size={12} />}
                      {iconUploading ? t('common.uploading', 'Uploading…') : t('widgetSettings.appearance.uploadIcon', 'Upload Icon')}
                    </button>
                    {settings.icon_url && (
                      <button
                        className="btn-ghost text-xs flex items-center gap-1.5 px-3 py-1.5"
                        style={{ color: 'hsl(var(--danger))' }}
                        onClick={() => setSettings(s => ({ ...s, icon_url: null }))}
                      >
                        <X size={12} /> {t('common.remove', 'Remove')}
                      </button>
                    )}
                  </div>
                </div>
                <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('widgetSettings.appearance.iconSubtitle', 'PNG, JPEG, GIF or WEBP · Max 2 MB · Save to apply')}</p>
              </div>

              <div>
                <label className="text-xs font-medium mb-2 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.accentColorLabel', 'Accent Color')}</label>
                <div className="flex items-center gap-3 flex-wrap">
                  {PRESET_COLORS.map(color => (
                    <button
                      key={color}
                      onClick={() => setSettings(s => ({ ...s, primary_color: color }))}
                      className="w-7 h-7 rounded-full transition-transform"
                      style={{
                        backgroundColor: color,
                        transform: settings.primary_color === color ? 'scale(1.2)' : 'scale(1)',
                        border: settings.primary_color === color ? '2px solid hsl(var(--foreground))' : '2px solid transparent',
                        boxShadow: settings.primary_color === color ? '0 0 0 2px white inset' : 'none',
                      }}
                    />
                  ))}
                  <div className="flex items-center gap-2">
                    <input type="color" value={settings.primary_color} onChange={e => setSettings(s => ({ ...s, primary_color: e.target.value }))} className="w-8 h-8 rounded-lg cursor-pointer border-0 p-0" style={{ border: '1px solid hsl(var(--border))' }} />
                    <span className="text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{settings.primary_color}</span>
                  </div>
                </div>
              </div>

              <div>
                <label className="text-xs font-medium mb-2 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.positionLabel', 'Widget Position')}</label>
                <div className="grid grid-cols-2 gap-2">
                  {(['bottom-right', 'bottom-left'] as const).map(pos => (
                    <button
                      key={pos}
                      onClick={() => setSettings(s => ({ ...s, position: pos }))}
                      className="px-3 py-2.5 rounded-xl text-xs font-medium transition-all border"
                      style={{
                        backgroundColor: settings.position === pos ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                        color: settings.position === pos ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
                        borderColor: settings.position === pos ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      }}
                    >
                      {pos === 'bottom-right' ? t('widgetSettings.appearance.bottomRight', '↘ Bottom Right') : t('widgetSettings.appearance.bottomLeft', '↙ Bottom Left')}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div className="card p-5 space-y-4">
              <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.messagingTitle', 'Messaging')}</h3>

              <div>
                <label className="text-xs font-medium mb-1.5 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.welcomeMessageLabel', 'Welcome Message')}</label>
                <textarea
                  className="input-base resize-none"
                  rows={2}
                  value={settings.welcome_message}
                  onChange={e => setSettings(s => ({ ...s, welcome_message: e.target.value }))}
                  placeholder={t('widgetSettings.appearance.welcomeMessagePlaceholder', 'Hi! How can we help you today?')}
                  maxLength={200}
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{settings.welcome_message.length}/200 {t('common.characters', 'characters')}</p>
              </div>

              <div>
                <label className="text-xs font-medium mb-1.5 block" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.appearance.placeholderLabel', 'Input Placeholder')}</label>
                <input className="input-base" value={settings.placeholder_text} onChange={e => setSettings(s => ({ ...s, placeholder_text: e.target.value }))} placeholder={t('widgetSettings.appearance.placeholderPlaceholder', 'Type your message...')} maxLength={60} />
              </div>

              <div>
                <label className="text-xs font-medium mb-2 block" style={{ color: 'hsl(var(--foreground))' }}>
                  {t('widgetSettings.appearance.autoOpenLabel', 'Auto-open Delay')}
                  <span className="ml-1 font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>— {t('widgetSettings.appearance.autoOpenSubtitle', '0 disables auto-open')}</span>
                </label>
                <div className="flex items-center gap-3">
                  <input
                    type="range" min={0} max={30} step={1}
                    value={settings.auto_open_delay}
                    onChange={e => setSettings(s => ({ ...s, auto_open_delay: Number(e.target.value) }))}
                    className="flex-1"
                    style={{ accentColor: 'hsl(var(--primary))' }}
                  />
                  <span className="text-sm font-mono w-10 text-center font-medium" style={{ color: 'hsl(var(--foreground))' }}>
                    {settings.auto_open_delay === 0 ? t('common.off', 'Off') : `${settings.auto_open_delay}s`}
                  </span>
                </div>
              </div>
            </div>

          </div>
        )}

        {/* ── AGENT tab ── */}
        {activeTab === 'agent' && (
          <div className="space-y-4">
            <div className="card p-5 space-y-4">
              <div>
                <h3 className="font-semibold text-sm mb-0.5" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.agent.selectTitle', 'Select AI Agent')}</h3>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('widgetSettings.agent.selectSubtitle', 'Choose which AI agent powers this chat widget. Only active agents with the "chat" channel are shown.')}
                </p>
              </div>

              {agents.length === 0 ? (
                <div className="flex items-start gap-3 p-4 rounded-xl" style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}>
                  <AlertCircle size={16} style={{ color: 'hsl(var(--warning))', flexShrink: 0, marginTop: 1 }} />
                  <div>
                    <p className="text-sm font-semibold" style={{ color: 'hsl(var(--warning))' }}>{t('widgetSettings.agent.noAgentsTitle', 'No chat agents configured')}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                      {t('widgetSettings.agent.noAgentsSubtitle', 'Go to AI Agent Config and create an agent with the "chat" channel enabled, then return here to select it.')}
                    </p>
                  </div>
                </div>
              ) : (
                <div className="space-y-2">
                  {/* Auto-select option */}
                  <button
                    onClick={() => setSettings(s => ({ ...s, agent_id: null }))}
                    className="w-full flex items-start gap-3 p-3.5 rounded-xl text-left transition-all border"
                    style={{
                      backgroundColor: settings.agent_id === null ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                      borderColor: settings.agent_id === null ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                    }}
                  >
                    <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5" style={{ backgroundColor: settings.agent_id === null ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))', opacity: settings.agent_id === null ? 1 : 0.4 }}>
                      <Zap size={16} className="text-white" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('widgetSettings.agent.autoSelect', 'Auto-select (Recommended)')}</span>
                        {settings.agent_id === null && (
                          <span className="text-xs px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>{t('common.active', 'Active')}</span>
                        )}
                      </div>
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t('widgetSettings.agent.autoSelectSubtitle', 'Automatically uses your default chat agent. Best for most restaurants.')}
                      </p>
                    </div>
                  </button>

                  {/* Per-agent options */}
                  {agents.map(agent => (
                    <button
                      key={agent.id}
                      onClick={() => setSettings(s => ({ ...s, agent_id: agent.id }))}
                      className="w-full flex items-start gap-3 p-3.5 rounded-xl text-left transition-all border"
                      style={{
                        backgroundColor: settings.agent_id === agent.id ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                        borderColor: settings.agent_id === agent.id ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      }}
                    >
                      <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5" style={{ background: `linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))` }}>
                        <Bot size={16} className="text-white" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{agent.name}</span>
                          {agent.is_default && (
                            <span className="text-xs px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'hsl(var(--warning-bg))', color: 'hsl(var(--warning))', border: '1px solid hsl(var(--warning-border))' }}>{t('common.default', 'Default')}</span>
                          )}
                          {settings.agent_id === agent.id && (
                            <span className="text-xs px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>{t('common.active', 'Active')}</span>
                          )}
                        </div>
                        {agent.description && (
                          <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{agent.description}</p>
                        )}
                        <div className="flex items-center gap-3 mt-1.5">
                          {agent.model_id && (
                            <span className="text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>🤖 {agent.model_id}</span>
                          )}
                          <span className="text-xs flex items-center gap-1" style={{ color: 'hsl(var(--success))' }}>
                            <span className="w-1.5 h-1.5 bg-green-500 rounded-full"></span> {t('common.active', 'Active')}
                          </span>
                        </div>
                      </div>
                      {settings.agent_id === agent.id && (
                        <Check size={16} style={{ color: 'hsl(var(--primary))', flexShrink: 0 }} />
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {selectedAgent && (
              <div className="card p-5" style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsl(var(--primary))' }}>
                <div className="flex items-center gap-2 mb-2">
                  <Sparkles size={14} style={{ color: 'hsl(var(--primary))' }} />
                  <span className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>{t('widgetSettings.agent.pinnedTitle', 'Pinned Agent Active')}</span>
                </div>
                <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {t('widgetSettings.agent.pinnedSubtitle', 'All widget conversations will use {name}. Save to apply.', { name: selectedAgent.name }).replace('{name}', selectedAgent.name)}
                </p>
              </div>
            )}

            <div className="card p-4" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <div className="flex items-start gap-2">
                <Info size={14} style={{ color: 'hsl(var(--muted-foreground))', flexShrink: 0, marginTop: 1 }} />
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  The selected agent's system prompt, greeting script, and fallback rules are used for all widget conversations. Configure agents under <strong>AI Agent Config</strong> in the sidebar.
                </p>
              </div>
            </div>
          </div>
        )}

        {/* ── EMBED tab ── */}
        {activeTab === 'embed' && (
          <div className="space-y-4">
            {/localhost|127\.0\.0\.1|\.ngrok\.io|\.ngrok-free\.app|\.trycloudflare\.com|\.loca\.lt/.test(origin) && (
              <div className="card p-4 flex items-start gap-3" style={{ backgroundColor: 'hsl(40, 100%, 97%)', border: '1px solid hsl(40, 90%, 75%)' }}>
                <AlertCircle size={15} style={{ color: 'hsl(40, 90%, 45%)', flexShrink: 0, marginTop: 1 }} />
                <div>
                  <p className="text-xs font-semibold mb-0.5" style={{ color: 'hsl(40, 70%, 35%)' }}>Development URL detected</p>
                  <p className="text-xs" style={{ color: 'hsl(40, 60%, 40%)' }}>
                    This embed code points to your development server. For a live website, <strong>publish your app</strong> first — the published URL is stable and always on. Your dev server URL changes when the workspace restarts.
                  </p>
                </div>
              </div>
            )}
            <div className="card p-5">
              <h3 className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>Your Embed Code</h3>
              <p className="text-xs mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                Paste this into the <code className="font-mono px-1 rounded" style={{ backgroundColor: 'hsl(var(--muted))' }}>&lt;body&gt;</code> of every page you want the widget to appear on.
              </p>
              <div className="rounded-xl p-4 font-mono text-xs relative" style={{ backgroundColor: 'hsl(220, 20%, 14%)', color: '#86efac', lineHeight: 1.8 }}>
                <button
                  onClick={handleCopy}
                  className="absolute top-3 right-3 flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg transition-colors"
                  style={{ backgroundColor: copied ? '#16a34a' : 'rgba(255,255,255,0.1)', color: 'white' }}
                >
                  {copied ? <><Check size={12} /> Copied!</> : <><Copy size={12} /> Copy</>}
                </button>
                <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all', paddingRight: 80 }}>{embedCode}</pre>
              </div>
            </div>

            <div className="card p-5 space-y-3">
              <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('widget.setupSteps', 'Setup Steps')}</h3>
              {[
                { step: '1', title: t('widget.step1Title', 'Copy the embed code above'), desc: t('widget.step1Desc', 'Use the copy button to copy your unique snippet') },
                { step: '2', title: t('widget.step2Title', 'Paste before </body> on your site'), desc: t('widget.step2Desc', 'Add it to every page where you want the widget to appear') },
                { step: '3', title: t('widget.step3Title', 'Save — done!'), desc: t('widget.step3Desc', 'The widget loads automatically with your configured settings and chosen AI agent') },
              ].map(item => (
                <div key={item.step} className="flex gap-3">
                  <div className="w-7 h-7 rounded-full flex items-center justify-center text-sm font-bold text-white flex-shrink-0" style={{ backgroundColor: 'hsl(var(--primary))' }}>{item.step}</div>
                  <div>
                    <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.title}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.desc}</p>
                  </div>
                </div>
              ))}
            </div>

            <div className="card p-5">
              <h3 className="font-semibold text-sm mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('widget.capabilities', 'Widget Capabilities')}</h3>
              <div className="grid grid-cols-2 gap-2">
                {[
                  { icon: '💬', label: t('widget.cap.aiChat', 'AI Chat'), desc: t('widget.cap.aiChatDesc', 'Instant AI-powered responses') },
                  { icon: '🍽️', label: t('widget.cap.orderTaking', 'Order Taking'), desc: t('widget.cap.orderTakingDesc', 'Customers can place orders') },
                  { icon: '📅', label: t('widget.cap.tableBooking', 'Table Booking'), desc: t('widget.cap.tableBookingDesc', 'Reserve tables through chat') },
                  { icon: '🔍', label: t('widget.cap.knowledgeBase', 'Knowledge Base'), desc: t('widget.cap.knowledgeBaseDesc', 'Answers from your KB') },
                  { icon: '📱', label: t('widget.cap.mobileReady', 'Mobile Ready'), desc: t('widget.cap.mobileReadyDesc', 'Full-screen on small screens') },
                  { icon: '🌐', label: t('widget.cap.anyWebsite', 'Any Website'), desc: t('widget.cap.anyWebsiteDesc', 'Works on any HTML site') },
                ].map(cap => (
                  <div key={cap.label} className="flex items-start gap-2.5 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                    <span className="text-lg">{cap.icon}</span>
                    <div>
                      <p className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{cap.label}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{cap.desc}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Save button */}
        {(activeTab === 'settings' || activeTab === 'agent') && (
          <div className="flex items-center justify-between pt-1">
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {settings.agent_id
                ? `${t('widget.using', 'Using')}: ${selectedAgent?.name ?? t('widget.customAgent', 'Custom agent')}`
                : `${t('widget.using', 'Using')}: ${t('widget.autoSelectedDefaultAgent', 'Auto-selected default agent')}`}
            </p>
            <button className="btn-primary" onClick={handleSave} disabled={saving}>
              {saving ? <><Loader2 size={15} className="animate-spin" /> {t('common.savingDots', 'Saving…')}</> : <><Check size={15} /> {t('widget.saveSettings', 'Save Settings')}</>}
            </button>
          </div>
        )}
      </div>

      {/* Right panel — live interactive preview */}
      <div className="w-full xl:w-80 flex-shrink-0">
        <div className="sticky top-6 space-y-4">

          {/* Live preview iframe */}
          <div className="card p-4">
            <div className="flex items-center justify-between mb-3">
              <div>
                <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>Live Preview</h3>
                <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>Real widget — chat with your AI</p>
              </div>
              <button
                className="btn-ghost p-1.5 text-xs flex items-center gap-1"
                onClick={() => setPreviewKey(k => k + 1)}
                title={t('widget.reloadPreview', 'Reload preview')}
              >
                <RefreshCw size={13} /> {t('widget.refresh', 'Refresh')}
              </button>
            </div>

            <div className="rounded-xl overflow-hidden" style={{ height: 480, border: '1px solid hsl(var(--border))' }}>
              {restaurantId ? (
                <iframe
                  key={previewKey}
                  src={`/api/widget/preview-page?restaurantId=${restaurantId}`}
                  className="w-full h-full"
                  style={{ border: 'none' }}
                  title={t('widget.livePreview', 'Live widget preview')}
                />
              ) : (
                <div className="flex items-center justify-center h-full" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Loader2 size={20} className="animate-spin" />
                </div>
              )}
            </div>

            <p className="text-xs mt-2 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('widgetSettings.previewHint', 'Save settings, then click Refresh to preview changes')}
            </p>
          </div>

          {/* Configuration summary */}
          <div className="card p-4 space-y-3">
            <h3 className="text-xs font-semibold" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('widgetSettings.configSummary', 'Configuration')}</h3>
            <div className="space-y-2">
              {[
                { label: t('common.status', 'Status'), value: settings.is_enabled ? t('common.enabled', 'Enabled') : t('common.disabled', 'Disabled'), ok: settings.is_enabled },
                { label: t('widgetSettings.position', 'Position'), value: settings.position === 'bottom-right' ? t('widgetSettings.position.bottomRight', '↘ Bottom Right') : t('widgetSettings.position.bottomLeft', '↙ Bottom Left'), ok: true },
                { label: t('widgetSettings.autoOpen', 'Auto-open'), value: settings.auto_open_delay === 0 ? t('common.off', 'Off') : t('widgetSettings.autoOpenAfter', 'After {{sec}}s', { sec: settings.auto_open_delay }), ok: true },
                { label: t('widgetSettings.aiAgent', 'AI Agent'), value: selectedAgent ? selectedAgent.name : t('widgetSettings.agent.autoSelect', 'Auto-select (Recommended)'), ok: true },
                { label: t('widgetSettings.botIcon', 'Bot Icon'), value: settings.icon_url ? t('widgetSettings.botIconCustom', 'Custom') : t('widgetSettings.botIconDefault', 'Default emoji'), ok: true },
              ].map(item => (
                <div key={item.label} className="flex items-center justify-between">
                  <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="text-xs font-medium" style={{ color: item.ok ? 'hsl(var(--foreground))' : 'hsl(var(--danger))' }}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
