import { createMemo, createSignal, For, Show } from 'solid-js';

export type OnboardingFieldType = 'text' | 'textarea' | 'number' | 'email' | 'tel' | 'date' | 'select' | 'url' | 'file' | 'checkbox';

export type OnboardingField = {
  id: string;
  label: string;
  type: OnboardingFieldType;
  required: boolean;
  placeholder?: string;
  options?: { label: string; value: string }[];
};

export type OnboardingStep = {
  id: string;
  title: string;
  description?: string;
  fields: OnboardingField[];
};

type QuestionCategory = 'business' | 'documents' | 'experience' | 'contact' | 'profile';

type OnboardingQuestion = {
  key: string;
  label: string;
  type: OnboardingFieldType;
  required: boolean;
  category: QuestionCategory;
  options?: { label: string; value: string }[];
};

type Props = {
  title: string;
  roleKey: string;
  description: string;
  finalSubmissionMessage: string;
  stepCount: number;
  selectedFields: OnboardingField[];
  saving?: boolean;
  error?: string;
  livePreviewUrl?: string;
  livePreviewHint?: string;
  roleOptions?: { value: string; label: string }[];
  primaryLabel: string;
  onChange: (next: {
    title?: string;
    roleKey?: string;
    description?: string;
    finalSubmissionMessage?: string;
    stepCount?: number;
    selectedFields?: OnboardingField[];
  }) => void;
  onSubmit: () => void;
};

const ROLE_OPTIONS = [
  'company',
  'job_seeker',
  'jobseeker',
  'customer',
  'service_seeker',
  'professional',
  'photographer',
  'video_editor',
  'graphic_designer',
  'social_media_manager',
  'fitness_trainer',
  'catering_services',
  'makeup_artist',
  'tutor',
  'developer',
  'ugc_content_creator',
];

function fallbackRoleOptions(): { value: string; label: string }[] {
  return ROLE_OPTIONS.map((option) => ({
    value: option,
    label: option.replace(/_/g, ' '),
  }));
}

const DEFAULT_LIBRARY: OnboardingQuestion[] = [
  { key: 'full_name', label: 'Full Name', type: 'text', required: true, category: 'profile' },
  { key: 'email', label: 'Email', type: 'email', required: true, category: 'contact' },
  { key: 'phone', label: 'Phone', type: 'tel', required: true, category: 'contact' },
  { key: 'city', label: 'City', type: 'text', required: true, category: 'contact' },
  { key: 'experience_years', label: 'Experience (Years)', type: 'number', required: false, category: 'experience' },
  { key: 'portfolio_url', label: 'Portfolio URL', type: 'url', required: false, category: 'experience' },
  { key: 'gst_number', label: 'GST Number', type: 'text', required: false, category: 'business' },
  { key: 'pan_number', label: 'PAN Number', type: 'text', required: false, category: 'business' },
  { key: 'identity_document', label: 'Identity Document', type: 'file', required: true, category: 'documents' },
  { key: 'address_proof', label: 'Address Proof', type: 'file', required: true, category: 'documents' },
];

const FIELD_TYPES: OnboardingFieldType[] = ['text', 'textarea', 'number', 'select', 'file', 'email', 'tel', 'date', 'url', 'checkbox'];

function makeId(prefix: string): string {
  return `${prefix}_${Math.random().toString(36).slice(2, 10)}`;
}

function toSlug(input: string): string {
  return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
}

function createFieldFromQuestion(question: OnboardingQuestion): OnboardingField {
  return {
    id: question.key || makeId('fld'),
    label: question.label,
    type: question.type,
    required: question.required,
    placeholder: question.type === 'file' ? 'Upload file' : `Enter ${question.label}`,
    options: question.options,
  };
}

function createField(
  id: string,
  label: string,
  type: OnboardingFieldType,
  required: boolean,
  options?: string[],
  placeholder?: string,
): OnboardingField {
  return {
    id,
    label,
    type,
    required,
    placeholder: placeholder || (type === 'file' ? 'Upload file' : type === 'select' ? `Select ${label}` : `Enter ${label}`),
    options: Array.isArray(options) ? options.map((value) => ({ label: value, value })) : undefined,
  };
}

function normalizeRoleKey(roleKey: string): string {
  return String(roleKey || '')
    .trim()
    .toLowerCase()
    .replace(/[-\s]+/g, '_');
}

function categoryLabel(category: QuestionCategory): string {
  if (category === 'business') return 'Business';
  if (category === 'documents') return 'Documents';
  if (category === 'experience') return 'Experience';
  if (category === 'contact') return 'Contact';
  return 'Profile';
}

export function inferStepCount(steps: OnboardingStep[]): number {
  return Math.max(1, steps.length || 1);
}

export function buildStepsFromFields(selectedFields: OnboardingField[], stepCount: number): OnboardingStep[] {
  const safeStepCount = Math.max(1, stepCount || 1);
  const buckets: OnboardingField[][] = Array.from({ length: safeStepCount }, () => []);
  selectedFields.forEach((field, index) => {
    buckets[index % safeStepCount].push(field);
  });
  return buckets.map((fields, index) => ({
    id: `step_${index + 1}`,
    title: `Step ${index + 1}`,
    description: '',
    fields,
  }));
}

export function createDefaultFields(roleKey: string): OnboardingField[] {
  const role = normalizeRoleKey(roleKey);

  const company = [
    createField('company_name', 'Company name', 'text', true),
    createField('legal_name', 'Legal entity name', 'text', true),
    createField('industry', 'Industry', 'text', true),
    createField('contact_name', 'Contact person', 'text', true),
    createField('contact_email', 'Contact email', 'email', true),
    createField('contact_phone', 'Contact phone', 'tel', true),
    createField('website', 'Website', 'url', false),
    createField('hq_city', 'Headquarter city', 'text', true),
    createField('team_size', 'Team size', 'select', true, ['1-10', '11-50', '51-200', '200+']),
    createField('hiring_for', 'Primary hiring for', 'text', true),
    createField('work_mode', 'Preferred work mode', 'select', true, ['onsite', 'remote', 'hybrid']),
    createField('monthly_openings', 'Expected monthly openings', 'number', false),
    createField('registration_number', 'Company registration number', 'text', true),
    createField('official_email', 'Official company email', 'email', true),
    createField('authorized_signatory', 'Authorized signatory', 'text', true),
  ];

  const jobseeker = [
    createField('full_name', 'Full name', 'text', true),
    createField('city', 'City', 'text', true),
    createField('skills', 'Skills', 'textarea', true),
    createField('preferred_role', 'Preferred role', 'text', true),
    createField('expected_salary', 'Expected salary', 'text', false),
    createField('experience_years', 'Years of experience', 'number', true),
    createField('latest_company', 'Latest company', 'text', false),
    createField('notice_period', 'Notice period', 'text', false),
    createField('resume_url', 'Resume URL', 'url', true),
    createField('linkedin_url', 'LinkedIn URL', 'url', false),
    createField('about_me', 'About me', 'textarea', false),
  ];

  const professionalBase = [
    createField(
      'profession',
      'Professional role',
      'select',
      true,
      ['photographer', 'makeup_artist', 'tutor', 'developer', 'video_editor', 'ugc_content_creator', 'graphic_designer', 'social_media_manager', 'fitness_trainer', 'catering_services'],
    ),
    createField('full_name', 'Full name', 'text', true),
    createField('experience', 'Experience', 'text', true),
    createField('bio', 'Bio', 'textarea', true),
    createField('email', 'Email', 'email', true),
    createField('phone', 'Phone', 'tel', true),
    createField('city', 'City', 'text', true),
    createField('primary_service', 'Primary service', 'text', true),
    createField('price_range', 'Price range', 'text', true),
    createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
    createField('portfolio_url', 'Portfolio URL', 'url', false),
    createField('portfolio_note', 'Portfolio note', 'textarea', false),
    createField('identity_document', 'Identity Document', 'file', true),
  ];

  const customer = [
    createField(
      'profession',
      'Service category',
      'select',
      true,
      ['photographer', 'makeup_artist', 'tutor', 'developer', 'video_editor', 'ugc_content_creator', 'graphic_designer', 'social_media_manager', 'fitness_trainer', 'catering_services'],
    ),
    createField('event_type', 'Event type', 'text', false),
    createField('coverage_hours', 'Coverage hours', 'number', false),
    createField('photo_style', 'Preferred photo style', 'text', false),
    createField('occasion_type', 'Occasion type', 'text', false),
    createField('people_count', 'Number of people', 'number', false),
    createField('skin_preferences', 'Skin or product preferences', 'textarea', false),
    createField('subject', 'Subject', 'text', false),
    createField('grade_level', 'Grade or level', 'text', false),
    createField('sessions_per_week', 'Sessions per week', 'number', false),
    createField('project_type', 'Project type', 'text', false),
    createField('platform', 'Platform (web/mobile/backend)', 'text', false),
    createField('feature_summary', 'Key features', 'textarea', false),
    createField('video_type', 'Video type', 'text', false),
    createField('video_duration', 'Approx. duration (minutes)', 'number', false),
    createField('editing_style', 'Editing style', 'text', false),
    createField('design_type', 'Design type', 'text', false),
    createField('brand_guidelines', 'Brand guidelines', 'textarea', false),
    createField('asset_count', 'Number of assets', 'number', false),
    createField('platforms', 'Platforms', 'text', false),
    createField('posting_frequency', 'Posting frequency', 'text', false),
    createField('goal', 'Primary goal', 'text', false),
    createField('fitness_goal', 'Fitness goal', 'text', false),
    createField('sessions_per_week_fitness', 'Sessions per week', 'number', false),
    createField('training_mode', 'Training mode preference', 'select', false, ['onsite', 'remote', 'hybrid']),
    createField('event_size', 'Event size (people)', 'number', false),
    createField('menu_preference', 'Menu preference', 'text', false),
    createField('cuisine_type', 'Cuisine type', 'text', false),
    createField('budget_range', 'Budget range', 'text', false),
    createField('expected_start', 'Expected start date', 'date', false),
    createField('urgency', 'Urgency', 'select', false, ['low', 'medium', 'high']),
    createField('service_city', 'Service location', 'text', true),
    createField('service_mode', 'Service mode', 'select', true, ['onsite', 'remote', 'hybrid']),
    createField('address_line', 'Address line', 'text', false),
    createField('pin_code', 'PIN code', 'text', false),
    createField('summary_note', 'Additional notes', 'textarea', false),
  ];

  const specialistOverrides: Record<string, OnboardingField[]> = {
    photographer: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Photography specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    makeup_artist: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Makeup specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    tutor: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Subjects', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    developer: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Tech specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    video_editor: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Editing specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    ugc_content_creator: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('service_area', 'Area / Place', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'UGC specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    graphic_designer: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Design specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    social_media_manager: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Platform specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    fitness_trainer: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Training specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
    catering_services: [
      createField('full_name', 'Full name', 'text', true),
      createField('email', 'Email', 'email', true),
      createField('phone', 'Phone', 'tel', true),
      createField('city', 'City', 'text', true),
      createField('experience_years', 'Experience (Years)', 'number', false),
      createField('specialization', 'Catering specialization', 'text', true),
      createField('portfolio_url', 'Portfolio URL', 'url', false),
      createField('price_range', 'Price range', 'text', true),
      createField('availability', 'Availability', 'select', true, ['weekdays', 'weekends', 'all_days']),
      createField('identity_document', 'Identity Document', 'file', true),
    ],
  };

  if (role === 'company') return company;
  if (role === 'job_seeker' || role === 'jobseeker') return jobseeker;
  if (role === 'customer' || role === 'service_seeker') return customer;
  if (role === 'professional') return professionalBase;
  if (specialistOverrides[role]) return specialistOverrides[role];

  return DEFAULT_LIBRARY
    .filter((q) => ['full_name', 'email', 'phone', 'city', 'identity_document'].includes(q.key))
    .map(createFieldFromQuestion);
}

export default function OnboardingFlowBuilder(props: Props) {
  const [activeTab, setActiveTab] = createSignal<'overview' | 'library' | 'selected' | 'preview' | 'live'>('overview');
  const [customLabel, setCustomLabel] = createSignal('');
  const [customType, setCustomType] = createSignal<OnboardingFieldType>('text');
  const [customRequired, setCustomRequired] = createSignal(true);
  const [customOptions, setCustomOptions] = createSignal('');

  const groupedQuestions = createMemo(() => {
    const groups = new Map<QuestionCategory, OnboardingQuestion[]>();
    DEFAULT_LIBRARY.forEach((question) => {
      if (!groups.has(question.category)) groups.set(question.category, []);
      groups.get(question.category)!.push(question);
    });
    return Array.from(groups.entries());
  });

  const selectedKeySet = createMemo(() => new Set(props.selectedFields.map((field) => field.id)));
  const previewSteps = createMemo(() => buildStepsFromFields(props.selectedFields, props.stepCount));
  const roleOptions = createMemo(() => {
    const incoming = Array.isArray(props.roleOptions) ? props.roleOptions : [];
    return incoming.length > 0 ? incoming : fallbackRoleOptions();
  });

  const toggleQuestion = (question: OnboardingQuestion) => {
    const checked = selectedKeySet().has(question.key);
    if (checked) {
      props.onChange({ selectedFields: props.selectedFields.filter((field) => field.id !== question.key) });
      return;
    }
    props.onChange({ selectedFields: [...props.selectedFields, createFieldFromQuestion(question)] });
  };

  const updateField = (id: string, patch: Partial<OnboardingField>) => {
    props.onChange({
      selectedFields: props.selectedFields.map((field) => (field.id === id ? { ...field, ...patch } : field)),
    });
  };

  const removeField = (id: string) => {
    props.onChange({ selectedFields: props.selectedFields.filter((field) => field.id !== id) });
  };

  const addCustomField = () => {
    const label = customLabel().trim();
    if (!label) return;
    const key = toSlug(label);
    if (!key || selectedKeySet().has(key)) return;
    const field: OnboardingField = {
      id: key,
      label,
      type: customType(),
      required: customRequired(),
      options: customType() === 'select'
        ? customOptions().split(',').map((item) => item.trim()).filter(Boolean).map((value) => ({ label: value, value }))
        : undefined,
      placeholder: customType() === 'file' ? 'Upload file' : `Enter ${label}`,
    };
    props.onChange({ selectedFields: [...props.selectedFields, field] });
    setCustomLabel('');
    setCustomType('text');
    setCustomRequired(true);
    setCustomOptions('');
  };

  return (
    <section class="card">
      <h2 style="margin-bottom:4px">Onboarding Setup</h2>
      <p class="notice" style="margin:0 0 10px">
        Pick who this form is for, choose the steps, select the questions, and set the message users will see after they submit.
      </p>

      <Show when={props.error}>
        <div class="error-box">{props.error}</div>
      </Show>

      <div class="admin-segmented">
        <button class={`admin-segment ${activeTab() === 'overview' ? 'active' : ''}`} onClick={() => setActiveTab('overview')}>Overview</button>
        <button class={`admin-segment ${activeTab() === 'library' ? 'active' : ''}`} onClick={() => setActiveTab('library')}>Question List</button>
        <button class={`admin-segment ${activeTab() === 'selected' ? 'active' : ''}`} onClick={() => setActiveTab('selected')}>Your Questions</button>
        <button class={`admin-segment ${activeTab() === 'preview' ? 'active' : ''}`} onClick={() => setActiveTab('preview')}>Step Preview</button>
        <button class={`admin-segment ${activeTab() === 'live' ? 'active' : ''}`} onClick={() => setActiveTab('live')}>Live Preview</button>
      </div>

      <Show when={activeTab() === 'overview'}>
        <div class="field-grid-2">
          <div class="field">
            <label>Form title</label>
            <input value={props.title} onInput={(event) => props.onChange({ title: event.currentTarget.value })} />
          </div>
          <div class="field">
            <label>Who is this form for?</label>
            <select value={props.roleKey} onChange={(event) => props.onChange({ roleKey: event.currentTarget.value })}>
              <option value="">Select a role</option>
              <For each={roleOptions()}>{(option) => <option value={option.value}>{option.label}</option>}</For>
            </select>
          </div>
          <div class="field">
            <label>Short description (optional)</label>
            <textarea rows="3" value={props.description} onInput={(event) => props.onChange({ description: event.currentTarget.value })} />
          </div>
          <div class="field">
            <label>How many steps should users see?</label>
            <input type="number" min={1} max={8} value={props.stepCount} onInput={(event) => props.onChange({ stepCount: Number(event.currentTarget.value) || 1 })} />
          </div>
          <div class="nested-card" style="display:flex;flex-direction:column;justify-content:center">
            <p style="margin:0;font-size:13px;font-weight:700;color:#0f172a">{props.selectedFields.length} questions selected</p>
            <p class="notice" style="margin:6px 0 0">Choose from the question list or add your own custom question.</p>
          </div>
          <div class="field" style="grid-column:1 / -1">
            <label>Success message after submit</label>
            <textarea rows="3" value={props.finalSubmissionMessage} onInput={(event) => props.onChange({ finalSubmissionMessage: event.currentTarget.value })} />
          </div>
        </div>
      </Show>

      <Show when={activeTab() === 'library'}>
        <div class="space-y-3">
          <For each={groupedQuestions()}>
            {([category, questions]) => (
              <section class="sub-card">
                <h4>{categoryLabel(category)}</h4>
                <div class="field-grid-2">
                  <For each={questions}>
                    {(question) => {
                      const checked = () => selectedKeySet().has(question.key);
                      return (
                        <label class="nested-card" style={checked() ? 'border-color:#fd6216;background:#fff7ed' : ''}>
                          <div style="display:flex;gap:10px">
                            <input type="checkbox" checked={checked()} onChange={() => toggleQuestion(question)} />
                            <div>
                              <p style="margin:0;font-weight:700">{question.label}</p>
                              <p class="notice" style="margin-top:2px">{question.type}{question.required ? ' • required' : ' • optional'}</p>
                            </div>
                          </div>
                        </label>
                      );
                    }}
                  </For>
                </div>
              </section>
            )}
          </For>

          <section class="sub-card">
            <h4>Add Your Own Question</h4>
            <div class="field-grid-2">
              <input value={customLabel()} onInput={(event) => setCustomLabel(event.currentTarget.value)} placeholder="Question label" />
              <select value={customType()} onChange={(event) => setCustomType(event.currentTarget.value as OnboardingFieldType)}>
                <For each={FIELD_TYPES}>{(type) => <option value={type}>{type}</option>}</For>
              </select>
              <label class="checkbox-label"><input type="checkbox" checked={customRequired()} onChange={(event) => setCustomRequired(event.currentTarget.checked)} />Required</label>
              <Show when={customType() === 'select'} fallback={<p class="notice">No extra options needed</p>}>
                <input value={customOptions()} onInput={(event) => setCustomOptions(event.currentTarget.value)} placeholder="Option 1, Option 2" />
              </Show>
            </div>
            <div class="actions"><button class="btn navy" type="button" onClick={addCustomField}>Add Question</button></div>
          </section>
        </div>
      </Show>

      <Show when={activeTab() === 'selected'}>
        <div class="space-y-3">
          <h3 style="margin:0;font-size:14px;font-weight:700;color:#0f172a">Your Selected Questions</h3>
          <Show when={props.selectedFields.length === 0}>
            <p class="notice">No questions selected yet.</p>
          </Show>
          <For each={props.selectedFields}>
            {(field) => (
              <div class="nested-card">
                <div class="field-grid-2">
                  <input value={field.label} onInput={(event) => updateField(field.id, { label: event.currentTarget.value })} />
                  <select value={field.type} onChange={(event) => updateField(field.id, { type: event.currentTarget.value as OnboardingFieldType })}>
                    <For each={FIELD_TYPES}>{(type) => <option value={type}>{type}</option>}</For>
                  </select>
                  <label class="checkbox-label"><input type="checkbox" checked={field.required} onChange={(event) => updateField(field.id, { required: event.currentTarget.checked })} />Required</label>
                  <button class="btn danger" type="button" onClick={() => removeField(field.id)}>Remove Question</button>
                </div>
                <Show when={field.type === 'select'}>
                  <input
                    style="margin-top:8px"
                    value={(field.options || []).map((item) => item.value).join(', ')}
                    onInput={(event) => updateField(field.id, {
                      options: event.currentTarget.value.split(',').map((item) => item.trim()).filter(Boolean).map((value) => ({ label: value, value })),
                    })}
                    placeholder="Option 1, Option 2"
                  />
                </Show>
              </div>
            )}
          </For>
        </div>
      </Show>

      <Show when={activeTab() === 'preview'}>
        <div class="space-y-3">
          <p class="notice">This preview shows how questions are split across steps before you save.</p>
          <For each={previewSteps()}>
            {(step, index) => (
              <section class="sub-card">
                <h4 style="margin-bottom:6px">Step {index() + 1}</h4>
                <Show when={step.fields.length === 0}>
                  <p class="notice">No questions in this step yet.</p>
                </Show>
                <For each={step.fields}>
                  {(field) => (
                    <div class="kv-item" style="margin-bottom:8px">
                      <p class="kv-label">{field.label}{field.required ? ' *' : ''}</p>
                      <p class="kv-value">{field.type}</p>
                    </div>
                  )}
                </For>
              </section>
            )}
          </For>
        </div>
      </Show>

      <Show when={activeTab() === 'live'}>
        <div class="space-y-3">
          <p class="notice">Live preview opens the real onboarding screen users will see.</p>
          <Show when={props.livePreviewHint}>
            <p class="notice" style="margin-top:0">{props.livePreviewHint}</p>
          </Show>
          <Show
            when={props.livePreviewUrl}
            fallback={<div class="notice" style="padding:10px 12px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">Pick a role first to open live preview.</div>}
          >
            <div style="border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;background:#fff">
              <iframe
                src={props.livePreviewUrl}
                title="Live Onboarding Preview"
                style="width:100%;height:780px;border:0;background:#fff"
                loading="lazy"
              />
            </div>
          </Show>
        </div>
      </Show>

      <div class="actions" style="justify-content:flex-end">
        <button class="btn primary" type="button" disabled={props.saving} onClick={props.onSubmit}>
          {props.saving ? 'Saving...' : props.primaryLabel}
        </button>
      </div>
    </section>
  );
}
