import React, { useState } from 'react';
import { cn } from './lib/utils';
import type { DashboardData } from './types';
import {
  CheckCircle2,
  ExternalLink,
  UserPlus,
  Zap,
  Smartphone,
  Lock,
  Globe,
  FileType,
  Layout,
  Palette,
  Plus,
  ChevronUp,
  ChevronDown,
  Type,
  Mail,
  Settings2,
  Code2,
  MessageSquare,
  X,
  ChevronLeft,
  SquarePen,
  Trash2 as Trash,
  Brackets,
  Rocket,
  Save,
  Flame,
  Info,
  AlignLeft,
  Eye,
  AlertCircle,
  Pencil,
  Hash,
  List,
  Braces,
  Key
} from 'lucide-react';
import { motion, AnimatePresence } from "framer-motion";
import { PersonalizationDialog } from './components/ui/personalization-dialog';
import { SearchableSelect } from './components/ui/searchable-select';
import { Switch } from './components/ui/switch';
import { Label } from './components/ui/label';
import { Badge } from './components/ui/badge';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';
import {
  ModernCardHeader,
  SettingSwitchCard,
  SettingInput,
  StatusMessage,
  CodeEditor,
  ShortcodeManager,
  IntegrationCard,
  FlatTabs,
  SettingCard,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SaveWithStatus,
  MethodButton
} from './components/ui/settings-ui';



interface CustomField {
  key?: string;
  label: string;
  type: string;
  enabled: boolean;
  required: boolean;
  options?: string | { label: string; value: string }[];
  isNew?: boolean;
}

interface Settings {
  [key: string]: unknown;
  enable_otp?: number | string;
  otp_method?: string;
  field_order?: string;
  custom_fields?: Record<string, CustomField>;
  custom_shortcode?: string[];
  signup_logo?: string;
  signup_title?: string;
  signup_description?: string;
  custom_css?: string;
  color_theme?: string;
  signup_redirect_url?: string;
  enable_strong_password?: number | string;
  enable_password_reset?: number | string;
  enable_verification_fallback?: number | string;
  auto_login?: number | string;
  enable_premium_design?: number | string;
}






import { useSettingsManager, type ModuleData } from './hooks/use-settings-manager';

interface WordPressWindow {
  wp?: {
    media: (args: Record<string, unknown>) => {
      on: (event: string, callback: () => void) => void;
      open: () => void;
      state: () => {
        get: (key: string) => {
          first: () => {
            toJSON: () => { url: string };
          };
        };
      };
    };
  };
}

const RegistrationFormSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = rootData?.registrationForm || { options: {}, i18n: {}, optionNames: {}, availability: {}, emailTemplates: [], instances: [] };
  const [activeTab, setActiveTab] = useState('general');

  const {
    settings,
    setSettings,
    updateSetting,
    handleSave,
    saveStatus,
    hasUnsavedChanges,
    isSaving,
    t
  } = useSettingsManager<Settings>({
    rootData,
    moduleData: data as unknown as ModuleData,
    initialSettings: {},
    onBeforeSave: (s) => s // Standard conversion handled by hook
  });

  const [editingField, setEditingField] = useState<string | null>(null);
  const [tempField, setTempField] = useState<CustomField | null>(null);
  const [isPersonalizationOpen, setIsPersonalizationOpen] = useState(false);
  const [personalizationEditorId, setPersonalizationEditorId] = useState('');
  const [optionsViewMode, setOptionsViewMode] = useState<'interactive' | 'bulk'>('interactive');
  const isRTL = data?.rtl || window.wawpDashboardData?.rtl;

  const getStatus = (id: string): { type: 'active' | 'inactive' | 'error' | 'warning', message: string } | null => {
    const isChecked = (key: string) => settings[key] == 1 || settings[key] === 'yes';

    switch (id) {
      case 'enable_otp':
        return isChecked('enable_otp')
          ? { type: 'active', message: t.signup_active }
          : { type: 'inactive', message: t.signup_inactive };

      case 'otp_method': {
        const method = (settings.otp_method || '') as string;
        const name = (t[`${method}_label`] || method) as string;
        const avail = data?.availability[method as keyof typeof data.availability];

        if (avail && !avail.available) {
          return { type: 'error', message: `${t.signup_method?.replace('%s', `<b>${name}</b>`)}<br/><span class="text-[11px] opacity-80">${avail.reason}</span>` };
        }
        return { type: 'active', message: t.signup_method?.replace('%s', `<b>${name}</b>`) };
      }

      case 'fields': {
        const standard = ['first_name', 'last_name', 'email', 'phone', 'password'];
        const enabled = standard.filter(f => settings[`${f}_enabled`] == 1).length;
        const required = standard.filter(f => settings[`${f}_required`] == 1).length;
        const total = standard.length + (settings.custom_fields ? Object.keys(settings.custom_fields).length : 0);

        // Critical check: Required but not enabled
        const critical = standard.filter(f => settings[`${f}_required`] == 1 && settings[`${f}_enabled`] == 0);
        if (critical.length > 0) {
          return { type: 'error', message: t.signup_fields_error?.replace('%s', critical.join(', ')) };
        }

        return {
          type: 'active',
          message: t.signup_fields_active?.replace('%1$d', total.toString()).replace('%2$d', enabled.toString()).replace('%3$d', required.toString())
        };
      }

      case 'strong_pw':
        return isChecked('enable_strong_password')
          ? { type: 'active', message: t.signup_strong_pw_a || "Users must create a password with letters, numbers, and symbols for better security." }
          : { type: 'inactive', message: t.signup_strong_pw_i || "Standard password requirements are active. Users can use simpler passwords." };

      case 'pw_reset':
        return isChecked('enable_password_reset')
          ? { type: 'active', message: t.signup_pw_reset_a || "A 'Forgot Password' link will be displayed on the login/signup screens." }
          : { type: 'inactive', message: t.signup_pw_reset_i || "Password reset link is hidden. Ensure users have another way to recover access." };

      case 'fallback':
        return isChecked('enable_verification_fallback')
          ? { type: 'active', message: t.signup_fallback_a || "If WhatsApp verification fails or is unavailable, users can verify via Email OTP." }
          : { type: 'inactive', message: t.signup_fallback_i || "Email fallback is disabled. Users must verify via WhatsApp only." };

      case 'autologin':
        return isChecked('auto_login')
          ? { type: 'active', message: t.signup_autologin_a || "Users will be automatically logged in to their account after successful registration." }
          : { type: 'inactive', message: t.signup_autologin_i || "Users will need to log in manually after completing the registration process." };

      case 'redirect':
        return settings.signup_redirect_url
          ? { type: 'active', message: `Users will be redirected to <b>${settings.signup_redirect_url}</b> after registration.` }
          : { type: 'inactive', message: "No redirect URL set. Users will remain on the success page." };

      case 'logo':
        return settings.signup_logo
          ? { type: 'active', message: "Your brand logo is set and will appear at the top of the registration form." }
          : { type: 'inactive', message: "No logo selected. The form will display your site title instead." };

      case 'branding':
        return (settings.signup_title || settings.signup_description)
          ? { type: 'active', message: "Custom form header (title and description) is active and visible to users." }
          : { type: 'inactive', message: "Using default header text. Consider adding a custom title to welcome users." };

      case 'css':
        return settings.custom_css
          ? { type: 'active', message: "Custom CSS is active. Your style overrides are being applied to the form." }
          : { type: 'inactive', message: "No custom CSS applied. The form is using the standard premium theme." };
      
      case 'colors':
        return {
          type: 'active',
          message: "Visual theme overrides are active. Custom button and text colors are being applied."
        };

      default:
        return null;
    }
  };

  const tabs = [
    { id: 'general', label: t.general, icon: Settings2 },
    { id: 'fields', label: t.form_fields, icon: UserPlus },
    { id: 'advanced', label: t.advanced, icon: Rocket },
    { id: 'style', label: t.style, icon: Palette },
    { id: 'shortcodes', label: t.shortcodes, icon: Code2 },
  ];

  const standardFields: { id: string; label: string; icon: React.ElementType }[] = [
    { id: 'first_name', label: 'First Name', icon: Type },
    { id: 'last_name', label: 'Last Name', icon: Type },
    { id: 'email', label: 'Email Address', icon: Mail },
    { id: 'phone', label: 'Phone Number', icon: Smartphone },
    { id: 'password', label: 'Password', icon: Lock },
  ];

  const saveSettingsAtomic = async (nextSettings: Settings) => {
    const optionNames = data?.optionNames || {};
    const finalSettings = { ...nextSettings } as Record<string, unknown>;
    if (optionNames.custom_fields) finalSettings[optionNames.custom_fields] = nextSettings.custom_fields;
    if (optionNames.field_order) finalSettings[optionNames.field_order] = nextSettings.field_order;
    setSettings(finalSettings as Settings);
    await handleSave(finalSettings as Settings);
  };

  const fieldOrder = (settings.field_order || 'first_name,last_name,email,phone,password').split(',');

  const moveField = (index: number, direction: 'up' | 'down') => {
    const newOrder = [...fieldOrder];
    const target = direction === 'up' ? index - 1 : index + 1;
    if (target < 0 || target >= newOrder.length) return;

    [newOrder[index], newOrder[target]] = [newOrder[target], newOrder[index]];
    const newSettings = { ...settings, field_order: newOrder.join(',') };
    saveSettingsAtomic(newSettings);
  };

  return (
    <SettingsLayout>
      <SettingsHeader
        title={t.registration_form_title || 'Registration Form Builder'}
        description={t.registration_form_desc || 'Configure your custom registration form with OTP verification.'}
      >
        <SaveWithStatus
          saveStatus={saveStatus === 'unsaved' ? 'idle' : saveStatus}
          hasUnsavedChanges={hasUnsavedChanges}
          isSaving={isSaving}
          onSave={() => handleSave(false)}
          t={{
            saveChanges: t.save_settings_btn,
            saving: t.saving
          }}
        />
      </SettingsHeader>

      <FlatTabs
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      <div>
        <AnimatePresence mode="wait">
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
            className="space-y-6"
          >
            {activeTab === 'general' && (
              <div className="space-y-8">
                {/* Verification Toggle */}
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.enable_signup_verification_label}
                    description={t.enable_signup_verification_desc}
                    icon={Lock}
                    rightAction={
                      <Switch
                        checked={settings.enable_otp == 1}
                        onCheckedChange={(checked) => updateSetting('enable_otp', checked ? 1 : 0)}
                      />
                    }
                  />
                  <div className="p-6 md:p-8 space-y-6">
                    <div className="flex items-center gap-2">
                      <div className="h-8 w-8 rounded-lg bg-slate-50 flex items-center justify-center text-slate-600 border border-slate-100">
                        <Zap size={16} />
                      </div>
                      <h4 className="text-[12px] font-bold text-slate-900 uppercase tracking-wider">{t.method_label}</h4>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      {[
                        { id: 'whatsapp', label: t.whatsapp_label || 'WhatsApp Web Authentication', icon: MessageSquare, description: t.whatsapp_desc || 'High-speed WhatsApp OTP & Interactive verification via your own WhatsApp instances.', iconPath: String(rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-600', bg: 'bg-emerald-50' },
                        { id: 'email', label: t.email_label || 'Email Magic Link Login', icon: Mail, description: t.email_desc || 'Users receive a secure link in their inbox to authorize login instantly.', iconPath: String(rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", color: 'text-blue-600', bg: 'bg-blue-50' },
                        { id: 'firebase', label: t.firebase_label || 'Firebase SMS Authentication', icon: Flame, description: t.firebase_desc || 'Use Google Firebase to send SMS verification codes globally (Requires API Key).', iconPath: String(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg", color: 'text-orange-600', bg: 'bg-orange-50' }
                      ].map(item => (
                        <MethodButton
                          key={item.id}
                          active={settings.otp_method === item.id}
                          onClick={() => updateSetting('otp_method', item.id)}
                          label={item.label}
                          description={item.description}
                          icon={item.icon}
                          iconPath={item.iconPath}
                          color={item.color}
                          bg={item.bg}
                        />
                      ))}
                    </div>

                    {/* Merged Status Card */}
                    {settings.enable_otp == 1 && (
                      <motion.div
                        initial={{ opacity: 0, y: 5 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="flex flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3 bg-emerald-50/40 border border-emerald-100 rounded-[5px] text-[12px] font-semibold text-emerald-700"
                      >
                        <div className="flex items-center gap-2">
                          <CheckCircle2 size={14} className="text-emerald-500" />
                          <span>{t.signup_active}</span>
                        </div>
                        <div className="w-1 h-1 rounded-full bg-emerald-200 hidden md:block" />
                        <div className="flex items-center gap-2">
                          <Zap size={14} className="text-emerald-500" />
                          <span dangerouslySetInnerHTML={{
                            __html: t.signup_method?.replace('%s', `<b>${t[`${settings.otp_method}_label`] || settings.otp_method}</b>`)
                          }} />
                        </div>
                      </motion.div>
                    )}

                    {!settings.enable_otp && getStatus('enable_otp') && (
                      <StatusMessage {...getStatus('enable_otp')!} />
                    )}
                  </div>
                </SettingCard>

                <AnimatePresence mode="wait">
                  {settings.otp_method === 'whatsapp' && (
                    <motion.div
                      key="wa" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                      className="space-y-4"
                    >
                      <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader
                          title={t.whatsapp_web_auth_title || "WhatsApp Web Authentication"}
                          description={t.whatsapp_web_auth_desc || "High-speed WhatsApp OTP & Interactive verification via your own WhatsApp instances."}
                          iconPath={String(rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg"}
                        />

                        <div className="p-6 md:p-8 space-y-6">
                          <div className="flex items-center gap-2 mb-2 pl-1">
                            <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest">{t.whatsapp_engine_label || "WhatsApp Auth Engine"}</span>
                            <Badge variant="outline" className="h-5 px-1.5 text-[9px] font-black border-slate-200 text-slate-500 uppercase ml-auto">Active</Badge>
                          </div>

                          <div className="space-y-6 pt-4 border-t border-slate-100">
                            <WhatsAppAuthSettings
                              settings={settings as Record<string, string | number | boolean>}
                              updateSetting={updateSetting}
                              optionNames={data?.optionNames || {}}
                              msgs={t}
                            />
                          </div>

                          <StatusMessage
                            type={settings.enable_otp == 1 && data?.availability.whatsapp.available ? 'active' : (settings.enable_otp == 1 ? 'error' : 'inactive')}
                            message={settings.enable_otp == 1 && data?.availability.whatsapp.available ? t.signup_active : (settings.enable_otp == 1 ? (data?.availability.whatsapp.reason || '') : t.signup_inactive)}
                          />
                        </div>
                      </SettingCard>
                    </motion.div>
                  )}

                  {settings.otp_method === 'email' && (
                    <motion.div
                      key="em" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                      className="space-y-4"
                    >
                      <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader
                          title={t.email_magic_link_title || "Email Magic Link Login"}
                          description={t.email_magic_link_desc || "Users receive a secure link in their inbox to authorize login instantly."}
                          iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg"}
                        />

                        <div className="p-6 md:p-8 space-y-6">
                          <div className="flex items-center gap-2 mb-2 pl-1">
                            <Globe className="w-4 h-4 text-slate-400" />
                            <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest">{t.customer_email_label || "Customer Email"}</span>
                            <Badge variant="outline" className="h-5 px-1.5 text-[9px] font-black border-slate-200 text-slate-500 uppercase ml-auto">SMTP</Badge>
                          </div>

                          <SettingInput
                            label="Subject" value={(settings.otp_subject_email as string) || ''}
                            onChange={(val) => updateSetting('otp_subject_email', val)}
                            placeholder="Subject..."
                            icon={Mail}
                            showEmoji={true}
                            showFormatting={false}
                            button={
                              <button
                                className="p-2 text-slate-400 hover:text-blue-600 transition-colors"
                                onClick={() => {
                                  setPersonalizationEditorId('otp_subject_email');
                                  setIsPersonalizationOpen(true);
                                }}
                              >
                                <Brackets size={14} />
                              </button>
                            }
                          />

                          <div className="space-y-1.5">
                            <div className="flex justify-between items-center px-1">
                              <Label className="text-[11px] font-black text-slate-400 uppercase tracking-widest">Body Template</Label>
                              <a
                                href="/wp-admin/admin.php?page=wawp&wawp_section=email_templates"
                                className="text-[10px] font-black text-[#004449] hover:text-[#003337] uppercase tracking-widest flex items-center gap-1 transition-colors"
                                title="Manage Templates"
                              >
                                <Settings2 size={12} />
                                Manage
                              </a>
                            </div>
                            <SearchableSelect
                              options={data?.emailTemplates?.map((tpl: { id: number; name: string }) => ({
                                value: tpl.id.toString(),
                                label: tpl.name
                              })) || []}
                              value={settings.otp_email_template_id?.toString() || ""}
                              onChange={(val) => updateSetting('otp_email_template_id', val)}
                              placeholder="Select Email Template..."
                              className="h-11 bg-slate-50/30 border-slate-200 text-slate-700 font-bold text-[13px] hover:bg-white hover:border-[#004449]/30 transition-all rounded-[5px]"
                            />
                          </div>
                        </div>
                      </SettingCard>
                    </motion.div>
                  )}

                  {settings.otp_method === 'firebase' && (
                    <motion.div
                      key="fb" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                      className="space-y-4"
                    >
                      <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader
                          title={t.firebase_sms_auth_title || "Firebase SMS Authentication"}
                          description={t.firebase_sms_auth_desc || "Use Google Firebase to send SMS verification codes globally (Requires API Key)."}
                          iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"}
                        />

                        <div className="p-6 md:p-8 flex flex-col md:flex-row items-center gap-6">
                          <div className="h-14 w-14 flex items-center justify-center shrink-0">
                            <img src={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"} className="w-10 h-10 object-contain" alt="" />
                          </div>
                          <div className="flex-1 space-y-1.5 text-center md:text-left">
                            <h5 className="font-extrabold text-slate-900 text-[15px]">{t.firebase_tpl_label}</h5>
                            <p className="text-[12px] text-slate-500 leading-relaxed font-medium max-w-xl">
                              Firebase SMS messages are handled externally. To modify templates or manage costs, please visit your Firebase control panel.
                            </p>
                          </div>
                          <a
                            href="https://console.firebase.google.com/" target="_blank"
                            className="shrink-0 px-6 py-2.5 bg-orange-600 hover:bg-orange-700 !text-white text-[12px] font-black rounded-[5px] transition-all flex items-center gap-2 shadow-none hover:shadow-lg hover:shadow-orange-100 active:scale-95"
                            style={{ color: 'white' }}
                          >
                            Open Firebase Console
                            <ExternalLink size={14} className="!text-white" style={{ color: 'white' }} />
                          </a>
                        </div>
                        <div className="px-6 md:px-8 pb-8">
                           <StatusMessage 
                              type={data.availability?.firebase?.available ? 'active' : 'warning'} 
                              message={data.availability?.firebase?.available ? "Firebase Account found. System is ready to route messages through Google gateway." : "<b>Firebase is not configured!</b> Please visit the Firebase Settings tab first."} 
                           />
                        </div>
                      </SettingCard>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            )}

            {activeTab === 'fields' && (
              <div className="space-y-6 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.field_settings_label}
                    description="Standard and custom fields for your registration form. Drag rows to reorder."
                    icon={UserPlus}
                    rightAction={
                      <AdminButton
                        onClick={() => {
                          const key = `field_${Date.now()}`;
                          setTempField({ key, label: 'New Custom Field', type: 'text', enabled: true, required: false, isNew: true });
                          setEditingField(key);
                        }}
                        icon={Plus}
                      >
                        {t.new_field_btn}
                      </AdminButton>
                    }
                  />
                  <div className="p-6 md:p-8 space-y-3">
                    {fieldOrder.map((key: string, index: number) => {
                      const isStandard = standardFields.some(f => f.id === key);
                      const field = isStandard
                        ? standardFields.find(f => f.id === key)
                        : (settings.custom_fields && settings.custom_fields[key]);

                      if (!field) return null;

                      const isEnabled = isStandard ? (settings[`${key}_enabled`] == 1) : (field as CustomField).enabled;
                      const isRequired = isStandard ? (settings[`${key}_required`] == 1) : (field as CustomField).required;

                      return (
                        <motion.div
                          layout
                          key={key}
                          initial={{ opacity: 0, y: 10 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: index * 0.05 }}
                          className={`group flex items-center gap-4 p-3.5 rounded-[5px] border transition-all ${isEnabled ? 'bg-white border-[#dcdcde]' : 'bg-slate-50/50 border-slate-200 opacity-60'
                            }`}
                        >
                          <div className="flex flex-col gap-0.5 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity">
                            <button
                              onClick={() => moveField(index, 'up')}
                              className="p-1 hover:bg-slate-100 rounded text-slate-400 hover:text-slate-900 transition-colors"
                            >
                              <ChevronUp size={14} strokeWidth={3} />
                            </button>
                            <button
                              onClick={() => moveField(index, 'down')}
                              className="p-1 hover:bg-slate-100 rounded text-slate-400 hover:text-slate-900 transition-colors"
                            >
                              <ChevronDown size={14} strokeWidth={3} />
                            </button>
                          </div>

                          <div className={`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 shadow-none ${isEnabled ? (isStandard ? 'bg-blue-50 text-blue-600' : 'bg-violet-50 text-violet-600') : 'bg-slate-100 text-slate-400'
                            }`}>
                            {isStandard ? React.createElement((field as { icon: React.ElementType }).icon, { size: 20 }) : <FileType size={20} />}
                          </div>

                          <div className="grow">
                            <span className="block text-[14px] font-bold text-slate-900 tracking-tight">
                              {isStandard ? field.label : field.label}
                            </span>
                            <div className="flex items-center gap-2 mt-0.5">
                              <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest leading-none">
                                {isStandard ? 'Standard' : 'Custom'}
                              </span>
                              {isRequired && isEnabled && (
                                <Badge variant="outline" className="h-3.5 px-1 py-0 text-[8px] font-black border-rose-100 text-rose-500 uppercase leading-none">Required</Badge>
                              )}
                            </div>
                          </div>

                          <div className="flex items-center gap-6 pr-2">
                            {/* Enabled Toggle */}
                            <div className="flex flex-col items-center gap-1.5 shrink-0">
                              <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{t.enabled_fields_label}</span>
                              <Switch
                                checked={isEnabled}
                                onCheckedChange={() => {
                                  if (isStandard) {
                                    updateSetting(`${key}_enabled`, isEnabled ? 0 : 1);
                                  } else {
                                    const newCf = { ...settings.custom_fields };
                                    newCf[key].enabled = !isEnabled;
                                    updateSetting('custom_fields', newCf);
                                  }
                                }}
                              />
                            </div>

                            {/* Required Toggle */}
                            <div className="flex flex-col items-center gap-1.5 shrink-0">
                              <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{t.required_fields_label}</span>
                              <Switch
                                checked={isRequired}
                                disabled={!isEnabled}
                                onCheckedChange={() => {
                                  if (isStandard) {
                                    updateSetting(`${key}_required`, isRequired ? 0 : 1);
                                  } else {
                                    const newCf = { ...settings.custom_fields };
                                    newCf[key].required = !isRequired;
                                    updateSetting('custom_fields', newCf);
                                  }
                                }}
                              />
                            </div>

                            {!isStandard && (
                              <div className="flex items-center gap-1 ml-2 border-l border-slate-100 pl-4 py-1">
                                <button
                                  onClick={() => {
                                    setTempField({ key, ...(field as CustomField) });
                                    setEditingField(key);
                                  }}
                                  className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
                                  title="Edit Field"
                                >
                                  <SquarePen size={17} />
                                </button>
                                <button
                                  onClick={() => {
                                    const newCf = { ...settings.custom_fields };
                                    delete newCf[key];
                                    const newOrder = fieldOrder.filter((k: string) => k !== key);
                                    const newSettings = { ...settings, custom_fields: newCf, field_order: newOrder.join(',') };
                                    saveSettingsAtomic(newSettings);
                                  }}
                                  className="p-2 text-slate-300 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-all"
                                  title="Remove Field"
                                >
                                  <Trash size={17} />
                                </button>
                              </div>
                            )}
                          </div>
                        </motion.div>
                      );
                    })}
                  </div>


                  <AnimatePresence>
                    {getStatus('fields') && (
                      <div className="mt-6">
                        {getStatus('fields') && <StatusMessage {...getStatus('fields')!} />}
                      </div>
                    )}
                  </AnimatePresence>
                </SettingCard>
              </div>
            )}

            {activeTab === 'shortcodes' && (
              <div className="space-y-8 animate-in slide-in-from-right-4 duration-500">
                <ShortcodeManager
                  shortcodes={settings.custom_shortcode || []}
                  onChange={(sc) => updateSetting('custom_shortcode', sc)}
                  title={t.custom_shortcodes_label || "Additional Shortcodes"}
                  description={t.custom_shortcodes_desc || "Add custom shortcodes to display extra content below the form."}
                  placeholder={t.placeholder_shortcode || "[custom_shortcode]"}
                />

                <div className="mt-8">
                  <StatusMessage
                    type={(settings.custom_shortcode || []).length > 0 ? 'active' : 'inactive'}
                    message={(settings.custom_shortcode || []).length > 0 ? "<b>%d</b> additional shortcodes are active.".replace('%d', String((settings.custom_shortcode || []).length)) : "No additional shortcodes are currently active."}
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pb-8">
                  <IntegrationCard
                    title={t.main_shortcode_title || "Main Shortcode"}
                    description={t.main_shortcode_desc || "Display the complete Registration form on any page, post or widget area."}
                    code="[wawp_signup_form]"
                    badge="Primary"
                    badgeColor="brand"
                    icon={Code2}
                    variant="light"
                  />
                  <IntegrationCard
                    title={t.php_integration_title || "PHP Integration"}
                    description={t.php_integration_desc || "Call the form programmatically directly from your theme template files."}
                    code={'<?php echo do_shortcode("[wawp_signup_form]"); ?>'}
                    badge="Developer"
                    badgeColor="brand"
                    icon={Settings2}
                    variant="brand"
                  />
                </div>
              </div>
            )}

            {activeTab === 'advanced' && (
              <div className="space-y-8 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.advanced}
                    description="Fine-tune your registration flow and security settings."
                    icon={Rocket}
                  />

                  <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div className="space-y-6">
                      <SettingInput
                        label={t.redirect_url_label || "Success Redirect URL"} 
                        value={(settings.signup_redirect_url as string) || ''}
                        onChange={(val) => updateSetting('signup_redirect_url', val)}
                        icon={Globe} placeholder="https://example.com/welcome"
                        description={t.redirect_url_desc || "Where should users go after successful registration?"}
                        showEmoji={false}
                        showFormatting={false}
                      />
                      {getStatus('redirect') && <StatusMessage {...getStatus('redirect')!} />}

                      <div className="space-y-3">
                        <SettingSwitchCard
                          label={t.strong_pass_label || "Enforce Strong Passwords"} 
                          description={t.security_hardening_desc || "SECURITY HARDENING"}
                          checked={settings.enable_strong_password == 1}
                          onChange={() => updateSetting('enable_strong_password', settings.enable_strong_password != 1 ? 1 : 0)}
                        />
                        {getStatus('strong_pw') && <StatusMessage {...getStatus('strong_pw')!} />}
                      </div>
                    </div>

                    <div className="space-y-4">
                      <div className="space-y-3">
                        <SettingSwitchCard
                          label={t.pass_reset_label || "Show Password Reset Link"} 
                          description={t.user_convenience_desc || "USER CONVENIENCE"}
                          checked={settings.enable_password_reset == 1}
                          onChange={() => updateSetting('enable_password_reset', settings.enable_password_reset != 1 ? 1 : 0)}
                        />
                        {getStatus('pw_reset') && <StatusMessage {...getStatus('pw_reset')!} />}
                      </div>

                      <div className="space-y-3">
                        <SettingSwitchCard
                          label={t.fallback_label || "Verification Fallback"} 
                          description={t.fallback_desc || "ALLOW EMAIL VERIFICATION IF WHATSAPP FAILS"}
                          checked={settings.enable_verification_fallback == 1}
                          onChange={() => updateSetting('enable_verification_fallback', settings.enable_verification_fallback != 1 ? 1 : 0)}
                        />
                        {getStatus('fallback') && <StatusMessage {...getStatus('fallback')!} />}
                      </div>

                      <div className="space-y-3">
                        <SettingSwitchCard
                          label={t.autologin_label || "Auto Login After Signup"} 
                          description={t.direct_access_desc || "DIRECT ACCESS AFTER REGISTRATION"}
                          checked={settings.auto_login == 1}
                          onChange={() => updateSetting('auto_login', settings.auto_login != 1 ? 1 : 0)}
                        />
                        {getStatus('autologin') && <StatusMessage {...getStatus('autologin')!} />}
                      </div>
                    </div>
                  </div>
                </SettingCard>

              </div>
            )}

            {activeTab === 'style' && (
              <div className="space-y-8 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.style_settings_label}
                    description={t.style_settings_desc || "Customize how your registration form looks to your users."}
                    icon={Palette}
                  />

                  <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-12">
                    <div className="space-y-8">
                      {/* Logo Upload Section */}
                      <div className="space-y-4">
                        <label className="block text-sm font-bold text-slate-700">{t.logo_label}</label>
                        <div className="flex items-center gap-6">
                          <div className="w-32 h-32 bg-slate-50 rounded-[5px] border-2 border-dashed border-slate-200 flex items-center justify-center overflow-hidden group relative transition-all hover:bg-slate-100">
                            {settings.signup_logo ? (
                              <>
                                <img src={settings.signup_logo as string} className="w-full h-full object-contain p-4" alt="Logo" />
                                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                                  <button
                                    onClick={() => {
                                      const wpWindow = window as unknown as WordPressWindow;
                                      if (!wpWindow.wp || !wpWindow.wp.media) return;
                                      const frame = wpWindow.wp.media({
                                        title: t.select_logo || 'Select Logo',
                                        button: { text: t.use_this_logo || 'Use this logo' },
                                        multiple: false
                                      });
                                      frame.on('select', () => {
                                        const attachment = frame.state().get('selection').first().toJSON();
                                        updateSetting('signup_logo', attachment.url || '');
                                      });
                                      frame.open();
                                    }}
                                    className="p-2 bg-white rounded-lg text-slate-700 hover:text-blue-600 shadow-none transition-all active:scale-90"
                                  >
                                    <Palette size={18} />
                                  </button>
                                  <button
                                    onClick={() => updateSetting('signup_logo', '')}
                                    className="p-2 bg-white rounded-lg text-red-500 hover:text-red-700 shadow-none transition-all active:scale-90"
                                  >
                                    <Trash size={18} />
                                  </button>
                                </div>
                              </>
                            ) : (
                              <div
                                className="text-center cursor-pointer"
                                onClick={() => {
                                  const wpWindow = window as unknown as WordPressWindow;
                                  if (!wpWindow.wp || !wpWindow.wp.media) return;
                                  const frame = wpWindow.wp.media({
                                    title: 'Select Logo',
                                    button: { text: 'Use this logo' },
                                    multiple: false
                                  });
                                  frame.on('select', () => {
                                    const attachment = frame.state().get('selection').first().toJSON();
                                    updateSetting('signup_logo', attachment.url || '');
                                  });
                                  frame.open();
                                }}
                              >
                                <Layout className="w-10 h-10 text-slate-200 mx-auto mb-2" />
                                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-none block px-2">Select Logo</span>
                              </div>
                            )}
                          </div>
                          <div className="flex-1 space-y-2">
                            <p className="text-slate-400 text-[11px] leading-relaxed">Better to use a transparent PNG or SVG logo. Recommended size: 400x120px.</p>
                            <button
                              onClick={() => {
                                const wpWindow = window as unknown as WordPressWindow;
                                if (!wpWindow.wp || !wpWindow.wp.media) return;
                                const frame = wpWindow.wp.media({
                                  title: 'Change Logo',
                                  button: { text: 'Use this logo' },
                                  multiple: false
                                });
                                frame.on('select', () => {
                                  const attachment = frame.state().get('selection').first().toJSON();
                                  updateSetting('signup_logo', attachment.url || '');
                                });
                                frame.open();
                              }}
                              className="px-4 py-2 bg-white border border-[#dcdcde] text-slate-700 text-xs font-bold rounded-[5px] hover:border-slate-900 hover:text-slate-900 transition-all active:scale-95"
                            >
                              {t.select_logo || 'Change Logo'}
                            </button>
                          </div>
                        </div>
                      </div>
                      {getStatus('logo') && <StatusMessage {...getStatus('logo')!} className="mt-4" />}

                      <SettingInput
                        label={t.title_label}
                        value={(settings.signup_title as string) || ''}
                        onChange={(val) => updateSetting('signup_title', val)}
                        placeholder=""
                        icon={Type}
                        showEmoji={true}
                        showFormatting={true}
                      />

                      <SettingInput
                        label={t.description_label}
                        value={(settings.signup_description as string) || ''}
                        onChange={(val) => updateSetting('signup_description', val)}
                        placeholder=""
                        icon={Info}
                        showEmoji={true}
                        showFormatting={true}
                      />
                      {getStatus('branding') && <StatusMessage {...getStatus('branding')!} />}

                      <CodeEditor
                        value={(settings.custom_css as string) || ''}
                        onChange={(val) => updateSetting('custom_css', val)}
                        label="Custom CSS Implementation"
                        language="css"
                        placeholder=".wawp-signup-form { \n  background: #f8fafc;\n  border-radius: 20px;\n}"
                      />
                      {getStatus('css') && <StatusMessage {...getStatus('css')!} />}
                    </div>

                    {/* Appearance side */}
                    <div className="space-y-8">
                      <div className="space-y-4">
                        <label className="block text-sm font-bold text-slate-700">Color Presets</label>
                        <div className="grid grid-cols-3 gap-3">
                          {[
                            {
                              id: 'default', label: 'Default', colors: {
                                'whatsapp_button_color': '#22c55e', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#3b82f6', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#22c55e', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#ef4444', 'button_text_color': '#ffffff',
                                'verify_button_color': '#3b82f6', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#64748b', 'resend_button_text_color': '#ffffff',
                              }
                            },
                            {
                              id: 'wawp', label: 'Teal', colors: {
                                'whatsapp_button_color': '#004449', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#141b38', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#004449', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#141b38', 'button_text_color': '#ffffff',
                                'verify_button_color': '#004449', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#cbd5e1', 'resend_button_text_color': '#0f172a',
                              }
                            },
                            {
                              id: 'ocean', label: 'Ocean', colors: {
                                'whatsapp_button_color': '#0891b2', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#2563eb', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#0891b2', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#0f172a', 'button_text_color': '#ffffff',
                                'verify_button_color': '#2563eb', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#64748b', 'resend_button_text_color': '#ffffff',
                              }
                            },
                            {
                              id: 'midnight', label: 'Midnight', colors: {
                                'whatsapp_button_color': '#7c3aed', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#4f46e5', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#7c3aed', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#1e293b', 'button_text_color': '#ffffff',
                                'verify_button_color': '#4f46e5', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#475569', 'resend_button_text_color': '#ffffff',
                              }
                            },
                            {
                              id: 'sunset', label: 'Sunset', colors: {
                                'whatsapp_button_color': '#ea580c', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#dc2626', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#ea580c', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#991b1b', 'button_text_color': '#ffffff',
                                'verify_button_color': '#dc2626', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#78350f', 'resend_button_text_color': '#ffffff',
                              }
                            },
                            {
                              id: 'minimal', label: 'Minimal', colors: {
                                'whatsapp_button_color': '#171717', 'whatsapp_button_text_color': '#ffffff',
                                'firebase_button_color': '#404040', 'firebase_button_text_color': '#ffffff',
                                'email_otp_button_color': '#171717', 'email_otp_button_text_color': '#ffffff',
                                'button_background_color': '#525252', 'button_text_color': '#ffffff',
                                'verify_button_color': '#262626', 'verify_button_text_color': '#ffffff',
                                'resend_button_color': '#a3a3a3', 'resend_button_text_color': '#000000',
                              }
                            },
                          ].map(preset => (
                            <button
                              key={preset.id}
                              onClick={() => {
                                const newSettings = { ...settings, color_theme: preset.id, ...preset.colors };
                                setSettings(newSettings);
                              }}
                              className={`p-3 rounded-[5px] border-2 transition-all text-center group ${settings.color_theme === preset.id ? 'border-[#004449] bg-slate-50' : 'border-slate-100 hover:border-slate-200'}`}
                            >
                              <div className="flex justify-center gap-1 mb-2">
                                {Array.from(new Set(Object.values(preset.colors))).slice(0, 3).map((c, i) => (
                                  <div key={i} className="w-3 h-3 rounded-full border border-white shadow-none" style={{ backgroundColor: c as string }} />
                                ))}
                              </div>
                              <span className={`text-[10px] font-bold uppercase tracking-tight ${settings.color_theme === preset.id ? 'text-[#004449]' : 'text-slate-400 font-medium'}`}>{preset.label}</span>
                            </button>
                          ))}
                        </div>
                      </div>

                      <div className="space-y-4">
                        <label className="block text-sm font-bold text-slate-700">Detailed Colors</label>
                        <div className="grid grid-cols-1 gap-4 max-h-[500px] overflow-y-auto pr-2 no-scrollbar pl-1">
                          {[
                            { bgKey: 'whatsapp_button_color', textKey: 'whatsapp_button_text_color', label: 'WhatsApp Button', group: 'Methods' },
                            { bgKey: 'email_otp_button_color', textKey: 'email_otp_button_text_color', label: 'Email Button', group: 'Methods' },
                            { bgKey: 'firebase_button_color', textKey: 'firebase_button_text_color', label: 'SMS Button', group: 'Methods' },
                            { bgKey: 'button_background_color', textKey: 'button_text_color', label: 'Signup Button', group: 'Main Action' },
                            { bgKey: 'verify_button_color', textKey: 'verify_button_text_color', label: 'Verify Button', group: 'Verification' }
                          ].map((item) => (
                            <div key={item.bgKey} className="flex items-center justify-between p-4 bg-slate-50/50 rounded-[5px] border border-slate-100">
                              <div>
                                <span className="block text-[13px] font-bold text-slate-900">{item.label}</span>
                                <span className="text-[10px] text-slate-400 font-bold uppercase tracking-tight">{item.group}</span>
                              </div>
                              <div className="flex items-center gap-4">
                                <div className="flex flex-col items-center gap-1">
                                  <label className="text-[9px] font-black text-slate-300 uppercase">Bg</label>
                                  <input
                                    type="color"
                                    value={(settings[item.bgKey] as string) || '#000000'}
                                    onChange={(e) => updateSetting(item.bgKey, e.target.value)}
                                    className="w-9 h-9 rounded-lg cursor-pointer border-2 border-white shadow-[5px]"
                                  />
                                </div>
                                <div className="flex flex-col items-center gap-1">
                                  <label className="text-[9px] font-black text-slate-300 uppercase">Text</label>
                                  <input
                                    type="color"
                                    value={(settings[item.textKey] as string) || '#ffffff'}
                                    onChange={(e) => updateSetting(item.textKey, e.target.value)}
                                    className="w-9 h-9 rounded-lg cursor-pointer border-2 border-white shadow-[5px]"
                                  />
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="mt-12">
                    <StatusMessage
                      type={settings.enable_premium_design == 1 ? 'active' : 'inactive'}
                      message={settings.enable_premium_design == 1 ? "Premium custom design is active and applied to your registration form." : "Standard design is active. Enable premium design to apply these custom styles."}
                    />
                  </div>
                </SettingCard>
              </div>
            )}
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Field Edit Sidebar (Drawer) */}
      <AnimatePresence>
        {editingField && tempField && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setEditingField(null)}
              className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-[100000]"
            />

            {/* Sidebar Content */}
            <motion.div
              initial={{ x: isRTL ? '-100%' : '100%' }} animate={{ x: 0 }} exit={{ x: isRTL ? '-100%' : '100%' }}
              transition={{ type: 'spring', damping: 28, stiffness: 220 }}
              className={cn(
                "fixed inset-y-0 w-full lg:max-w-[calc(100%-280px)] xl:max-w-[1200px] bg-white z-[100001] shadow-2xl flex flex-col",
                isRTL ? "left-0 border-r" : "right-0 border-l"
              )}
            >
              {/* Drawer Header */}
              <div className="px-6 py-2 border-b border-slate-100 bg-white flex items-center justify-between sticky top-0 z-10">
                <div className="flex-1">
                   <ModernCardHeader 
                      title={t.edit_field_title || "Manage Custom Field"} 
                      description="Configure your field settings and options" 
                      icon={Pencil} 
                      className="!border-none !p-0 !bg-transparent"
                   />
                </div>
                <button onClick={() => setEditingField(null)} className="p-2 hover:bg-slate-50 rounded-lg text-slate-400 transition-colors">
                  <X size={20} />
                </button>
              </div>

              {/* Scrollable Content */}
              <div className="flex-1 overflow-y-auto no-scrollbar">
                <div className="p-8 space-y-9">
                  {/* Field Label */}
                  <SettingInput
                    label="Field Label"
                    value={tempField?.label || ''}
                    onChange={(val) => {
                      if (!tempField) return;
                      const updates: Partial<CustomField> = { label: val };
                      if (tempField.isNew) {
                        const slug = val.toLowerCase().trim().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
                        updates.key = slug;
                      }
                      setTempField({ ...tempField, ...updates });
                    }}
                    placeholder="e.g., Your Name"
                    icon={Type}
                    description="This will be the Name for the user frontend. Allowed every Thing."
                    showEmoji={true}
                  />

                  {/* Meta Key (Unique ID) */}
                  <SettingInput
                    label="Meta Key (Unique ID)"
                    value={tempField?.key || ''}
                    disabled={!tempField?.isNew}
                    onChange={(val) => tempField && setTempField({ ...tempField, key: val.toLowerCase().replace(/[^a-z0-9_]/g, '') })}
                    icon={Key}
                    placeholder="e.g., my_custom_field"
                    description="This will be the unique meta key for the user profile. Use lowercase, no spaces, no special characters except underscore."
                  />

                  {/* Field Type Selector */}
                  <div className="space-y-4">
                    <div className="flex items-center gap-2 px-1">
                      <Layout className="w-4 h-4 text-slate-400" />
                      <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Field Component Type</Label>
                    </div>
                    <SearchableSelect
                      options={[
                        { value: 'text', label: t.type_text || 'Text Input', icon: <Type size={14} /> },
                        { value: 'email', label: t.type_email || 'Email Input', icon: <Mail size={14} /> },
                        { value: 'number', label: t.type_number || 'Number Input', icon: <Hash size={14} /> },
                        { value: 'textarea', label: t.type_textarea || 'Text Area', icon: <AlignLeft size={14} /> },
                        { value: 'checkbox', label: t.type_checkbox || 'Checkbox', icon: <CheckCircle2 size={14} /> },
                        { value: 'radio', label: t.type_radio || 'Radio Selection', icon: <MessageSquare size={14} /> }
                      ]}
                      value={tempField.type}
                      onChange={(val) => setTempField({ ...tempField, type: val })}
                      placeholder="Select Component Type..."
                      className="h-11 bg-slate-50/30 border-slate-200 text-slate-700 font-bold text-[13px] hover:bg-white transition-all"
                    />
                    <p className="text-[10px] text-slate-400 font-bold px-1 m-0">Choose how the field will appear to your users.</p>
                  </div>

                  {/* Selection Options (Conditional) */}
                  {['checkbox', 'radio'].includes(tempField.type) && (
                    <div className="space-y-4 animate-in slide-in-from-top-2 duration-300 border-t border-slate-50 pt-8">
                      <div className="flex items-center justify-between px-1">
                         <div className="flex items-center gap-2">
                            <List className="w-4 h-4 text-slate-400" />
                            <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Selection Options</Label>
                         </div>
                         <div className="flex items-center bg-slate-100 p-1 rounded-lg">
                            <button 
                               onClick={() => setOptionsViewMode('interactive')}
                               className={`px-3 py-1 rounded-md text-[9px] font-black uppercase transition-all ${optionsViewMode === 'interactive' ? 'bg-white shadow-sm text-[#004449]' : 'text-slate-400 hover:text-slate-600'}`}
                            >
                               Interactive
                            </button>
                            <button 
                               onClick={() => setOptionsViewMode('bulk')}
                               className={`px-3 py-1 rounded-md text-[9px] font-black uppercase transition-all ${optionsViewMode === 'bulk' ? 'bg-white shadow-sm text-[#004449]' : 'text-slate-400 hover:text-slate-600'}`}
                            >
                               Bulk
                            </button>
                         </div>
                      </div>

                      {optionsViewMode === 'interactive' ? (
                         <div className="space-y-2.5">
                            {(Array.isArray(tempField.options) ? tempField.options : []).map((option, idx) => (
                               <div key={idx} className="flex items-center gap-3 animate-in fade-in slide-in-from-left-2 duration-200">
                                  <div className="grow grid grid-cols-2 gap-3">
                                     <div className="relative">
                                        <div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-300"><Type size={12} /></div>
                                        <input 
                                           value={option.label}
                                           onChange={(e) => {
                                              const newOpts = [...(tempField.options as {label: string, value: string}[])];
                                              newOpts[idx].label = e.target.value;
                                              setTempField({...tempField, options: newOpts});
                                           }}
                                           placeholder="Option Label"
                                           className="w-full h-10 pl-8 pr-3 bg-slate-50/50 border border-slate-200 rounded-lg text-xs font-bold focus:bg-white focus:border-[#004449] outline-none transition-all"
                                        />
                                     </div>
                                     <div className="relative">
                                        <div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-300"><Braces size={12} /></div>
                                        <input 
                                           value={option.value}
                                           onChange={(e) => {
                                              const newOpts = [...(tempField.options as {label: string, value: string}[])];
                                              newOpts[idx].value = e.target.value;
                                              setTempField({...tempField, options: newOpts});
                                           }}
                                           placeholder="Option Value"
                                           className="w-full h-10 pl-8 pr-3 bg-slate-50/50 border border-slate-200 rounded-lg text-xs font-bold focus:bg-white focus:border-[#004449] outline-none transition-all"
                                        />
                                     </div>
                                  </div>
                                  <button 
                                     onClick={() => {
                                        const newOpts = (tempField.options as {label: string, value: string}[]).filter((_, i) => i !== idx);
                                        setTempField({...tempField, options: newOpts});
                                     }}
                                     className="p-2 text-slate-300 hover:text-rose-500 hover:bg-rose-50 rounded-lg transition-all"
                                  >
                                     <Trash size={16} />
                                  </button>
                               </div>
                            ))}
                            <button 
                               onClick={() => {
                                  const currentOpts = Array.isArray(tempField.options) ? tempField.options : [];
                                  setTempField({...tempField, options: [...currentOpts, {label: '', value: ''}]});
                               }}
                               className="w-full py-3 border border-dashed border-slate-200 rounded-lg text-[11px] font-black text-slate-400 uppercase tracking-widest hover:border-[#004449]/30 hover:text-[#004449] hover:bg-[#004449]/5 transition-all flex items-center justify-center gap-2 group"
                            >
                               <Plus size={14} className="group-hover:scale-110 transition-transform" />
                               Add New Option
                            </button>
                         </div>
                      ) : (
                         <div className="relative">
                            <textarea
                              value={Array.isArray(tempField.options) ? tempField.options.map((o: { label: string; value: string }) => `${o.label}|${o.value}`).join('\n') : (tempField.options as string) || ''}
                              onChange={(e) => setTempField({ ...tempField, options: e.target.value })}
                              className="w-full h-32 p-4 bg-slate-50/20 border border-slate-200 rounded-lg focus:border-[#004449] focus:bg-white outline-none transition-all text-xs font-mono font-bold leading-relaxed"
                              placeholder="Option 1|value1&#10;Option 2|value2"
                            />
                            <div className="absolute top-3 right-3 text-slate-300 pointer-events-none"><Brackets size={16} /></div>
                         </div>
                      )}
                      <p className="text-[10px] text-slate-400 font-bold px-1 m-0">Provide labels and internal values for the selection options.</p>
                    </div>
                  )}

                  {/* Field Behavior (Switches) - Now at the bottom */}
                  <div className="space-y-4 border-t border-slate-50 pt-8">
                    {/* Enable Switch Card */}
                    <div className="bg-slate-50/30 border border-slate-100 rounded-xl overflow-hidden transition-all hover:bg-white hover:shadow-sm">
                      <div className="p-4 flex items-center justify-between">
                        <div className="flex-1">
                          <ModernCardHeader 
                            title="Enable Field" 
                            description="Show this field on your signup form." 
                            icon={Eye} 
                            className="!border-none !p-0 !bg-transparent"
                          />
                        </div>
                        <Switch 
                          checked={tempField.enabled} 
                          onCheckedChange={(checked) => setTempField({...tempField, enabled: checked})} 
                        />
                      </div>
                    </div>

                    {/* Required Switch Card */}
                    <div className="bg-slate-50/30 border border-slate-100 rounded-xl overflow-hidden transition-all hover:bg-white hover:shadow-sm">
                      <div className="p-4 flex items-center justify-between">
                        <div className="flex-1">
                          <ModernCardHeader 
                            title="Required Field" 
                            description="Users must fill this field to register." 
                            icon={AlertCircle} 
                            className="!border-none !p-0 !bg-transparent"
                          />
                        </div>
                        <Switch 
                          checked={tempField.required} 
                          onCheckedChange={(checked) => setTempField({...tempField, required: checked})} 
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Drawer Footer */}
              <div className="p-6 bg-slate-50 border-t border-slate-100 flex gap-3 sticky bottom-0">
                <button
                  onClick={() => setEditingField(null)}
                  className="px-8 py-3 rounded-lg text-slate-500 font-bold hover:bg-slate-200 transition-colors text-[13px] flex items-center gap-2"
                >
                  <ChevronLeft size={16} />
                  {t.close || t.back || "Back"}
                </button>
                <button
                  onClick={async () => {
                    const newCf = { ...(settings.custom_fields || {}) };
                    const oldKey = editingField;
                    const newKey = tempField.key || editingField;

                    if (!newKey) return;

                    let options = tempField.options;
                    if (['checkbox', 'radio'].includes(tempField.type) && typeof options === 'string') {
                      options = options.split('\n').map((line: string) => {
                        const [l, v] = line.split('|');
                        return { label: l?.trim() || '', value: (v || l)?.trim() || '' };
                      }).filter((o: { label: string; value: string }) => o.label);
                    }

                    const fieldData = {
                      label: tempField.label,
                      type: tempField.type,
                      enabled: tempField.enabled ?? true,
                      required: tempField.required ?? false,
                      options: options
                    };

                    let nextSettings = { ...settings };
                    
                    if (tempField.isNew) {
                      newCf[newKey] = fieldData;
                      // Ensure we are appending to the latest order from settings
                      const currentOrder = (settings.field_order || 'first_name,last_name,email,phone,password').split(',').filter(Boolean);
                      const newOrder = [...currentOrder, newKey];
                      nextSettings = { ...settings, custom_fields: newCf, field_order: newOrder.join(',') };
                    } else {
                      if (oldKey !== newKey) {
                        delete newCf[oldKey];
                        const currentOrder = (settings.field_order || '').split(',').filter(Boolean);
                        const newOrder = currentOrder.map((k: string) => k === oldKey ? newKey : k);
                        newCf[newKey] = fieldData;
                        nextSettings = { ...settings, custom_fields: newCf, field_order: newOrder.join(',') };
                      } else {
                        newCf[oldKey] = fieldData;
                        nextSettings = { ...settings, custom_fields: newCf };
                      }
                    }

                    // Atomic update and save
                    await saveSettingsAtomic(nextSettings);
                    setEditingField(null);
                  }}
                  className="grow bg-[#004449] text-white rounded-lg font-bold shadow-lg shadow-[#004449]/10 hover:bg-[#003337] active:scale-[0.98] transition-all text-[13px] py-3 flex items-center justify-center gap-2"
                >
                  <Save size={16} />
                  {t.apply_changes || t.save_changes || "Save Changes"}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      <PersonalizationDialog
        open={isPersonalizationOpen}
        onOpenChange={setIsPersonalizationOpen}
        onInsert={(placeholder) => {
          const textarea = document.getElementById(personalizationEditorId) as HTMLTextAreaElement;
          if (textarea) {
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const fieldKey = personalizationEditorId; // Always matches the setting key
            const currentVal = (settings[fieldKey] as string) || '';
            const newVal = currentVal.substring(0, start) + placeholder + currentVal.substring(end);
            updateSetting(fieldKey, newVal);

            setTimeout(() => {
              textarea.focus();
              textarea.selectionStart = textarea.selectionEnd = start + placeholder.length;
            }, 0);
          }
        }}
        placeholders={{
          '{{otp}}': 'Verification Code',
          '{{site_name}}': 'Your Site Name',
          '{{user_login}}': 'User Username',
          '{{user_email}}': 'User Email',
          '{{wp-email}}': 'WordPress Email',
          '{{tagline}}': 'Site Tagline'
        }}
        triggerKey="user_registration"
      />
    </SettingsLayout>
  );
};

export default RegistrationFormSettings;
