import { For, Match, Show, Switch, createEffect, createMemo, createSignal, onMount } from 'solid-js';
 
type VerificationType = 'IDENTITY' | 'BUSINESS' | 'MIXED' | 'NONE';

type OnboardingFieldType = 'text' | 'email' | 'phone' | 'number' | 'textarea' | 'select' | 'multi-select' | 'pincode' | 'file';

type OnboardingField = {
  id: string;
  label: string;
  key: string;
  type: OnboardingFieldType;
  required: boolean;
  placeholder?: string;
  help?: string;
  options?: string[];
  allowedFileTypes?: string[];
  condition?: { fieldKey: string; equals: string };
};

type OnboardingStep = {
  id: string;
  name: string;
  description: string;
  required: boolean;
  fields: OnboardingField[];
};

type OnboardingSubmission = {
  id: string;
  userId: string;
  userName: string;
  roleKey: string;
  status: 'IN_PROGRESS' | 'SUBMITTED' | 'PENDING_APPROVAL' | 'APPROVED' | 'REJECTED' | 'DOCUMENT_REQUESTED';
  createdAt: string;
  updatedAt: string;
};

type AuditEvent = {
  id: string;
  event: 'ONBOARDING_CREATED' | 'ONBOARDING_UPDATED' | 'ONBOARDING_PUBLISHED' | 'ONBOARDING_PREVIEWED';
  actor: string;
  target: string;
  createdAt: string;
};

type OnboardingSchema = {
  id: string;
  name: string;
  code: string;
  userType: 'CUSTOMER' | 'PROFESSIONAL' | 'COMPANY' | 'JOBSEEKER';
  role?: string;
  description: string;
  steps: OnboardingStep[];
  requiredDocuments: string[];
  verificationType: VerificationType;
  status: 'ACTIVE' | 'INACTIVE' | 'DRAFT';
  version: string;
  updatedAt: string;
};

const FALLBACK_SCHEMAS: OnboardingSchema[] = [
  {
    id: 'os1',
    name: 'Professional Photographer Flow',
    code: 'ONB-PRO-PHOTO',
    userType: 'PROFESSIONAL',
    role: 'Photographer',
    description: 'Onboarding for professional photographers (India localization).',
    verificationType: 'IDENTITY',
    requiredDocuments: ['Aadhaar Card', 'PAN Card', 'Portfolio Sample'],
    steps: [
      {
        id: 'st_role',
        name: 'Choose Role',
        description: 'Confirm your onboarding role and specialization.',
        required: true,
        fields: [
          { id: 'f_role', key: 'role', label: 'Professional Role', type: 'select', required: true, options: ['Photographer', 'Makeup Artist', 'Tutor', 'Developer', 'Video Editor', 'UGC Content Creator'] },
          { id: 'f_special', key: 'specialization', label: 'Specialization', type: 'select', required: true, options: ['Wedding', 'Product', 'Corporate', 'Portrait', 'Events'] },
        ],
      },
      {
        id: 'st_profile',
        name: 'Profile Details',
        description: 'Tell us about your profile.',
        required: true,
        fields: [
          { id: 'f_name', key: 'full_name', label: 'Full Name', type: 'text', required: true, placeholder: 'e.g., Ashwin Kumar' },
          { id: 'f_email', key: 'email', label: 'Email', type: 'email', required: true, placeholder: 'e.g., ashwin@example.com' },
          { id: 'f_phone', key: 'phone', label: 'Phone Number', type: 'phone', required: true, placeholder: 'e.g., +91 98765 43210' },
        ],
      },
      {
        id: 'st_location',
        name: 'Contact & Location',
        description: 'Your contact address details.',
        required: true,
        fields: [
          { id: 'f_city', key: 'city', label: 'City', type: 'text', required: true, placeholder: 'e.g., Chennai' },
          { id: 'f_pin', key: 'pincode', label: 'PIN Code', type: 'pincode', required: true, placeholder: 'e.g., 600001' },
          { id: 'f_addr', key: 'address', label: 'Address', type: 'textarea', required: true, placeholder: 'House no, Street, Area' },
        ],
      },
      {
        id: 'st_portfolio',
        name: 'Portfolio & Submission',
        description: 'Upload your portfolio sample.',
        required: true,
        fields: [
          { id: 'f_portfolio', key: 'portfolio_file', label: 'Portfolio File', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
          { id: 'f_about', key: 'about', label: 'About You', type: 'textarea', required: true, placeholder: 'Tell us about your work…' },
        ],
      },
      {
        id: 'st_identity',
        name: 'Identity Verification',
        description: 'Upload identity documents for verification.',
        required: true,
        fields: [
          { id: 'f_aadhaar', key: 'aadhaar', label: 'Aadhaar Card', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
          { id: 'f_pan', key: 'pan', label: 'PAN Card', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
        ],
      },
    ],
    status: 'ACTIVE',
    version: '1.2.0',
    updatedAt: '2026-03-27',
  },
  {
    id: 'os2',
    name: 'Basic Company Onboarding',
    code: 'ONB-COMP-BASIC',
    userType: 'COMPANY',
    description: 'Company onboarding with business verification.',
    verificationType: 'BUSINESS',
    requiredDocuments: ['GST Certificate', 'Company PAN', 'Incorporation Certificate'],
    steps: [
      {
        id: 'st_comp_identity',
        name: 'Company Identity',
        description: 'Provide company identity details.',
        required: true,
        fields: [
          { id: 'f_company_name', key: 'company_name', label: 'Company Name', type: 'text', required: true, placeholder: 'e.g., Tech Solutions Inc' },
          { id: 'f_industry', key: 'industry', label: 'Industry', type: 'select', required: true, options: ['Software', 'Design', 'Logistics', 'Manufacturing', 'Services'] },
        ],
      },
      {
        id: 'st_comp_contact',
        name: 'Contact Details',
        description: 'Primary contact information.',
        required: true,
        fields: [
          { id: 'f_c_email', key: 'email', label: 'Company Email', type: 'email', required: true, placeholder: 'e.g., hr@company.com' },
          { id: 'f_c_phone', key: 'phone', label: 'Phone Number', type: 'phone', required: true, placeholder: 'e.g., +91 98765 43210' },
          { id: 'f_c_city', key: 'city', label: 'City', type: 'text', required: true, placeholder: 'e.g., Chennai' },
        ],
      },
      {
        id: 'st_hiring',
        name: 'Hiring Preferences',
        description: 'Tell us about hiring needs.',
        required: true,
        fields: [
          { id: 'f_roles', key: 'hire_for', label: 'Hiring For', type: 'multi-select', required: true, options: ['Developers', 'Designers', 'Photographers', 'UGC Content Creators', 'Tutors'] },
          { id: 'f_budget', key: 'budget', label: 'Monthly Hiring Budget (₹)', type: 'number', required: true, placeholder: 'e.g., 50000' },
        ],
      },
      {
        id: 'st_business',
        name: 'Business Verification',
        description: 'Upload business documents.',
        required: true,
        fields: [
          { id: 'f_gst', key: 'gst', label: 'GST Certificate', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
          { id: 'f_comp_pan', key: 'company_pan', label: 'Company PAN', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
        ],
      },
    ],
    status: 'ACTIVE',
    version: '1.0.5',
    updatedAt: '2026-03-27',
  },
  {
    id: 'os3',
    name: 'Jobseeker Registration',
    code: 'ONB-JOB-DEFAULT',
    userType: 'JOBSEEKER',
    description: 'Jobseeker registration with identity verification.',
    verificationType: 'IDENTITY',
    requiredDocuments: ['Aadhaar Card', 'Resume'],
    steps: [
      {
        id: 'st_basic',
        name: 'Basic Profile',
        description: 'Fill basic profile details.',
        required: true,
        fields: [
          { id: 'f_js_name', key: 'full_name', label: 'Full Name', type: 'text', required: true, placeholder: 'e.g., Priya Sharma' },
          { id: 'f_js_email', key: 'email', label: 'Email', type: 'email', required: true, placeholder: 'e.g., priya@example.com' },
          { id: 'f_js_phone', key: 'phone', label: 'Phone Number', type: 'phone', required: true, placeholder: 'e.g., +91 98765 43210' },
        ],
      },
      {
        id: 'st_pref',
        name: 'Job Preferences',
        description: 'Your job preferences.',
        required: true,
        fields: [
          { id: 'f_job_type', key: 'job_type', label: 'Job Type', type: 'select', required: true, options: ['Full-time', 'Part-time', 'Contract', 'Internship'] },
          { id: 'f_location', key: 'preferred_location', label: 'Preferred Location', type: 'text', required: true, placeholder: 'e.g., Chennai' },
        ],
      },
      {
        id: 'st_docs',
        name: 'Documents & Links',
        description: 'Upload resume and identity.',
        required: true,
        fields: [
          { id: 'f_resume', key: 'resume', label: 'Resume', type: 'file', required: true, allowedFileTypes: ['PDF'] },
          { id: 'f_js_aadhaar', key: 'aadhaar', label: 'Aadhaar Card', type: 'file', required: true, allowedFileTypes: ['PDF', 'JPG', 'JPEG', 'PNG'] },
        ],
      },
    ],
    status: 'DRAFT',
    version: '2.0.0-rc',
    updatedAt: '2026-03-27',
  },
];

const FALLBACK_SUBMISSIONS: OnboardingSubmission[] = [
  { id: 'sub_1001', userId: 'u_2001', userName: 'Rohit Mehra', roleKey: 'PROFESSIONAL_PHOTOGRAPHER', status: 'PENDING_APPROVAL', createdAt: '2026-03-25', updatedAt: '2026-03-27' },
  { id: 'sub_1002', userId: 'u_2002', userName: 'Tech Solutions Inc', roleKey: 'COMPANY', status: 'DOCUMENT_REQUESTED', createdAt: '2026-03-20', updatedAt: '2026-03-26' },
  { id: 'sub_1003', userId: 'u_2003', userName: 'Priya Sharma', roleKey: 'JOBSEEKER', status: 'SUBMITTED', createdAt: '2026-03-22', updatedAt: '2026-03-22' },
];

const FALLBACK_AUDIT: AuditEvent[] = [
  { id: 'evt_1', event: 'ONBOARDING_CREATED', actor: 'Admin', target: 'ONB-PRO-PHOTO', createdAt: '2026-03-01 10:11' },
  { id: 'evt_2', event: 'ONBOARDING_UPDATED', actor: 'Admin', target: 'ONB-COMP-BASIC', createdAt: '2026-03-15 16:40' },
  { id: 'evt_3', event: 'ONBOARDING_PREVIEWED', actor: 'Admin', target: 'ONB-JOB-DEFAULT', createdAt: '2026-03-26 09:20' },
];

function StatusBadge(props: { status: string }) {
  const active = () => props.status === 'ACTIVE';
  const draft = () => props.status === 'DRAFT';
  return (
    <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${active() ? '#FFD8C2' : draft() ? '#E5E7EB' : '#D1D5DB'};background:${active() ? '#FFF1EB' : draft() ? '#F9FAFB' : '#F3F4F6'};color:${active() ? '#FF5E13' : draft() ? '#6B7280' : '#4B5563'};padding:2px 10px;font-size:12px;font-weight:500`}>
      <span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${active() ? '#FF5E13' : draft() ? '#9CA3AF' : '#9CA3AF'};margin-right:5px;flex-shrink:0`} />
      {active() ? 'Active' : draft() ? 'Draft' : 'Inactive'}
    </span>
  );
}

export default function OnboardingManagementPage() {
  const [pageTab, setPageTab] = createSignal<'flows' | 'builder' | 'preview' | 'submissions' | 'audit'>('flows');
  const [listTab, setListTab] = createSignal<'all' | 'view'>('all');
  const [builderTab, setBuilderTab] = createSignal<'general' | 'steps' | 'fields' | 'verification' | 'success' | 'preview'>('general');
  const [flowViewTab, setFlowViewTab] = createSignal<'overview' | 'steps' | 'submissions'>('overview');
  
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal('all');
  const [sortBy, setSortBy] = createSignal<'name_asc' | 'name_desc' | 'steps_desc' | 'steps_asc'>('name_asc');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);
  const [rows, setRows] = createSignal<OnboardingSchema[]>([]);
  const [viewingSchema, setViewingSchema] = createSignal<OnboardingSchema | null>(null);
  const [editingId, setEditingId] = createSignal<string | null>(null);
  const [openMenuId, setOpenMenuId] = createSignal<string | null>(null);

  const [flowName, setFlowName] = createSignal('');
  const [flowCode, setFlowCode] = createSignal('');
  const [flowDescription, setFlowDescription] = createSignal('');
  const [flowUserType, setFlowUserType] = createSignal<OnboardingSchema['userType']>('PROFESSIONAL');
  const [flowRole, setFlowRole] = createSignal('');
  const [flowStatus, setFlowStatus] = createSignal<OnboardingSchema['status']>('DRAFT');
  const [flowVersion, setFlowVersion] = createSignal('1.0.0');
  const [flowVerificationType, setFlowVerificationType] = createSignal<VerificationType>('IDENTITY');
  const [flowRequiredDocuments, setFlowRequiredDocuments] = createSignal<string[]>([]);
  const [flowSteps, setFlowSteps] = createSignal<OnboardingStep[]>([]);
  const [successTitle, setSuccessTitle] = createSignal('Application Submitted');
  const [successMessage, setSuccessMessage] = createSignal('Your onboarding submission has been received.');

  const [selectedStepId, setSelectedStepId] = createSignal<string | null>(null);
  const selectedStep = createMemo(() => flowSteps().find(s => s.id === selectedStepId()) || null);
  const [editingStepName, setEditingStepName] = createSignal('');
  const [editingStepDescription, setEditingStepDescription] = createSignal('');
  const [editingStepRequired, setEditingStepRequired] = createSignal(true);

  const [fieldEditorOpen, setFieldEditorOpen] = createSignal(false);
  const [editingFieldId, setEditingFieldId] = createSignal<string | null>(null);
  const [fieldLabel, setFieldLabel] = createSignal('');
  const [fieldKey, setFieldKey] = createSignal('');
  const [fieldType, setFieldType] = createSignal<OnboardingFieldType>('text');
  const [fieldRequired, setFieldRequired] = createSignal(true);
  const [fieldPlaceholder, setFieldPlaceholder] = createSignal('');
  const [fieldHelp, setFieldHelp] = createSignal('');
  const [fieldOptionsText, setFieldOptionsText] = createSignal('');
  const [fieldAllowedTypesText, setFieldAllowedTypesText] = createSignal('PDF, JPG, JPEG, PNG');
  const [fieldConditionKey, setFieldConditionKey] = createSignal('');
  const [fieldConditionEquals, setFieldConditionEquals] = createSignal('');

  const [previewDevice, setPreviewDevice] = createSignal<'desktop' | 'mobile'>('desktop');
  const [previewScenario, setPreviewScenario] = createSignal<'empty' | 'sample' | 'errors' | 'success' | 'pending' | 'rejected' | 'document_requested'>('sample');
  const [previewStepIndex, setPreviewStepIndex] = createSignal(0);
  const [previewMode, setPreviewMode] = createSignal<'stepper' | 'review' | 'result'>('stepper');
  const [previewSubmitted, setPreviewSubmitted] = createSignal(false);
  const [previewData, setPreviewData] = createSignal<Record<string, string>>({});

  const [subSearch, setSubSearch] = createSignal('');
  const [subStatusFilter, setSubStatusFilter] = createSignal<'all' | OnboardingSubmission['status']>('all');
  const [subSortBy, setSubSortBy] = createSignal<'updated_desc' | 'updated_asc' | 'name_asc' | 'name_desc'>('updated_desc');
  const [subSortMenuOpen, setSubSortMenuOpen] = createSignal(false);
  const [subFilterMenuOpen, setSubFilterMenuOpen] = createSignal(false);

  const [auditSearch, setAuditSearch] = createSignal('');

  const API = '/api/gateway';

  const load = async () => {
    try {
      const res = await fetch(`${API}/api/admin/onboarding-config`);
      if (!res.ok) throw new Error('Fetch failed');
      const data = await res.json();
      const items = Array.isArray(data) ? data : (data.items || []);
      const list = items.map((c: any) => ({
        id: c.id,
        name: `${c.role_key} Onboarding Flow`,
        code: `ONB-${c.role_key.toUpperCase()}-${c.version}`,
        userType: 'PROFESSIONAL', 
        role: c.role_key,
        description: `Standard onboarding flow for ${c.role_key}`,
        steps: [], 
        requiredDocuments: [],
        verificationType: 'IDENTITY',
        status: (c.is_active ? 'ACTIVE' : 'DRAFT') as 'ACTIVE' | 'DRAFT',
        version: `v${c.version}`,
        updatedAt: new Date(c.updated_at).toLocaleDateString()
      } as OnboardingSchema));
      setRows(list);
    } catch (e) {
      console.error('Onboarding load error:', e);
      setRows([]);
    }
  };

  onMount(() => void load());

  const filteredRows = createMemo(() => {
    let r = rows();
    if (statusFilter() !== 'all') r = r.filter((d) => d.status === statusFilter().toUpperCase());
    const q = search().toLowerCase();
    if (q) {
      r = r.filter(r => r.name.toLowerCase().includes(q) || r.code.toLowerCase().includes(q));
    }
    const sorted = [...r];
    const mode = sortBy();
    sorted.sort((a, b) => {
      if (mode === 'name_desc') return b.name.localeCompare(a.name);
      if (mode === 'steps_desc') return b.steps.length - a.steps.length;
      if (mode === 'steps_asc') return a.steps.length - b.steps.length;
      return a.name.localeCompare(b.name);
    });
    return sorted;
  });

  const resetBuilder = () => {
    setEditingId(null);
    setViewingSchema(null);
    setBuilderTab('general');
    setFlowName('');
    setFlowCode('');
    setFlowDescription('');
    setFlowUserType('PROFESSIONAL');
    setFlowRole('');
    setFlowStatus('DRAFT');
    setFlowVersion('1.0.0');
    setFlowVerificationType('IDENTITY');
    setFlowRequiredDocuments([]);
    setFlowSteps([]);
    setSuccessTitle('Application Submitted');
    setSuccessMessage('Your onboarding submission has been received.');
    setSelectedStepId(null);
    setEditingStepName('');
    setEditingStepDescription('');
    setEditingStepRequired(true);
    setFieldEditorOpen(false);
    setEditingFieldId(null);
    setFieldLabel('');
    setFieldKey('');
    setFieldType('text');
    setFieldRequired(true);
    setFieldPlaceholder('');
    setFieldHelp('');
    setFieldOptionsText('');
    setFieldAllowedTypesText('PDF, JPG, JPEG, PNG');
    setFieldConditionKey('');
    setFieldConditionEquals('');
    setPreviewDevice('desktop');
    setPreviewScenario('sample');
    setPreviewStepIndex(0);
    setPreviewMode('stepper');
    setPreviewSubmitted(false);
    setPreviewData({});
  };

  const hydrateBuilderFromSchema = (row: OnboardingSchema, mode: 'edit' | 'preview') => {
    setViewingSchema(row);
    setEditingId(mode === 'edit' ? row.id : null);
    setFlowName(row.name);
    setFlowCode(row.code);
    setFlowDescription(row.description);
    setFlowUserType(row.userType);
    setFlowRole(row.role || '');
    setFlowStatus(row.status);
    setFlowVersion(row.version);
    setFlowVerificationType(row.verificationType);
    setFlowRequiredDocuments([...row.requiredDocuments]);
    setFlowSteps(row.steps.map(s => ({ ...s, fields: s.fields.map(f => ({ ...f })) })));
    setSelectedStepId(row.steps[0]?.id ?? null);
    setPreviewStepIndex(0);
    setPreviewMode('stepper');
    setPreviewSubmitted(false);
    setPreviewData({});
  };

  const openCreate = () => {
    resetBuilder();
    setPageTab('builder');
  };

  const openEdit = (row: OnboardingSchema) => {
    resetBuilder();
    hydrateBuilderFromSchema(row, 'edit');
    setPageTab('builder');
    setOpenMenuId(null);
  };

  const openDetail = (row: OnboardingSchema) => {
    setViewingSchema(row);
    setListTab('view');
    setFlowViewTab('overview');
    setPageTab('flows');
    setOpenMenuId(null);
  };

  const openPreview = (row: OnboardingSchema) => {
    resetBuilder();
    hydrateBuilderFromSchema(row, 'preview');
    setPageTab('preview');
    setOpenMenuId(null);
  };

  const moveStep = (stepId: string, dir: -1 | 1) => {
    const list = flowSteps();
    const idx = list.findIndex(s => s.id === stepId);
    const next = idx + dir;
    if (idx < 0 || next < 0 || next >= list.length) return;
    const copy = [...list];
    const [item] = copy.splice(idx, 1);
    copy.splice(next, 0, item);
    setFlowSteps(copy);
  };

  const addStep = () => {
    const id = `st_${Math.random().toString(16).slice(2)}`;
    const step: OnboardingStep = { id, name: 'New Step', description: 'Step description', required: true, fields: [] };
    setFlowSteps(s => [...s, step]);
    setSelectedStepId(id);
    setBuilderTab('steps');
  };

  const deleteStep = (stepId: string) => {
    const next = flowSteps().filter(s => s.id !== stepId);
    setFlowSteps(next);
    if (selectedStepId() === stepId) setSelectedStepId(next[0]?.id ?? null);
  };

  createEffect(() => {
    const s = selectedStep();
    if (!s) return;
    setEditingStepName(s.name);
    setEditingStepDescription(s.description);
    setEditingStepRequired(s.required);
  });

  const saveStepEdits = () => {
    const s = selectedStep();
    if (!s) return;
    setFlowSteps(list =>
      list.map(st =>
        st.id === s.id
          ? { ...st, name: editingStepName().trim() || st.name, description: editingStepDescription().trim(), required: editingStepRequired() }
          : st,
      ),
    );
  };

  const openCreateField = () => {
    if (!selectedStep()) return;
    setEditingFieldId(null);
    setFieldLabel('');
    setFieldKey('');
    setFieldType('text');
    setFieldRequired(true);
    setFieldPlaceholder('');
    setFieldHelp('');
    setFieldOptionsText('');
    setFieldAllowedTypesText('PDF, JPG, JPEG, PNG');
    setFieldConditionKey('');
    setFieldConditionEquals('');
    setFieldEditorOpen(true);
  };

  const openEditField = (field: OnboardingField) => {
    setEditingFieldId(field.id);
    setFieldLabel(field.label);
    setFieldKey(field.key);
    setFieldType(field.type);
    setFieldRequired(field.required);
    setFieldPlaceholder(field.placeholder || '');
    setFieldHelp(field.help || '');
    setFieldOptionsText((field.options || []).join('\n'));
    setFieldAllowedTypesText((field.allowedFileTypes || []).join(', '));
    setFieldConditionKey(field.condition?.fieldKey || '');
    setFieldConditionEquals(field.condition?.equals || '');
    setFieldEditorOpen(true);
  };

  const saveField = () => {
    const step = selectedStep();
    if (!step) return;
    const label = fieldLabel().trim();
    const key = fieldKey().trim();
    if (!label || !key) return;

    const field: OnboardingField = {
      id: editingFieldId() || `f_${Math.random().toString(16).slice(2)}`,
      label,
      key,
      type: fieldType(),
      required: fieldRequired(),
      placeholder: fieldPlaceholder().trim() || undefined,
      help: fieldHelp().trim() || undefined,
      options:
        fieldType() === 'select' || fieldType() === 'multi-select'
          ? fieldOptionsText()
              .split('\n')
              .map(s => s.trim())
              .filter(Boolean)
          : undefined,
      allowedFileTypes:
        fieldType() === 'file'
          ? fieldAllowedTypesText()
              .split(',')
              .map(s => s.trim().toUpperCase())
              .filter(Boolean)
          : undefined,
      condition: fieldConditionKey().trim() && fieldConditionEquals().trim() ? { fieldKey: fieldConditionKey().trim(), equals: fieldConditionEquals().trim() } : undefined,
    };

    setFlowSteps(list =>
      list.map(s => {
        if (s.id !== step.id) return s;
        const exists = s.fields.some(f => f.id === field.id);
        return { ...s, fields: exists ? s.fields.map(f => (f.id === field.id ? field : f)) : [...s.fields, field] };
      }),
    );
    setFieldEditorOpen(false);
  };

  const deleteField = (fieldId: string) => {
    const step = selectedStep();
    if (!step) return;
    setFlowSteps(list => list.map(s => (s.id === step.id ? { ...s, fields: s.fields.filter(f => f.id !== fieldId) } : s)));
  };

  const previewSteps = createMemo(() => flowSteps());
  const previewCurrentStep = createMemo(() => previewSteps()[previewStepIndex()] || null);
  const previewProgress = createMemo(() => {
    const total = Math.max(1, previewSteps().length);
    return Math.round(((Math.min(previewStepIndex(), total - 1) + 1) / total) * 100);
  });

  const fieldVisibleInPreview = (field: OnboardingField) => {
    const c = field.condition;
    if (!c) return true;
    return (previewData()[c.fieldKey] || '') === c.equals;
  };

  const previewErrors = createMemo(() => {
    if (previewScenario() !== 'errors') return new Set<string>();
    const step = previewCurrentStep();
    const errs = new Set<string>();
    if (!step) return errs;
    for (const f of step.fields) {
      if (!fieldVisibleInPreview(f)) continue;
      if (f.required && !previewData()[f.key]) errs.add(f.key);
    }
    return errs;
  });

  const goNextPreview = () => {
    if (previewMode() === 'result') return;
    if (previewMode() === 'review') {
      setPreviewMode('result');
      setPreviewSubmitted(true);
      return;
    }
    if (previewScenario() === 'errors' && previewErrors().size > 0) return;
    const next = previewStepIndex() + 1;
    if (next >= previewSteps().length) {
      setPreviewMode('review');
      return;
    }
    setPreviewStepIndex(next);
  };

  const goPrevPreview = () => {
    if (previewMode() === 'result') {
      setPreviewMode('review');
      setPreviewSubmitted(false);
      return;
    }
    if (previewMode() === 'review') {
      setPreviewMode('stepper');
      setPreviewStepIndex(Math.max(0, previewSteps().length - 1));
      return;
    }
    setPreviewStepIndex(i => Math.max(0, i - 1));
  };

  const submissionsFiltered = createMemo(() => {
    let r: OnboardingSubmission[] = [];
    const q = subSearch().trim().toLowerCase();
    if (q) r = r.filter(s => s.id.toLowerCase().includes(q) || s.userName.toLowerCase().includes(q) || s.userId.toLowerCase().includes(q));
    if (subStatusFilter() !== 'all') r = r.filter(s => s.status === subStatusFilter());
    const sorted = [...r];
    sorted.sort((a, b) => {
      if (subSortBy() === 'updated_asc') return a.updatedAt.localeCompare(b.updatedAt);
      if (subSortBy() === 'name_asc') return a.userName.localeCompare(b.userName);
      if (subSortBy() === 'name_desc') return b.userName.localeCompare(a.userName);
      return b.updatedAt.localeCompare(a.updatedAt);
    });
    return sorted;
  });

  const auditFiltered = createMemo(() => {
    const q = auditSearch().trim().toLowerCase();
    const logs: AuditEvent[] = [];
    if (!q) return logs;
    return logs.filter(e => e.event.toLowerCase().includes(q) || e.actor.toLowerCase().includes(q) || e.target.toLowerCase().includes(q));
  });

  const normalizeLabel = (s: string) => s.split('_').map(w => w.charAt(0) + w.slice(1).toLowerCase()).join(' ');

  const previewResult = createMemo(() => {
    if (!previewSubmitted()) return null;
    if (previewScenario() === 'pending') return { title: 'Pending Approval', desc: 'Your submission is pending admin approval.' };
    if (previewScenario() === 'rejected') return { title: 'Rejected', desc: 'Your submission was rejected. Please update and resubmit.' };
    if (previewScenario() === 'document_requested') return { title: 'Document Requested', desc: 'Additional documents have been requested. Please upload and resubmit.' };
    return { title: successTitle(), desc: successMessage() };
  });

  const VerificationBadge = (props: { type: VerificationType }) => (
    <span style="display:inline-flex;align-items:center;border-radius:9999px;border:1px solid #E5E7EB;background:#F9FAFB;color:#374151;padding:2px 10px;font-size:12px;font-weight:600">
      {props.type === 'IDENTITY' ? 'Identity Verification' : props.type === 'BUSINESS' ? 'Business Verification' : props.type === 'MIXED' ? 'Mixed Verification' : 'No Verification'}
    </span>
  );

  return (
      <div class="w-full space-y-6 pb-8">
        <div style="margin-bottom: 1.5rem">
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">External Onboarding Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Flows • Builder • Preview • Submissions • Audit Logs</p>
        </div>

        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          {([
            { key: 'flows', label: 'Flows' },
            { key: 'builder', label: 'Builder' },
            { key: 'preview', label: 'Preview' },
            { key: 'submissions', label: 'Submissions' },
            { key: 'audit', label: 'Audit Logs' },
          ] as const).map(tab => (
            <button
              type="button"
              onClick={() => setPageTab(tab.key)}
              style={`padding-bottom:12px;font-size:14px;font-weight:600;background:none;border:none;cursor:pointer;${pageTab() === tab.key ? 'color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px' : 'color:#6B7280'}`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        <Switch>
          <Match when={pageTab() === 'flows'}>
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
              <div>
                <h2 style="font-size:18px;font-weight:800;color:#111827">Onboarding Flow Management</h2>
                <p style="margin-top:4px;font-size:13px;color:#6B7280">Create, edit, duplicate, activate/deactivate, and preview real onboarding UI.</p>
              </div>
              <div style="display:flex;align-items:center;gap:10px">
                <button type="button" style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:600;color:#374151;cursor:pointer">Import Flow</button>
                <button type="button" style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:600;color:#374151;cursor:pointer">Export Flow</button>
                <button type="button" onClick={openCreate} style="height:36px;border-radius:10px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:700;color:white;border:none;cursor:pointer">Create Onboarding Flow</button>
              </div>
            </div>

            <div style="margin-top:16px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06);overflow:hidden">
              <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;flex-wrap:wrap">
                <input value={search()} onInput={(e) => setSearch(e.currentTarget.value)} placeholder="Search flows..." style="height:34px;flex:1;min-width:220px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none" />
                <div style="position:relative">
                  <button type="button" onClick={() => { setSortMenuOpen(v => !v); setFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:700;color:#374151;cursor:pointer">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                    Sort
                  </button>
                  <Show when={sortMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      {(['name_asc', 'name_desc', 'steps_desc', 'steps_asc'] as const).map((s, i) => (
                        <button type="button" onClick={() => { setSortBy(s); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === s ? '#FF5E13' : '#374151'};background:${sortBy() === s ? '#FFF1EB' : 'transparent'}`}>
                          {['Name (A-Z)', 'Name (Z-A)', 'Steps (High-Low)', 'Steps (Low-High)'][i]}
                        </button>
                      ))}
                    </div>
                  </Show>
                </div>
                <div style="position:relative">
                  <button type="button" onClick={() => { setFilterMenuOpen(v => !v); setSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:700;color:#374151;cursor:pointer">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                    Status
                  </button>
                  <Show when={filterMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:160px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      {(['all', 'active', 'inactive', 'draft'] as const).map((s) => (
                        <button type="button" onClick={() => { setStatusFilter(s); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === s ? '#FF5E13' : '#374151'};background:${statusFilter() === s ? '#FFF1EB' : 'transparent'}`}>
                          {s === 'all' ? 'All Status' : s === 'active' ? 'Active' : s === 'inactive' ? 'Inactive' : 'Draft'}
                        </button>
                      ))}
                    </div>
                  </Show>
                </div>
              </div>

              <div class="overflow-x-auto">
                <table class="min-w-full">
                  <thead>
                    <tr style="background:#0D0D2A;text-align:left">
                      {['Flow Name', 'User Type', 'Total Steps', 'Required Documents', 'Verification Type', 'Status', 'Last Updated', 'Actions'].map(h => (
                        <th style="padding:10px 20px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    <For each={filteredRows()}>
                      {(row) => (
                        <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                          <td style="padding:12px 20px">
                            <div style="display:flex;flex-direction:column;gap:2px">
                              <span style="font-size:14px;font-weight:700;color:#111827">{row.name}</span>
                              <span style="font-size:12px;color:#6B7280;font-family:monospace">{row.code} • {row.version}</span>
                            </div>
                          </td>
                          <td style="padding:12px 20px;font-size:13px;color:#374151;font-weight:600">{row.userType}{row.role ? ` (${row.role})` : ''}</td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{row.steps.length}</td>
                          <td style="padding:12px 20px">
                            <div style="display:flex;flex-wrap:wrap;gap:6px">
                              <For each={row.requiredDocuments.slice(0, 2)}>
                                {d => <span style="display:inline-flex;align-items:center;border-radius:9999px;border:1px solid #E5E7EB;background:#F9FAFB;color:#374151;padding:2px 10px;font-size:12px;font-weight:600">{d}</span>}
                              </For>
                              <Show when={row.requiredDocuments.length > 2}>
                                <span style="display:inline-flex;align-items:center;border-radius:9999px;border:1px solid #E5E7EB;background:#F9FAFB;color:#6B7280;padding:2px 10px;font-size:12px;font-weight:700">+{row.requiredDocuments.length - 2} more</span>
                              </Show>
                            </div>
                          </td>
                          <td style="padding:12px 20px"><VerificationBadge type={row.verificationType} /></td>
                          <td style="padding:12px 20px"><StatusBadge status={row.status} /></td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{row.updatedAt}</td>
                          <td style="padding:12px 20px;position:relative">
                            <button type="button" onClick={() => setOpenMenuId(openMenuId() === row.id ? null : row.id)} style="display:inline-flex;height:32px;width:32px;align-items:center;justify-content:center;border-radius:10px;color:#9CA3AF;background:none;border:none;cursor:pointer">
                              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/></svg>
                            </button>
                            <Show when={openMenuId() === row.id}>
                              <div style="position:absolute;right:20px;top:44px;z-index:20;width:200px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 20px rgba(0,0,0,0.12)">
                                <button type="button" onClick={() => openDetail(row)} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left">View Flow</button>
                                <button type="button" onClick={() => openEdit(row)} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left">Edit Flow</button>
                                <button type="button" onClick={() => openPreview(row)} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left">Preview UI</button>
                              </div>
                            </Show>
                          </td>
                        </tr>
                      )}
                    </For>
                  </tbody>
                </table>
              </div>
            </div>

            <Show when={listTab() === 'view'}>
              <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
                <div style="padding:20px 24px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between">
                  <div>
                    <h2 style="font-size:18px;font-weight:700;color:#111827">{viewingSchema()?.name || 'View Flow'}</h2>
                    <p style="margin-top:2px;font-size:13px;color:#6B7280">{viewingSchema()?.code || ''} {viewingSchema()?.userType ? `• ${viewingSchema()!.userType}` : ''}</p>
                  </div>
                  <Show when={viewingSchema()}><StatusBadge status={viewingSchema()!.status} /></Show>
                </div>

                <div style="display:flex;align-items:center;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 24px;background:#FAFAFA">
                  {(['overview', 'steps', 'submissions'] as const).map((tab, i) => {
                    const labels = ['Overview', 'Steps', 'Submissions'];
                    const active = () => flowViewTab() === tab;
                    return (
                      <button type="button" onClick={() => setFlowViewTab(tab)} style={`position:relative;padding:14px 12px;font-size:13px;font-weight:700;background:none;border:none;cursor:pointer;color:${active() ? '#FF5E13' : '#6B7280'}`}>
                        {labels[i]}
                        <Show when={active()}><span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" /></Show>
                      </button>
                    );
                  })}
                </div>

                <div style="padding:24px">
                  <Show when={viewingSchema()} fallback={<div style="padding:24px;color:#6B7280">Select a flow to view details.</div>}>
                    <Show when={flowViewTab() === 'overview'}>
                      <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
                        <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px">
                          <h3 style="font-size:14px;font-weight:800;color:#111827;margin-bottom:16px">Flow Summary</h3>
                          <div style="display:flex;flex-direction:column;gap:12px">
                            {[
                              { l: 'Version', v: viewingSchema()!.version },
                              { l: 'Total Steps', v: viewingSchema()!.steps.length },
                              { l: 'Verification', v: normalizeLabel(viewingSchema()!.verificationType) },
                              { l: 'Last Updated', v: viewingSchema()!.updatedAt },
                            ].map(item => (
                              <div style="display:flex;justify-content:space-between">
                                <span style="font-size:13px;color:#6B7280">{item.l}</span>
                                <span style="font-size:13px;font-weight:700;color:#111827">{item.v}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                        <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px">
                          <h3 style="font-size:14px;font-weight:800;color:#111827;margin-bottom:16px">Required Documents</h3>
                          <div style="display:flex;flex-wrap:wrap;gap:8px">
                            <For each={viewingSchema()!.requiredDocuments}>
                              {d => <span style="display:inline-flex;align-items:center;border-radius:9999px;border:1px solid #E5E7EB;background:#F9FAFB;color:#374151;padding:2px 10px;font-size:12px;font-weight:600">{d}</span>}
                            </For>
                          </div>
                        </div>
                      </div>
                    </Show>

                    <Show when={flowViewTab() === 'steps'}>
                      <div style="display:flex;flex-direction:column;gap:10px">
                        <For each={viewingSchema()!.steps}>
                          {(s, i) => (
                            <div style="display:flex;align-items:flex-start;gap:12px;padding:14px;border:1px solid #E5E7EB;border-radius:12px;background:white">
                              <div style="width:26px;height:26px;border-radius:50%;background:#0D0D2A;color:white;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800">{i() + 1}</div>
                              <div style="flex:1">
                                <p style="font-size:14px;font-weight:800;color:#111827">{s.name}</p>
                                <p style="margin-top:2px;font-size:12px;color:#6B7280">{s.description}</p>
                                <p style="margin-top:8px;font-size:12px;color:#6B7280">{s.fields.length} fields</p>
                              </div>
                            </div>
                          )}
                        </For>
                      </div>
                    </Show>

                    <Show when={flowViewTab() === 'submissions'}>
                      <div style="border:1px solid #E5E7EB;border-radius:12px;overflow:hidden">
                        <table style="width:100%;border-collapse:collapse">
                          <thead style="background:#F9FAFB">
                            <tr style="text-align:left">
                              {['Submission ID', 'User', 'Status', 'Updated'].map(h => <th style="padding:12px 16px;font-size:11px;font-weight:800;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em">{h}</th>)}
                            </tr>
                          </thead>
                          <tbody>
                            <For each={submissionsFiltered()}>
                              {s => (
                                <tr style="border-top:1px solid #E5E7EB">
                                  <td style="padding:12px 16px;font-size:12px;font-family:monospace;color:#6B7280">{s.id}</td>
                                  <td style="padding:12px 16px;font-size:13px;font-weight:800;color:#111827">{s.userName}</td>
                                  <td style="padding:12px 16px;font-size:13px;color:#6B7280">{normalizeLabel(s.status)}</td>
                                  <td style="padding:12px 16px;font-size:13px;color:#6B7280">{s.updatedAt}</td>
                                </tr>
                              )}
                            </For>
                          </tbody>
                        </table>
                      </div>
                    </Show>
                  </Show>
                </div>

                <div style="display:flex;align-items:center;gap:10px;padding:14px 24px;border-top:1px solid #E5E7EB">
                  <button type="button" onClick={() => viewingSchema() && openEdit(viewingSchema()!)} style="height:36px;border-radius:8px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:700;color:white;border:none;cursor:pointer">Edit Flow</button>
                  <button type="button" onClick={() => { setViewingSchema(null); setListTab('all'); }} style="height:36px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 16px;font-size:13px;font-weight:700;color:#374151;cursor:pointer">Close</button>
                </div>
              </div>
            </Show>
          </Match>

          <Match when={pageTab() === 'builder'}>
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
              <div>
                <h2 style="font-size:18px;font-weight:800;color:#111827">{editingId() ? 'Edit Onboarding Flow' : 'Create Onboarding Flow'}</h2>
                <p style="margin-top:4px;font-size:13px;color:#6B7280">General configuration, step builder, field rules, verification, success state, and preview.</p>
              </div>
              <div style="display:flex;gap:10px">
                <button type="button" onClick={() => setPageTab('flows')} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 16px;font-size:13px;font-weight:700;color:#374151;cursor:pointer">Back to Flows</button>
                <button type="button" style="height:36px;border-radius:10px;background:#0D0D2A;padding:0 18px;font-size:13px;font-weight:800;color:white;border:none;cursor-pointer">{editingId() ? 'Save Changes' : 'Create Flow'}</button>
              </div>
            </div>

            <div style="margin-top:16px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
              <div style="display:flex;align-items:center;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 24px;flex-wrap:wrap">
                {(['general', 'steps', 'fields', 'verification', 'success', 'preview'] as const).map((tab, i) => {
                  const labels = ['General Configuration', 'Step Builder', 'Field Rules', 'Verification Rules', 'Success State', 'Preview'];
                  const active = () => builderTab() === tab;
                  return (
                    <button type="button" onClick={() => setBuilderTab(tab)} style={`position:relative;padding:14px 10px;font-size:13px;font-weight:700;background:none;border:none;cursor:pointer;color:${active() ? '#FF5E13' : '#6B7280'}`}>
                      {labels[i]}
                      <Show when={active()}><span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" /></Show>
                    </button>
                  );
                })}
              </div>

              <div style="padding:24px">
                <Show when={builderTab() === 'general'}>
                  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">Flow Name *</span>
                      <input value={flowName()} onInput={(e) => setFlowName(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827" />
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">Flow Code *</span>
                      <input value={flowCode()} onInput={(e) => setFlowCode(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827;font-family:monospace" />
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">User Type *</span>
                      <select value={flowUserType()} onChange={(e) => setFlowUserType(e.currentTarget.value as any)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;background:white;color:#111827">
                        <option value="CUSTOMER">Customer</option>
                        <option value="PROFESSIONAL">Professional</option>
                        <option value="COMPANY">Company</option>
                        <option value="JOBSEEKER">Jobseeker</option>
                      </select>
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">Version *</span>
                      <input value={flowVersion()} onInput={(e) => setFlowVersion(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827" />
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">Role (optional)</span>
                      <input value={flowRole()} onInput={(e) => setFlowRole(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827" />
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:700;color:#374151">Status *</span>
                      <select value={flowStatus()} onChange={(e) => setFlowStatus(e.currentTarget.value as any)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;background:white;color:#111827">
                        <option value="DRAFT">Draft</option>
                        <option value="ACTIVE">Active</option>
                        <option value="INACTIVE">Inactive</option>
                      </select>
                    </label>
                    <label style="display:block;grid-column:1 / span 2">
                      <span style="font-size:13px;font-weight:700;color:#374151">Description</span>
                      <textarea value={flowDescription()} onInput={(e) => setFlowDescription(e.currentTarget.value)} rows={3} style="display:block;margin-top:6px;width:100%;border-radius:12px;border:1px solid #E5E7EB;padding:12px 14px;font-size:13px;color:#111827;resize:none" />
                      <p style="margin-top:6px;font-size:12px;color:#6B7280">Configure the base onboarding flow for a specific external user type.</p>
                    </label>
                  </div>
                </Show>

                <Show when={builderTab() === 'steps'}>
                  <div style="display:grid;grid-template-columns:1fr 380px;gap:16px;align-items:start">
                    <div style="border:1px solid #E5E7EB;border-radius:14px;overflow:hidden">
                      <div style="display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid #E5E7EB;background:#F9FAFB">
                        <p style="font-size:13px;font-weight:800;color:#111827">Step Builder</p>
                        <button type="button" onClick={addStep} style="height:32px;border-radius:10px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:800;color:white;border:none;cursor:pointer">Add Step</button>
                      </div>
                      <div style="padding:10px;display:flex;flex-direction:column;gap:10px">
                        <Show when={flowSteps().length > 0} fallback={<div style="padding:28px;text-align:center;color:#6B7280">No steps added yet.</div>}>
                          <For each={flowSteps()}>
                            {(s, idx) => {
                              const isSelected = () => selectedStepId() === s.id;
                              return (
                                <div
                                  role="button"
                                  tabIndex={0}
                                  onClick={() => setSelectedStepId(s.id)}
                                  onKeyDown={(e) => {
                                    if (e.key === 'Enter' || e.key === ' ') {
                                      e.preventDefault();
                                      setSelectedStepId(s.id);
                                    }
                                  }}
                                  style={`text-align:left;display:flex;align-items:flex-start;gap:12px;padding:12px;border:1px solid ${isSelected() ? '#FFD8C2' : '#E5E7EB'};border-radius:12px;background:${isSelected() ? '#FFF1EB' : 'white'};cursor:pointer`}
                                >
                                  <div style="display:flex;flex-direction:column;align-items:center;gap:8px">
                                    <div style="width:26px;height:26px;border-radius:50%;background:#0D0D2A;color:white;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800">{idx() + 1}</div>
                                    <div style="display:flex;flex-direction:column;gap:4px">
                                      <button type="button" onClick={(e) => { e.stopPropagation(); moveStep(s.id, -1); }} style="height:20px;width:20px;display:flex;align-items:center;justify-content:center;background:white;border:1px solid #E5E7EB;border-radius:6px;cursor:pointer;color:#6B7280">
                                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path d="m18 15-6-6-6 6"/></svg>
                                      </button>
                                      <button type="button" onClick={(e) => { e.stopPropagation(); moveStep(s.id, 1); }} style="height:20px;width:20px;display:flex;align-items:center;justify-content:center;background:white;border:1px solid #E5E7EB;border-radius:6px;cursor:pointer;color:#6B7280">
                                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path d="m6 9 6 6 6-6"/></svg>
                                      </button>
                                    </div>
                                  </div>
                                  <div style="flex:1">
                                    <p style="font-size:14px;font-weight:800;color:#111827">{s.name}</p>
                                    <p style="margin-top:2px;font-size:12px;color:#6B7280">{s.description}</p>
                                    <div style="margin-top:10px;display:flex;align-items:center;gap:10px">
                                      <span style="font-size:12px;font-weight:700;color:#6B7280">{s.fields.length} fields</span>
                                      <button type="button" onClick={(e) => { e.stopPropagation(); deleteStep(s.id); }} style="margin-left:auto;height:28px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:12px;font-weight:900;color:#DC2626;cursor:pointer">Delete</button>
                                    </div>
                                  </div>
                                </div>
                              );
                            }}
                          </For>
                        </Show>
                      </div>
                    </div>

                    <div style="border:1px solid #E5E7EB;border-radius:14px;overflow:hidden">
                      <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;background:#F9FAFB">
                        <p style="font-size:13px;font-weight:800;color:#111827">Selected Step</p>
                        <p style="margin-top:4px;font-size:12px;color:#6B7280">Edit step name/description and required state.</p>
                      </div>
                      <div style="padding:16px">
                        <Show when={selectedStep()} fallback={<p style="font-size:13px;color:#6B7280">Select a step to edit.</p>}>
                          <div style="display:flex;flex-direction:column;gap:12px">
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:800;color:#374151">Step Name</span>
                              <input value={editingStepName()} onInput={(e) => setEditingStepName(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                            </label>
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:800;color:#374151">Step Description</span>
                              <textarea value={editingStepDescription()} onInput={(e) => setEditingStepDescription(e.currentTarget.value)} rows={3} style="display:block;margin-top:6px;width:100%;border-radius:12px;border:1px solid #E5E7EB;padding:10px 12px;font-size:13px;color:#111827;resize:none" />
                            </label>
                            <label style="display:flex;align-items:center;gap:10px">
                              <input type="checkbox" checked={editingStepRequired()} onChange={(e) => setEditingStepRequired(e.currentTarget.checked)} style="width:16px;height:16px;accent-color:#FF5E13" />
                              <span style="font-size:13px;font-weight:800;color:#374151">Required step</span>
                            </label>
                            <button type="button" onClick={saveStepEdits} style="height:36px;border-radius:10px;background:#0D0D2A;padding:0 14px;font-size:13px;font-weight:900;color:white;border:none;cursor:pointer">Save Step</button>
                            <button type="button" onClick={() => setBuilderTab('fields')} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:900;color:#374151;cursor:pointer">Manage Fields</button>
                          </div>
                        </Show>
                      </div>
                    </div>
                  </div>
                </Show>

                <Show when={builderTab() === 'fields'}>
                  <div style="display:grid;grid-template-columns:1fr 360px;gap:16px;align-items:start">
                    <div style="border:1px solid #E5E7EB;border-radius:14px;overflow:hidden">
                      <div style="display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid #E5E7EB;background:#F9FAFB">
                        <div>
                          <p style="font-size:13px;font-weight:900;color:#111827">Field Rules</p>
                          <p style="margin-top:2px;font-size:12px;color:#6B7280">Select a step and configure its fields.</p>
                        </div>
                        <button type="button" onClick={openCreateField} disabled={!selectedStep()} style={`height:32px;border-radius:10px;background:${selectedStep() ? '#0D0D2A' : '#E5E7EB'};padding:0 12px;font-size:12px;font-weight:900;color:${selectedStep() ? 'white' : '#9CA3AF'};border:none;cursor:${selectedStep() ? 'pointer' : 'not-allowed'}`}>
                          Add Field
                        </button>
                      </div>

                      <div style="padding:14px">
                        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
                          <span style="font-size:12px;font-weight:900;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em">Step</span>
                          <select value={selectedStepId() || ''} onChange={(e) => setSelectedStepId(e.currentTarget.value || null)} style="height:34px;min-width:260px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:13px;color:#111827">
                            <option value="">Select step…</option>
                            <For each={flowSteps()}>{s => <option value={s.id}>{s.name}</option>}</For>
                          </select>
                        </div>

                        <div style="margin-top:14px;border:1px solid #E5E7EB;border-radius:12px;overflow:hidden;background:white">
                          <table style="width:100%;border-collapse:collapse">
                            <thead style="background:#F9FAFB">
                              <tr style="text-align:left">
                                {['Field Label', 'Field Key', 'Type', 'Required', 'Condition', 'Actions'].map(h => (
                                  <th style="padding:12px 14px;font-size:11px;font-weight:900;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em;white-space:nowrap">{h}</th>
                                ))}
                              </tr>
                            </thead>
                            <tbody>
                              <Show when={selectedStep() && selectedStep()!.fields.length > 0} fallback={<tr><td colSpan={6} style="padding:20px 14px;font-size:13px;color:#6B7280">No fields configured for this step.</td></tr>}>
                                <For each={selectedStep()!.fields}>
                                  {f => (
                                    <tr style="border-top:1px solid #E5E7EB">
                                      <td style="padding:12px 14px;font-size:13px;font-weight:900;color:#111827">{f.label}</td>
                                      <td style="padding:12px 14px;font-size:12px;font-family:monospace;color:#6B7280">{f.key}</td>
                                      <td style="padding:12px 14px;font-size:13px;color:#6B7280">{f.type}</td>
                                      <td style="padding:12px 14px;font-size:13px;color:#6B7280">{f.required ? 'Yes' : 'No'}</td>
                                      <td style="padding:12px 14px;font-size:12px;color:#6B7280">{f.condition ? `${f.condition.fieldKey} = ${f.condition.equals}` : '—'}</td>
                                      <td style="padding:12px 14px">
                                        <div style="display:flex;gap:8px">
                                          <button type="button" onClick={() => openEditField(f)} style="height:30px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:12px;font-weight:900;color:#374151;cursor:pointer">Edit</button>
                                          <button type="button" onClick={() => deleteField(f.id)} style="height:30px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:12px;font-weight:900;color:#DC2626;cursor:pointer">Delete</button>
                                        </div>
                                      </td>
                                    </tr>
                                  )}
                                </For>
                              </Show>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>

                    <div style="border:1px solid #E5E7EB;border-radius:14px;overflow:hidden">
                      <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;background:#F9FAFB">
                        <p style="font-size:13px;font-weight:900;color:#111827">Field Editor</p>
                        <p style="margin-top:2px;font-size:12px;color:#6B7280">Add or edit a field for the selected step.</p>
                      </div>
                      <div style="padding:16px">
                        <Show when={fieldEditorOpen()} fallback={<p style="font-size:13px;color:#6B7280">Click “Add Field” or “Edit” to open the editor.</p>}>
                          <div style="display:flex;flex-direction:column;gap:12px">
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:900;color:#374151">Field Label *</span>
                              <input value={fieldLabel()} onInput={(e) => setFieldLabel(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                            </label>
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:900;color:#374151">Field Key *</span>
                              <input value={fieldKey()} onInput={(e) => setFieldKey(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827;font-family:monospace" />
                            </label>
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:900;color:#374151">Input Type *</span>
                              <select value={fieldType()} onChange={(e) => setFieldType(e.currentTarget.value as any)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;background:white;color:#111827">
                                {(['text', 'email', 'phone', 'number', 'textarea', 'select', 'multi-select', 'pincode', 'file'] as const).map(t => <option value={t}>{t}</option>)}
                              </select>
                            </label>
                            <label style="display:flex;align-items:center;gap:10px">
                              <input type="checkbox" checked={fieldRequired()} onChange={(e) => setFieldRequired(e.currentTarget.checked)} style="width:16px;height:16px;accent-color:#FF5E13" />
                              <span style="font-size:13px;font-weight:900;color:#374151">Required</span>
                            </label>
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:900;color:#374151">Placeholder</span>
                              <input value={fieldPlaceholder()} onInput={(e) => setFieldPlaceholder(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                            </label>
                            <label style="display:block">
                              <span style="font-size:13px;font-weight:900;color:#374151">Help Text</span>
                              <input value={fieldHelp()} onInput={(e) => setFieldHelp(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                            </label>

                            <Show when={fieldType() === 'select' || fieldType() === 'multi-select'}>
                              <label style="display:block">
                                <span style="font-size:13px;font-weight:900;color:#374151">Options (one per line)</span>
                                <textarea value={fieldOptionsText()} onInput={(e) => setFieldOptionsText(e.currentTarget.value)} rows={4} style="display:block;margin-top:6px;width:100%;border-radius:12px;border:1px solid #E5E7EB;padding:10px 12px;font-size:13px;color:#111827;resize:none" />
                              </label>
                            </Show>

                            <Show when={fieldType() === 'file'}>
                              <label style="display:block">
                                <span style="font-size:13px;font-weight:900;color:#374151">Allowed File Types</span>
                                <input value={fieldAllowedTypesText()} onInput={(e) => setFieldAllowedTypesText(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                              </label>
                            </Show>

                            <div style="border-top:1px solid #E5E7EB;padding-top:12px">
                              <p style="font-size:12px;font-weight:900;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em">Conditional Visibility</p>
                              <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px">
                                <label style="display:block">
                                  <span style="font-size:13px;font-weight:900;color:#374151">Field Key</span>
                                  <input value={fieldConditionKey()} onInput={(e) => setFieldConditionKey(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827;font-family:monospace" />
                                </label>
                                <label style="display:block">
                                  <span style="font-size:13px;font-weight:900;color:#374151">Equals</span>
                                  <input value={fieldConditionEquals()} onInput={(e) => setFieldConditionEquals(e.currentTarget.value)} style="display:block;margin-top:6px;height:38px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 12px;font-size:13px;color:#111827" />
                                </label>
                              </div>
                            </div>

                            <div style="display:flex;gap:10px">
                              <button type="button" onClick={() => setFieldEditorOpen(false)} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:900;color:#374151;cursor:pointer">Close</button>
                              <button type="button" onClick={saveField} style="height:36px;border-radius:10px;background:#0D0D2A;padding:0 14px;font-size:13px;font-weight:900;color:white;border:none;cursor:pointer">Save Field</button>
                            </div>
                          </div>
                        </Show>
                      </div>
                    </div>
                  </div>
                </Show>

                <Show when={builderTab() === 'verification'}>
                  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:800;color:#374151">Verification Type *</span>
                      <select value={flowVerificationType()} onChange={(e) => setFlowVerificationType(e.currentTarget.value as any)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827">
                        <option value="IDENTITY">Identity Verification</option>
                        <option value="BUSINESS">Business Verification</option>
                        <option value="MIXED">Mixed Verification</option>
                        <option value="NONE">No Verification</option>
                      </select>
                    </label>
                    <div style="border:1px solid #E5E7EB;border-radius:12px;padding:14px;background:white">
                      <p style="font-size:13px;font-weight:900;color:#111827">Required Documents</p>
                      <p style="margin-top:4px;font-size:12px;color:#6B7280">Supports upload simulation and review workflows.</p>
                      <div style="margin-top:10px;display:flex;flex-wrap:wrap;gap:8px">
                        <For each={['Aadhaar Card', 'PAN Card', 'Passport', 'Resume', 'Portfolio Sample', 'GST Certificate', 'Company PAN', 'Incorporation Certificate']}>
                          {doc => {
                            const selected = () => flowRequiredDocuments().includes(doc);
                            return (
                              <button type="button" onClick={() => setFlowRequiredDocuments(list => selected() ? list.filter(d => d !== doc) : [...list, doc])} style={`height:30px;border-radius:9999px;border:1px solid #E5E7EB;background:${selected() ? '#FFF1EB' : 'white'};padding:0 12px;font-size:12px;font-weight:900;color:${selected() ? '#FF5E13' : '#374151'};cursor:pointer`}>
                                {doc}
                              </button>
                            );
                          }}
                        </For>
                      </div>
                    </div>
                  </div>
                </Show>

                <Show when={builderTab() === 'success'}>
                  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:900;color:#374151">Success Title</span>
                      <input value={successTitle()} onInput={(e) => setSuccessTitle(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827" />
                    </label>
                    <label style="display:block">
                      <span style="font-size:13px;font-weight:900;color:#374151">Success Message</span>
                      <input value={successMessage()} onInput={(e) => setSuccessMessage(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827" />
                    </label>
                  </div>
                </Show>

                <Show when={builderTab() === 'preview'}>
                  <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
                    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
                      <select value={previewDevice()} onChange={(e) => setPreviewDevice(e.currentTarget.value as any)} style="height:34px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:13px;color:#111827">
                        <option value="desktop">Desktop</option>
                        <option value="mobile">Mobile</option>
                      </select>
                      <select value={previewScenario()} onChange={(e) => { setPreviewScenario(e.currentTarget.value as any); setPreviewMode('stepper'); setPreviewSubmitted(false); }} style="height:34px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 10px;font-size:13px;color:#111827">
                        <option value="empty">Empty State</option>
                        <option value="sample">Sample Data</option>
                        <option value="errors">Validation Errors</option>
                        <option value="success">Success Screen</option>
                        <option value="pending">Pending Approval</option>
                        <option value="rejected">Rejected</option>
                        <option value="document_requested">Document Requested</option>
                      </select>
                      <button type="button" onClick={() => { setPreviewData({}); setPreviewStepIndex(0); setPreviewMode('stepper'); setPreviewSubmitted(false); }} style="height:34px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:900;color:#374151;cursor:pointer">Reset Preview</button>
                      <button type="button" onClick={() => setPageTab('preview')} style="height:34px;border-radius:10px;background:#0D0D2A;padding:0 14px;font-size:12px;font-weight:900;color:white;border:none;cursor:pointer">Open Full Preview</button>
                    </div>
                  </div>
                </Show>
              </div>
            </div>
          </Match>

          <Match when={pageTab() === 'preview'}>
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
              <div>
                <h2 style="font-size:18px;font-weight:800;color:#111827">Preview (Real User UI)</h2>
                <p style="margin-top:4px;font-size:13px;color:#6B7280">Step-by-step flow simulation with validation, uploads, and result states.</p>
              </div>
              <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
                <select value={viewingSchema()?.id || ''} onChange={(e) => { const s = rows().find(x => x.id === e.currentTarget.value); if (s) openPreview(s); }} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;min-width:260px">
                  <option value="">Select flow…</option>
                  <For each={rows()}>{r => <option value={r.id}>{r.name} ({r.version})</option>}</For>
                </select>
                <select value={previewDevice()} onChange={(e) => setPreviewDevice(e.currentTarget.value as any)} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827">
                  <option value="desktop">Desktop</option>
                  <option value="mobile">Mobile</option>
                </select>
                <select value={previewScenario()} onChange={(e) => { setPreviewScenario(e.currentTarget.value as any); setPreviewMode('stepper'); setPreviewSubmitted(false); }} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827">
                  <option value="empty">Empty</option>
                  <option value="sample">Sample</option>
                  <option value="errors">Errors</option>
                  <option value="success">Success</option>
                  <option value="pending">Pending</option>
                  <option value="rejected">Rejected</option>
                  <option value="document_requested">Doc Requested</option>
                </select>
              </div>
            </div>

            <div style="margin-top:16px;border:1px solid #E5E7EB;border-radius:16px;background:#F9FAFB;overflow:hidden">
              <div style="padding:16px;border-bottom:1px solid #E5E7EB;background:white;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
                <div>
                  <p style="font-size:15px;font-weight:900;color:#111827">{flowName() || viewingSchema()?.name || 'Select a flow'}</p>
                  <p style="margin-top:2px;font-size:12px;color:#6B7280">{flowUserType()} {flowRole() ? `(${flowRole()})` : ''} • Version {flowVersion()}</p>
                </div>
                <div style="width:220px">
                  <div style="display:flex;align-items:center;justify-content:space-between">
                    <span style="font-size:12px;color:#6B7280;font-weight:800">Progress</span>
                    <span style="font-size:12px;color:#6B7280;font-weight:800">{previewProgress()}%</span>
                  </div>
                  <div style="margin-top:6px;height:8px;border-radius:9999px;background:#E5E7EB;overflow:hidden">
                    <div style={`height:100%;width:${previewProgress()}%;background:#FF5E13;border-radius:9999px`} />
                  </div>
                </div>
              </div>

              <div style={`padding:20px;max-width:${previewDevice() === 'mobile' ? '420px' : '960px'};margin:0 auto`}>
                <Show when={flowSteps().length > 0} fallback={<div style="padding:40px;text-align:center;color:#6B7280">Select a flow to preview.</div>}>
                  <Show when={previewMode() === 'result'} fallback={
                    <Show when={previewMode() === 'review'} fallback={
                      <div style="border:1px solid #E5E7EB;border-radius:16px;background:white;padding:18px">
                        <p style="font-size:12px;font-weight:900;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em">Step {previewStepIndex() + 1} of {previewSteps().length}</p>
                        <p style="margin-top:6px;font-size:18px;font-weight:900;color:#111827">{previewCurrentStep()!.name}</p>
                        <p style="margin-top:6px;font-size:13px;color:#6B7280">{previewCurrentStep()!.description}</p>

                        <div style="margin-top:16px;display:flex;flex-direction:column;gap:14px">
                          <For each={previewCurrentStep()!.fields}>
                            {f => (
                              <Show when={fieldVisibleInPreview(f)}>
                                <div>
                                  <div style="display:flex;align-items:center;justify-content:space-between">
                                    <label style="font-size:13px;font-weight:800;color:#374151">{f.label}{f.required ? ' *' : ''}</label>
                                    <Show when={previewErrors().has(f.key)}><span style="font-size:12px;font-weight:800;color:#DC2626">Required</span></Show>
                                  </div>
                                  <Show when={f.type === 'textarea'} fallback={
                                    <Show when={f.type === 'select'} fallback={
                                      <Show when={f.type === 'file'} fallback={
                                        <input value={previewScenario() === 'empty' ? '' : (previewData()[f.key] || '')} onInput={(e) => setPreviewData(d => ({ ...d, [f.key]: e.currentTarget.value }))} placeholder={f.placeholder} style={`margin-top:6px;height:40px;width:100%;border-radius:12px;border:1px solid ${previewErrors().has(f.key) ? '#FECACA' : '#E5E7EB'};padding:0 12px;font-size:13px;color:#111827;outline:none`} />
                                      }>
                                        <div style={`margin-top:6px;border:2px dashed ${previewErrors().has(f.key) ? '#FECACA' : '#E5E7EB'};border-radius:12px;padding:14px;background:white;display:flex;align-items:center;justify-content:space-between;gap:10px`}>
                                          <div>
                                            <p style="font-size:13px;font-weight:900;color:#111827">Upload {f.label}</p>
                                            <p style="margin-top:2px;font-size:12px;color:#6B7280">Allowed: {(f.allowedFileTypes || ['PDF', 'JPG', 'JPEG', 'PNG']).join(', ')}</p>
                                          </div>
                                          <button type="button" onClick={() => setPreviewData(d => ({ ...d, [f.key]: 'uploaded' }))} style="height:32px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:900;color:#374151;cursor:pointer">
                                            {previewData()[f.key] ? 'Replace' : 'Choose File'}
                                          </button>
                                        </div>
                                      </Show>
                                    }>
                                      <select value={previewScenario() === 'empty' ? '' : (previewData()[f.key] || '')} onChange={(e) => setPreviewData(d => ({ ...d, [f.key]: e.currentTarget.value }))} style={`margin-top:6px;height:40px;width:100%;border-radius:12px;border:1px solid ${previewErrors().has(f.key) ? '#FECACA' : '#E5E7EB'};padding:0 12px;font-size:13px;color:#111827;background:white;outline:none`}>
                                        <option value="">Select…</option>
                                        <For each={f.options || []}>{opt => <option value={opt}>{opt}</option>}</For>
                                      </select>
                                    </Show>
                                  }>
                                    <textarea value={previewScenario() === 'empty' ? '' : (previewData()[f.key] || '')} onInput={(e) => setPreviewData(d => ({ ...d, [f.key]: e.currentTarget.value }))} placeholder={f.placeholder} rows={3} style={`margin-top:6px;width:100%;border-radius:12px;border:1px solid ${previewErrors().has(f.key) ? '#FECACA' : '#E5E7EB'};padding:10px 12px;font-size:13px;color:#111827;resize:none;outline:none`} />
                                  </Show>
                                  <Show when={f.help}><p style="margin-top:6px;font-size:12px;color:#6B7280">{f.help}</p></Show>
                                </div>
                              </Show>
                            )}
                          </For>
                        </div>

                        <div style="margin-top:18px;display:flex;align-items:center;justify-content:space-between;gap:12px">
                          <button type="button" onClick={goPrevPreview} disabled={previewStepIndex() === 0} style={`height:36px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:900;color:${previewStepIndex() === 0 ? '#9CA3AF' : '#374151'};cursor:${previewStepIndex() === 0 ? 'not-allowed' : 'pointer'}`}>Back</button>
                          <button type="button" onClick={goNextPreview} style="height:36px;border-radius:12px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:900;color:white;border:none;cursor:pointer">Next</button>
                        </div>
                      </div>
                    }>
                      <div style="border:1px solid #E5E7EB;border-radius:16px;background:white;padding:18px">
                        <p style="font-size:18px;font-weight:900;color:#111827">Review</p>
                        <p style="margin-top:6px;font-size:13px;color:#6B7280">Review your details before submitting.</p>
                        <div style="margin-top:14px;border:1px solid #E5E7EB;border-radius:12px;padding:14px;background:#F9FAFB">
                          <div style="display:flex;flex-direction:column;gap:10px">
                            <For each={Object.entries(previewData())}>
                              {([k, v]) => (
                                <div style="display:flex;justify-content:space-between;gap:12px">
                                  <span style="font-size:12px;color:#6B7280">{k}</span>
                                  <span style="font-size:12px;font-weight:800;color:#111827">{v || '—'}</span>
                                </div>
                              )}
                            </For>
                          </div>
                        </div>
                        <div style="margin-top:18px;display:flex;align-items:center;justify-content:space-between;gap:12px">
                          <button type="button" onClick={goPrevPreview} style="height:36px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;font-weight:900;color:#374151;cursor:pointer">Back</button>
                          <button type="button" onClick={goNextPreview} style="height:36px;border-radius:12px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:900;color:white;border:none;cursor:pointer">Submit</button>
                        </div>
                      </div>
                    </Show>
                  }>
                    <div style="border:1px solid #E5E7EB;border-radius:16px;background:white;padding:22px;text-align:center">
                      <p style="font-size:20px;font-weight:900;color:#111827">{previewResult()!.title}</p>
                      <p style="margin-top:8px;font-size:13px;color:#6B7280">{previewResult()!.desc}</p>
                      <Show when={previewScenario() === 'document_requested'}>
                        <div style="margin-top:14px;display:flex;flex-direction:column;gap:10px;align-items:center">
                          <p style="font-size:12px;color:#6B7280">Requested Documents</p>
                          <div style="display:flex;flex-wrap:wrap;gap:8px;justify-content:center">
                            <For each={flowRequiredDocuments()}>{d => <span style="display:inline-flex;align-items:center;border-radius:9999px;border:1px solid #E5E7EB;background:#F9FAFB;color:#374151;padding:2px 10px;font-size:12px;font-weight:700">{d}</span>}</For>
                          </div>
                        </div>
                      </Show>
                      <button type="button" onClick={() => { setPreviewMode('stepper'); setPreviewSubmitted(false); }} style="margin-top:18px;height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:12px;font-weight:900;color:#374151;cursor:pointer">Back to Preview</button>
                    </div>
                  </Show>
                </Show>
              </div>
            </div>
          </Match>

          <Match when={pageTab() === 'submissions'}>
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
              <div>
                <h2 style="font-size:18px;font-weight:800;color:#111827">Onboarding Submissions</h2>
                <p style="margin-top:4px;font-size:13px;color:#6B7280">Review onboarding submissions and their current states.</p>
              </div>
            </div>

            <div style="margin-top:16px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06);overflow:hidden">
              <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;flex-wrap:wrap">
                <input value={subSearch()} onInput={(e) => setSubSearch(e.currentTarget.value)} placeholder="Search submissions..." style="height:34px;flex:1;min-width:220px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none" />
                <div style="position:relative">
                  <button type="button" onClick={() => { setSubSortMenuOpen(v => !v); setSubFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:800;color:#374151;cursor:pointer">Sort</button>
                  <Show when={subSortMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:200px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      {(['updated_desc', 'updated_asc', 'name_asc', 'name_desc'] as const).map((s, i) => (
                        <button type="button" onClick={() => { setSubSortBy(s); setSubSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${subSortBy() === s ? '#FF5E13' : '#374151'};background:${subSortBy() === s ? '#FFF1EB' : 'transparent'}`}>
                          {['Updated (Newest)', 'Updated (Oldest)', 'User (A-Z)', 'User (Z-A)'][i]}
                        </button>
                      ))}
                    </div>
                  </Show>
                </div>
                <div style="position:relative">
                  <button type="button" onClick={() => { setSubFilterMenuOpen(v => !v); setSubSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:800;color:#374151;cursor:pointer">Status</button>
                  <Show when={subFilterMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      {(['all', 'IN_PROGRESS', 'SUBMITTED', 'PENDING_APPROVAL', 'APPROVED', 'REJECTED', 'DOCUMENT_REQUESTED'] as const).map((s) => (
                        <button type="button" onClick={() => { setSubStatusFilter(s as any); setSubFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${subStatusFilter() === (s as any) ? '#FF5E13' : '#374151'};background:${subStatusFilter() === (s as any) ? '#FFF1EB' : 'transparent'}`}>
                          {s === 'all' ? 'All Status' : normalizeLabel(s)}
                        </button>
                      ))}
                    </div>
                  </Show>
                </div>
              </div>

              <div class="overflow-x-auto">
                <table class="min-w-full">
                  <thead>
                    <tr style="background:#0D0D2A;text-align:left">
                      {['Submission ID', 'User', 'Role', 'Status', 'Created', 'Updated'].map(h => (
                        <th style="padding:10px 20px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    <For each={submissionsFiltered()}>
                      {s => (
                        <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                          <td style="padding:12px 20px;font-size:12px;font-family:monospace;color:#6B7280">{s.id}</td>
                          <td style="padding:12px 20px;font-size:13px;font-weight:800;color:#111827">{s.userName} <span style="font-weight:600;color:#6B7280">({s.userId})</span></td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{normalizeLabel(s.roleKey)}</td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{normalizeLabel(s.status)}</td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{s.createdAt}</td>
                          <td style="padding:12px 20px;font-size:13px;color:#6B7280">{s.updatedAt}</td>
                        </tr>
                      )}
                    </For>
                  </tbody>
                </table>
              </div>
            </div>
          </Match>

          <Match when={pageTab() === 'audit'}>
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
              <div>
                <h2 style="font-size:18px;font-weight:800;color:#111827">Audit Logs</h2>
                <p style="margin-top:4px;font-size:13px;color:#6B7280">Track onboarding schema events such as create, update, publish, and preview.</p>
              </div>
              <input value={auditSearch()} onInput={(e) => setAuditSearch(e.currentTarget.value)} placeholder="Search audit logs..." style="height:36px;min-width:240px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none" />
            </div>

            <div style="margin-top:16px;display:flex;flex-direction:column;gap:10px">
              <For each={auditFiltered()}>
                {e => (
                  <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;border:1px solid #E5E7EB;border-radius:14px;background:white;padding:14px">
                    <div>
                      <p style="font-size:13px;font-weight:900;color:#111827">{normalizeLabel(e.event)} <span style="font-weight:700;color:#6B7280">by {e.actor}</span></p>
                      <p style="margin-top:4px;font-size:12px;color:#6B7280">Target: <span style="font-family:monospace">{e.target}</span></p>
                    </div>
                    <div style="font-size:12px;font-weight:800;color:#6B7280;white-space:nowrap">{e.createdAt}</div>
                  </div>
                )}
              </For>
            </div>
          </Match>
        </Switch>
      </div>
  );
}
