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

export type ExternalRoleConfig = {
  id?: string;
  roleKey: string;
  displayName: string;
  vertical: 'jobs' | 'marketplace';
  roleCategory: 'provider' | 'employer' | 'consumer' | 'specialist';
  enabledModules: string[];
  permissions: Record<string, string[]>;
  onboardingSchemaId: string;
  requiresOnboardingApproval: boolean;
  requiresLeadApproval: boolean;
  requiresJobApproval: boolean;
  featureLimits: Record<string, unknown>;
  runtimeConfigVersion: number;
  isActive: boolean;
};

type RolePermissionAction = {
  key: string;
  label: string;
};

type ModuleOption = {
  key: string;
  label: string;
  description: string;
};

type ExternalRoleFormProps = {
  initialValue: ExternalRoleConfig;
  onboardingSchemaOptions?: string[];
  saving?: boolean;
  submitLabel: string;
  onSubmit: (value: ExternalRoleConfig) => Promise<void> | void;
};

const ROLE_PERMISSION_ACTIONS: RolePermissionAction[] = [
  { key: 'read', label: 'Read' },
  { key: 'create', label: 'Create' },
  { key: 'update', label: 'Update' },
  { key: 'delete', label: 'Delete' },
  { key: 'approve', label: 'Approve' },
];

const ONBOARDING_SCHEMA_OPTIONS = [
  'company_onboarding_v1',
  'job_seeker_onboarding_v1',
  'customer_onboarding_v1',
  'photographer_onboarding_v1',
  'makeup_artist_onboarding_v1',
  'tutor_onboarding_v1',
  'developer_onboarding_v1',
  'video_editor_onboarding_v1',
  'graphic_designer_onboarding_v1',
  'social_media_manager_onboarding_v1',
  'fitness_trainer_onboarding_v1',
  'catering_service_onboarding_v1',
  'ugc_content_creator_onboarding_v1',
  'default_onboarding_v1',
];

const MODULES_BY_VERTICAL: Record<'jobs' | 'marketplace', ModuleOption[]> = {
  jobs: [
    { key: 'dashboard', label: 'Dashboard', description: 'Home page with KPI summary cards.' },
    { key: 'profile', label: 'Profile', description: 'Maintain role profile and preferences.' },
    { key: 'jobs', label: 'Jobs', description: 'Manage job postings and candidate flow.' },
    { key: 'applications', label: 'Applications', description: 'Review incoming applications and hiring flow.' },
    { key: 'notifications', label: 'Notifications', description: 'View and manage alerts.' },
    { key: 'settings', label: 'Settings', description: 'Account settings and password.' },
  ],
  marketplace: [
    { key: 'dashboard', label: 'Dashboard', description: 'Home page with KPI summary cards.' },
    { key: 'profile', label: 'Profile', description: 'Public-facing professional or customer profile.' },
    { key: 'portfolio', label: 'Portfolio', description: 'Publish portfolio items and case studies.' },
    { key: 'services', label: 'Services', description: 'List services with pricing and duration.' },
    { key: 'leads', label: 'Leads / Requests', description: 'Handle incoming lead requests from customers.' },
    { key: 'requirements', label: 'Requirements', description: 'Post and manage customer requirements (consumers).' },
    { key: 'marketplace', label: 'Marketplace', description: 'Browse and send requests to professionals (consumers).' },
    { key: 'wallet', label: 'Wallet', description: 'Tracecoin balance, history, and top-up.' },
    { key: 'notifications', label: 'Notifications', description: 'View and manage alerts.' },
    { key: 'settings', label: 'Settings', description: 'Account settings and password.' },
  ],
};

const MARKETPLACE_PROVIDER_MODULES = ['dashboard', 'profile', 'portfolio', 'services', 'leads', 'wallet', 'notifications', 'settings'];
const MARKETPLACE_PROVIDER_PERMISSIONS: Record<string, string[]> = {
  dashboard: ['read'],
  profile: ['read', 'update'],
  portfolio: ['read', 'create', 'update', 'delete'],
  services: ['read', 'create', 'update', 'delete'],
  leads: ['read', 'update'],
  wallet: ['read'],
  notifications: ['read'],
  settings: ['read', 'update'],
};

const DEFAULT_PRESETS: Record<string, ExternalRoleConfig> = {
  company: {
    roleKey: 'company',
    displayName: 'Company',
    vertical: 'jobs',
    roleCategory: 'employer',
    enabledModules: ['dashboard', 'profile', 'jobs', 'applications', 'notifications', 'settings'],
    permissions: {
      dashboard: ['read'],
      profile: ['read', 'update'],
      jobs: ['read', 'create', 'update'],
      applications: ['read', 'approve'],
      notifications: ['read'],
      settings: ['read', 'update'],
    },
    onboardingSchemaId: 'company_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: false,
    requiresJobApproval: true,
    featureLimits: { maxActiveJobs: 5 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  job_seeker: {
    roleKey: 'job_seeker',
    displayName: 'Job Seeker',
    vertical: 'jobs',
    roleCategory: 'specialist',
    enabledModules: ['dashboard', 'profile', 'jobs', 'applications', 'notifications', 'settings'],
    permissions: {
      dashboard: ['read'],
      profile: ['read', 'update'],
      jobs: ['read'],
      applications: ['read', 'create'],
      notifications: ['read'],
      settings: ['read', 'update'],
    },
    onboardingSchemaId: 'job_seeker_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: false,
    requiresJobApproval: false,
    featureLimits: { maxApplicationsPerDay: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  customer: {
    roleKey: 'customer',
    displayName: 'Service Seeker',
    vertical: 'marketplace',
    roleCategory: 'consumer',
    enabledModules: ['dashboard', 'profile', 'requirements', 'marketplace', 'wallet', 'notifications', 'settings'],
    permissions: {
      dashboard: ['read'],
      profile: ['read', 'update'],
      requirements: ['read', 'create', 'update'],
      marketplace: ['read'],
      wallet: ['read', 'create'],
      notifications: ['read'],
      settings: ['read', 'update'],
    },
    onboardingSchemaId: 'customer_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: false,
    requiresJobApproval: false,
    featureLimits: { maxActiveRequirements: 2 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  ugc_content_creator: {
    roleKey: 'ugc_content_creator',
    displayName: 'UGC Content Creator',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'ugc_content_creator_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  photographer: {
    roleKey: 'photographer',
    displayName: 'Photographer',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'photographer_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  makeup_artist: {
    roleKey: 'makeup_artist',
    displayName: 'Makeup Artist',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'makeup_artist_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  tutor: {
    roleKey: 'tutor',
    displayName: 'Tutor',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'tutor_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  developer: {
    roleKey: 'developer',
    displayName: 'Developer',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'developer_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  video_editor: {
    roleKey: 'video_editor',
    displayName: 'Video Editor',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'video_editor_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  graphic_designer: {
    roleKey: 'graphic_designer',
    displayName: 'Graphic Designer',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'graphic_designer_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  social_media_manager: {
    roleKey: 'social_media_manager',
    displayName: 'Social Media Manager',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'social_media_manager_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  fitness_trainer: {
    roleKey: 'fitness_trainer',
    displayName: 'Fitness Trainer',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'fitness_trainer_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
  catering_service: {
    roleKey: 'catering_service',
    displayName: 'Catering Service',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: MARKETPLACE_PROVIDER_MODULES,
    permissions: MARKETPLACE_PROVIDER_PERMISSIONS,
    onboardingSchemaId: 'catering_service_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: true,
    requiresJobApproval: false,
    featureLimits: { maxOpenLeads: 10 },
    runtimeConfigVersion: 1,
    isActive: true,
  },
};

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

function parseFeatureLimits(raw: string): Record<string, unknown> {
  const parsed = JSON.parse(raw || '{}');
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error('Advanced limits must be valid JSON (object format).');
  }
  return parsed as Record<string, unknown>;
}

export default function ExternalRoleForm(props: ExternalRoleFormProps) {
  const [config, setConfig] = createSignal<ExternalRoleConfig>(props.initialValue);
  const [featureLimitsRaw, setFeatureLimitsRaw] = createSignal(JSON.stringify(props.initialValue.featureLimits || {}, null, 2));
  const [errors, setErrors] = createSignal<Record<string, string>>({});

  createEffect(() => {
    setConfig(props.initialValue);
    setFeatureLimitsRaw(JSON.stringify(props.initialValue.featureLimits || {}, null, 2));
    setErrors({});
  });

  const moduleOptions = createMemo(() => MODULES_BY_VERTICAL[config().vertical] || MODULES_BY_VERTICAL.marketplace);
  const onboardingOptions = createMemo(() => {
    const fromProps = Array.isArray(props.onboardingSchemaOptions) ? props.onboardingSchemaOptions : [];
    const fromDefaults = ONBOARDING_SCHEMA_OPTIONS;
    const current = config().onboardingSchemaId ? [config().onboardingSchemaId] : [];
    return Array.from(new Set([...fromProps, ...fromDefaults, ...current].filter(Boolean)));
  });

  createEffect(() => {
    const allowed = new Set(moduleOptions().map((item) => item.key));
    setConfig((current) => ({
      ...current,
      enabledModules: current.enabledModules.filter((item) => allowed.has(item)),
      permissions: Object.fromEntries(Object.entries(current.permissions).filter(([key]) => allowed.has(key))),
    }));
  });

  const setConfigPatch = (patch: Partial<ExternalRoleConfig>) => setConfig((current) => ({ ...current, ...patch }));

  const applyPreset = (presetKey: string) => {
    const preset = DEFAULT_PRESETS[presetKey];
    if (!preset) return;
    const next = {
      ...preset,
      runtimeConfigVersion: (config().runtimeConfigVersion || 1) + 1,
    };
    setConfig(next);
    setFeatureLimitsRaw(JSON.stringify(next.featureLimits || {}, null, 2));
    setErrors({});
  };

  const updateModuleSelection = (moduleKey: string, enabled: boolean) => {
    setConfig((current) => {
      const enabledModules = enabled
        ? Array.from(new Set([...current.enabledModules, moduleKey]))
        : current.enabledModules.filter((value) => value !== moduleKey);
      const nextPermissions = { ...current.permissions };
      if (!enabled) delete nextPermissions[moduleKey];
      return { ...current, enabledModules, permissions: nextPermissions };
    });
  };

  const applyRecommendedModules = () => {
    const recommended = config().vertical === 'jobs'
      ? (config().roleCategory === 'employer'
          ? ['dashboard', 'profile', 'jobs', 'applications', 'notifications', 'settings']
          : ['dashboard', 'profile', 'jobs', 'applications', 'notifications', 'settings'])
      : (config().roleCategory === 'consumer'
          ? ['dashboard', 'profile', 'requirements', 'marketplace', 'wallet', 'notifications', 'settings']
          : MARKETPLACE_PROVIDER_MODULES);
    const allowed = new Set(moduleOptions().map((item) => item.key));
    const enabledModules = recommended.filter((key) => allowed.has(key));
    const nextPermissions = { ...config().permissions };
    enabledModules.forEach((moduleKey) => {
      if (!nextPermissions[moduleKey] || nextPermissions[moduleKey].length === 0) {
        nextPermissions[moduleKey] = moduleKey === 'dashboard' || moduleKey === 'wallet' || moduleKey === 'notifications'
          ? ['read']
          : ['read', 'update'];
      }
    });
    setConfigPatch({ enabledModules, permissions: nextPermissions });
  };

  const selectAllModules = () => {
    const enabledModules = moduleOptions().map((option) => option.key);
    const nextPermissions = { ...config().permissions };
    enabledModules.forEach((moduleKey) => {
      if (!nextPermissions[moduleKey] || nextPermissions[moduleKey].length === 0) {
        nextPermissions[moduleKey] = ['read'];
      }
    });
    setConfigPatch({ enabledModules, permissions: nextPermissions });
  };

  const clearAllModules = () => {
    setConfigPatch({ enabledModules: [], permissions: {} });
  };

  const togglePermission = (moduleKey: string, action: string) => {
    setConfig((current) => {
      const next = new Set(current.permissions[moduleKey] || []);
      if (next.has(action)) next.delete(action);
      else next.add(action);
      return {
        ...current,
        permissions: {
          ...current.permissions,
          [moduleKey]: Array.from(next),
        },
      };
    });
  };

  const validateAndSubmit = async () => {
    const nextErrors: Record<string, string> = {};
    const normalizedRoleKey = slugifyRoleKey(config().roleKey);
    if (!normalizedRoleKey) nextErrors.roleKey = 'Role code is required.';
    if (!config().displayName.trim()) nextErrors.displayName = 'Role name is required.';
    if (config().enabledModules.length === 0) nextErrors.enabledModules = 'Select at least one area/page.';

    const modulesWithoutPermissions = config().enabledModules.filter((moduleKey) => !(config().permissions[moduleKey] || []).length);
    if (modulesWithoutPermissions.length > 0) {
      nextErrors.permissions = `Choose at least one access permission for: ${modulesWithoutPermissions.join(', ')}.`;
    }

    let featureLimits: Record<string, unknown> = {};
    try {
      featureLimits = parseFeatureLimits(featureLimitsRaw());
    } catch (error: any) {
      nextErrors.featureLimits = error?.message || 'Feature limits JSON is invalid.';
    }

    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;

    await props.onSubmit({
      ...config(),
      roleKey: normalizedRoleKey,
      featureLimits,
    });
  };

  return (
    <div class="space-y-6">
      <section class="card">
        <div class="list-header">
          <div>
            <h2>External Role Setup</h2>
            <p class="notice" style="margin-top:2px">
              Set up what this role can see and do in the app.
            </p>
          </div>
          <div class="field" style="min-width:220px;margin:0">
            <label>Start from a template</label>
            <select
              value=""
              onChange={(event) => {
                if (event.currentTarget.value) {
                  applyPreset(event.currentTarget.value);
                  event.currentTarget.value = '';
                }
              }}
            >
              <option value="">Choose a template</option>
              <optgroup label="Jobs Vertical">
                <option value="company">Company (Employer)</option>
                <option value="job_seeker">Job Seeker</option>
              </optgroup>
              <optgroup label="Marketplace — Consumer">
                <option value="customer">Service Seeker</option>
              </optgroup>
              <optgroup label="Marketplace — Providers">
                <option value="photographer">Photographer</option>
                <option value="makeup_artist">Makeup Artist</option>
                <option value="tutor">Tutor</option>
                <option value="developer">Developer</option>
                <option value="video_editor">Video Editor</option>
                <option value="ugc_content_creator">UGC Content Creator</option>
                <option value="graphic_designer">Graphic Designer</option>
                <option value="social_media_manager">Social Media Manager</option>
                <option value="fitness_trainer">Fitness Trainer</option>
                <option value="catering_service">Catering Service</option>
              </optgroup>
            </select>
          </div>
        </div>

        <div class="field-grid-2">
          <div class="field">
            <label>Role Code</label>
            <input value={config().roleKey} onInput={(event) => setConfigPatch({ roleKey: event.currentTarget.value })} placeholder="company" />
            <Show when={errors().roleKey}><p class="error-note">{errors().roleKey}</p></Show>
          </div>
          <div class="field">
            <label>Role Name</label>
            <input value={config().displayName} onInput={(event) => setConfigPatch({ displayName: event.currentTarget.value })} placeholder="Company" />
            <Show when={errors().displayName}><p class="error-note">{errors().displayName}</p></Show>
          </div>
          <div class="field">
            <label>App Area</label>
            <select value={config().vertical} onChange={(event) => setConfigPatch({ vertical: event.currentTarget.value as 'jobs' | 'marketplace' })}>
              <option value="jobs">Jobs</option>
              <option value="marketplace">Marketplace</option>
            </select>
          </div>
          <div class="field">
            <label>Role Type</label>
            <select value={config().roleCategory} onChange={(event) => setConfigPatch({ roleCategory: event.currentTarget.value as ExternalRoleConfig['roleCategory'] })}>
              <option value="provider">Provider</option>
              <option value="employer">Employer</option>
              <option value="consumer">Consumer</option>
              <option value="specialist">Specialist</option>
            </select>
          </div>
          <div class="field">
            <label>Profile Flow Config</label>
            <select value={config().onboardingSchemaId} onChange={(event) => setConfigPatch({ onboardingSchemaId: event.currentTarget.value })}>
              <For each={onboardingOptions()}>
                {(schemaId) => <option value={schemaId}>{schemaId}</option>}
              </For>
            </select>
          </div>
          <div class="field" style="display:flex;align-items:flex-end">
            <label class="checkbox-label">
              <input type="checkbox" checked={config().isActive} onChange={(event) => setConfigPatch({ isActive: event.currentTarget.checked })} />
              This role is active
            </label>
          </div>
        </div>
      </section>

      <section class="card">
        <h2 style="margin-bottom:4px">Visible Areas</h2>
        <p class="notice" style="margin:0 0 10px">Choose which pages/areas this role can access.</p>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin:0 0 12px">
          <button class="btn" type="button" onClick={applyRecommendedModules}>Use Recommended</button>
          <button class="btn" type="button" onClick={selectAllModules}>Select All</button>
          <button class="btn" type="button" onClick={clearAllModules}>Clear All</button>
          <span class="notice" style="align-self:center">{moduleOptions().length} available modules</span>
        </div>
        <div class="field-grid-2">
          <For each={moduleOptions()}>
            {(option) => {
              const checked = () => config().enabledModules.includes(option.key);
              return (
                <label class="nested-card" style={checked() ? 'border-color:#fd6216;background:#fff7ed' : ''}>
                  <div style="display:flex;gap:10px;align-items:flex-start">
                    <input type="checkbox" checked={checked()} onChange={(event) => updateModuleSelection(option.key, event.currentTarget.checked)} />
                    <div>
                      <p style="margin:0;font-size:14px;font-weight:700;color:#0f172a">{option.label}</p>
                      <p class="notice" style="margin-top:2px">{option.description}</p>
                    </div>
                  </div>
                </label>
              );
            }}
          </For>
        </div>
        <Show when={moduleOptions().length === 0}>
          <p class="error-note">No module options were found for this app area. Switch the app area and try again.</p>
        </Show>
        <Show when={errors().enabledModules}><p class="error-note">{errors().enabledModules}</p></Show>
      </section>

      <section class="card">
        <h2 style="margin-bottom:4px">Access Permissions</h2>
        <p class="notice" style="margin:0 0 10px">Choose what actions this role can do in each selected area.</p>
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Area</th>
                <For each={ROLE_PERMISSION_ACTIONS}>
                  {(action) => <th class="align-right">{action.label}</th>}
                </For>
              </tr>
            </thead>
            <tbody>
              <Show when={config().enabledModules.length === 0}>
                <tr><td colspan={ROLE_PERMISSION_ACTIONS.length + 1} style="text-align:center;padding:18px;color:#64748b">Select at least one area to set permissions.</td></tr>
              </Show>
              <For each={moduleOptions().filter((option) => config().enabledModules.includes(option.key))}>
                {(option) => (
                  <tr>
                    <td>{option.label}</td>
                    <For each={ROLE_PERMISSION_ACTIONS}>
                      {(action) => {
                        const checked = () => (config().permissions[option.key] || []).includes(action.key);
                        return (
                          <td class="align-right">
                            <input type="checkbox" checked={checked()} onChange={() => togglePermission(option.key, action.key)} />
                          </td>
                        );
                      }}
                    </For>
                  </tr>
                )}
              </For>
            </tbody>
          </table>
        </div>
        <Show when={errors().permissions}><p class="error-note">{errors().permissions}</p></Show>
      </section>

      <section class="card">
        <h2 style="margin-bottom:6px">Approvals & Limits</h2>
        <div class="field-grid-2">
          <label class="checkbox-label"><input type="checkbox" checked={config().requiresOnboardingApproval} onChange={(event) => setConfigPatch({ requiresOnboardingApproval: event.currentTarget.checked })} />Require profile verification before full access</label>
          <label class="checkbox-label"><input type="checkbox" checked={config().requiresLeadApproval} onChange={(event) => setConfigPatch({ requiresLeadApproval: event.currentTarget.checked })} />Review incoming leads before approval</label>
          <label class="checkbox-label"><input type="checkbox" checked={config().requiresJobApproval} onChange={(event) => setConfigPatch({ requiresJobApproval: event.currentTarget.checked })} />Review job posts before approval</label>
        </div>
        <div class="field" style="margin-top:10px">
          <label>Advanced Limits (optional JSON)</label>
          <textarea rows="8" value={featureLimitsRaw()} onInput={(event) => setFeatureLimitsRaw(event.currentTarget.value)} />
          <p class="notice" style="margin:6px 0 0">Leave this as `{}` unless you need advanced limits.</p>
          <Show when={errors().featureLimits}><p class="error-note">{errors().featureLimits}</p></Show>
        </div>
      </section>

      <div class="actions" style="justify-content:flex-end">
        <button class="btn primary" onClick={() => void validateAndSubmit()} disabled={props.saving}>
          {props.saving ? 'Saving...' : props.submitLabel}
        </button>
      </div>
    </div>
  );
}
