import { useEffect, useMemo, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, Textarea, View } from '@tarojs/components';
import {
  disableTenantMember,
  disableRoleTemplate,
  loadAuthProviders,
  loadTenantMembers,
  loadPaymentAccounts,
  loadRoleTemplates,
  loadTenantDomains,
  loadTenantOverview,
  loadTenantPermissions,
  loadTenantTheme,
  loadThemeTemplates,
  previewTenantTheme,
  publishTenantTheme,
  upsertTenantMember,
  upsertRoleTemplate,
  type TenantMemberItem,
  type TenantOverview,
  type TenantPermissionCatalogItem,
  type TenantPermissionsPayload,
  type TenantRoleTemplateItem,
  type TenantThemeConfigItem,
  type TenantThemeTemplateItem,
} from '@/services/tenantAdmin';
import '../admin.css';

type BooleanMapField = 'permissions' | 'menuPermissions' | 'modulePermissions' | 'fieldPermissions';

interface RoleTemplateForm {
  id?: string;
  code: string;
  name: string;
  description: string;
  baseRole: string;
  status: string;
  sortOrder: string;
  permissions: Record<string, boolean>;
  menuPermissions: Record<string, boolean>;
  modulePermissions: Record<string, boolean>;
  fieldPermissions: Record<string, boolean>;
  dataScopeMode: string;
  ownLeadsOnly: boolean;
}

interface MemberForm {
  membershipId?: string;
  userId: string;
  username: string;
  name: string;
  phone: string;
  email: string;
  role: string;
  status: string;
  roleTemplateId: string;
  permissions: Record<string, boolean>;
}

interface ThemeForm {
  templateCode: string;
  primaryColor: string;
  accentColor: string;
  logoUrl: string;
  shareImageUrl: string;
  iconSet: string;
  shareCardStyle: string;
}

const BASE_ROLE_OPTIONS = [
  { key: 'tenant_operator', label: '运营' },
  { key: 'teacher', label: '教师' },
  { key: 'sales', label: '销售' },
  { key: 'agent', label: '代理' },
  { key: 'student', label: '学生' },
  { key: 'tenant_admin', label: '管理员' },
];

const MEMBER_STATUS_OPTIONS = [
  { key: 'active', label: '启用' },
  { key: 'invited', label: '邀请中' },
  { key: 'disabled', label: '停用' },
];

const STATUS_OPTIONS = [
  { key: 'active', label: '启用' },
  { key: 'disabled', label: '停用' },
  { key: 'archived', label: '归档' },
];

const DATA_SCOPE_OPTIONS = [
  { key: 'tenant', label: '全租户' },
  { key: 'own', label: '本人' },
  { key: 'class', label: '班级' },
  { key: 'sales_team', label: '销售团队' },
];

const MODULE_CATALOG: TenantPermissionCatalogItem[] = [
  { key: 'banners', label: 'Banner' },
  { key: 'announcements', label: '公告' },
  { key: 'faqs', label: 'FAQ' },
  { key: 'coupons', label: '优惠券' },
  { key: 'activation_codes', label: '激活码' },
  { key: 'badges', label: '勋章' },
  { key: 'imports', label: '导入' },
  { key: 'public_question_banks', label: '公共题库' },
  { key: 'assets', label: '资料' },
  { key: 'videos', label: '视频' },
  { key: 'scoreline', label: '分数线' },
  { key: 'vocabulary', label: '单词' },
  { key: 'handbook', label: '知识手册' },
  { key: 'classes', label: '班级' },
  { key: 'followups', label: '跟进' },
  { key: 'commissions', label: '分佣' },
  { key: 'crm_queue', label: 'CRM 队列' },
];

const DEFAULT_THEME_FORM: ThemeForm = {
  templateCode: 'classic',
  primaryColor: '#2563eb',
  accentColor: '#0f766e',
  logoUrl: '',
  shareImageUrl: '',
  iconSet: 'classic',
  shareCardStyle: 'clean',
};

function boolRecord(value: unknown) {
  const source = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
  const result: Record<string, boolean> = {};
  Object.entries(source).forEach(([key, raw]) => {
    if (typeof raw === 'boolean') result[key] = raw;
  });
  return result;
}

function emptyRoleTemplateForm(): RoleTemplateForm {
  return {
    code: '',
    name: '',
    description: '',
    baseRole: 'tenant_operator',
    status: 'active',
    sortOrder: '100',
    permissions: {},
    menuPermissions: {},
    modulePermissions: {},
    fieldPermissions: {},
    dataScopeMode: 'tenant',
    ownLeadsOnly: false,
  };
}

function emptyMemberForm(): MemberForm {
  return {
    userId: '',
    username: '',
    name: '',
    phone: '',
    email: '',
    role: 'tenant_operator',
    status: 'active',
    roleTemplateId: '',
    permissions: {},
  };
}

function roleTemplateFormFrom(item?: TenantRoleTemplateItem | null): RoleTemplateForm {
  if (!item) return emptyRoleTemplateForm();
  const dataScope = item.dataScope && typeof item.dataScope === 'object' ? item.dataScope : {};
  return {
    id: item.id,
    code: item.code || '',
    name: item.name || '',
    description: item.description || '',
    baseRole: item.baseRole || 'tenant_operator',
    status: item.status || 'active',
    sortOrder: String(item.sortOrder ?? 100),
    permissions: boolRecord(item.permissions),
    menuPermissions: boolRecord(item.menuPermissions),
    modulePermissions: boolRecord(item.modulePermissions),
    fieldPermissions: boolRecord(item.fieldPermissions),
    dataScopeMode: String(dataScope.mode || 'tenant'),
    ownLeadsOnly: dataScope.ownLeadsOnly === true,
  };
}

function memberFormFrom(item?: TenantMemberItem | null): MemberForm {
  if (!item) return emptyMemberForm();
  return {
    membershipId: item.id,
    userId: item.userId || '',
    username: item.username || '',
    name: item.name || '',
    phone: item.phone || '',
    email: item.email || '',
    role: item.role || 'tenant_operator',
    status: item.status || 'active',
    roleTemplateId: item.roleTemplateId || '',
    permissions: boolRecord(item.permissions),
  };
}

function stringFromRecord(value: Record<string, unknown> | undefined, key: string, fallback = '') {
  const raw = value?.[key];
  return typeof raw === 'string' ? raw : fallback;
}

function themeFormFrom(item?: TenantThemeConfigItem | null, template?: TenantThemeTemplateItem | null): ThemeForm {
  const theme = item?.draftTemplateCode ? item.draftTheme : item?.activeTheme;
  const assets = item?.draftTemplateCode ? item.draftPublicAssets : item?.activePublicAssets;
  const templateTheme = template?.theme || {};
  const templateAssets = template?.publicAssets || {};
  return {
    templateCode: item?.draftTemplateCode || item?.activeTemplateCode || template?.code || DEFAULT_THEME_FORM.templateCode,
    primaryColor: stringFromRecord(theme, 'primaryColor', stringFromRecord(templateTheme, 'primaryColor', DEFAULT_THEME_FORM.primaryColor)),
    accentColor: stringFromRecord(theme, 'accentColor', stringFromRecord(templateTheme, 'accentColor', DEFAULT_THEME_FORM.accentColor)),
    logoUrl: stringFromRecord(assets, 'logoUrl', stringFromRecord(templateAssets, 'logoUrl', DEFAULT_THEME_FORM.logoUrl)),
    shareImageUrl: stringFromRecord(assets, 'shareImageUrl', stringFromRecord(templateAssets, 'shareImageUrl', DEFAULT_THEME_FORM.shareImageUrl)),
    iconSet: stringFromRecord(assets, 'iconSet', stringFromRecord(templateAssets, 'iconSet', DEFAULT_THEME_FORM.iconSet)),
    shareCardStyle: stringFromRecord(assets, 'shareCardStyle', stringFromRecord(templateAssets, 'shareCardStyle', DEFAULT_THEME_FORM.shareCardStyle)),
  };
}

function catalogLabel(item: TenantPermissionCatalogItem) {
  return item.label ? `${item.label}` : item.key;
}

export default function TenantSettingsPage() {
  const [overview, setOverview] = useState<TenantOverview | null>(null);
  const [domains, setDomains] = useState<Record<string, unknown>[]>([]);
  const [payments, setPayments] = useState<Record<string, unknown>[]>([]);
  const [authProviders, setAuthProviders] = useState<Record<string, unknown>[]>([]);
  const [roles, setRoles] = useState<TenantRoleTemplateItem[]>([]);
  const [members, setMembers] = useState<TenantMemberItem[]>([]);
  const [themeTemplates, setThemeTemplates] = useState<TenantThemeTemplateItem[]>([]);
  const [themeConfig, setThemeConfig] = useState<TenantThemeConfigItem | null>(null);
  const [themeForm, setThemeForm] = useState<ThemeForm>(() => DEFAULT_THEME_FORM);
  const [permissionsPayload, setPermissionsPayload] = useState<TenantPermissionsPayload>({});
  const [selectedRoleId, setSelectedRoleId] = useState('');
  const [roleForm, setRoleForm] = useState<RoleTemplateForm>(() => emptyRoleTemplateForm());
  const [memberKeyword, setMemberKeyword] = useState('');
  const [selectedMemberId, setSelectedMemberId] = useState('');
  const [memberForm, setMemberForm] = useState<MemberForm>(() => emptyMemberForm());
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  const selectedRole = useMemo(
    () => roles.find(item => item.id === selectedRoleId) || null,
    [roles, selectedRoleId],
  );
  const fieldCatalog = permissionsPayload.fieldGroups || permissionsPayload.fieldCatalog || [];
  const editingSystemRole = Boolean(selectedRole?.isSystem);
  const activeRoleTemplates = roles.filter(item => item.status === 'active');
  const selectedThemeTemplate = useMemo(
    () => themeTemplates.find(item => item.code === themeForm.templateCode) || themeTemplates[0] || null,
    [themeTemplates, themeForm.templateCode],
  );

  async function reloadSettings(preferredRoleId = selectedRoleId) {
    setError('');
    try {
      const [overviewPayload, domainPayload, paymentPayload, authPayload, rolePayload, permissionPayload, templatePayload, themePayload] = await Promise.all([
        loadTenantOverview().catch(() => ({ item: null })),
        loadTenantDomains().catch(() => ({ items: [] })),
        loadPaymentAccounts().catch(() => ({ items: [] })),
        loadAuthProviders().catch(() => ({ items: [] })),
        loadRoleTemplates().catch(() => ({ items: [] })),
        loadTenantPermissions().catch(() => ({})),
        loadThemeTemplates().catch(() => ({ items: [] })),
        loadTenantTheme().catch(() => ({ item: null })),
      ]);
      const nextRoles = rolePayload.items || [];
      const nextSelected = nextRoles.find(item => item.id === preferredRoleId) || nextRoles[0] || null;
      const nextThemeTemplates = templatePayload.items || [];
      const nextThemeConfig = themePayload.item || null;
      const nextTemplate = nextThemeTemplates.find(item => item.code === (nextThemeConfig?.draftTemplateCode || nextThemeConfig?.activeTemplateCode)) || nextThemeTemplates[0] || null;
      setOverview(overviewPayload.item || null);
      setDomains(domainPayload.items || []);
      setPayments(paymentPayload.items || []);
      setAuthProviders(authPayload.items || []);
      setRoles(nextRoles);
      setThemeTemplates(nextThemeTemplates);
      setThemeConfig(nextThemeConfig);
      setThemeForm(themeFormFrom(nextThemeConfig, nextTemplate));
      setPermissionsPayload(permissionPayload);
      setSelectedRoleId(nextSelected?.id || '');
      setRoleForm(nextSelected ? roleTemplateFormFrom(nextSelected) : emptyRoleTemplateForm());
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '设置加载失败');
    }
  }

  async function reloadMembers(preferredMemberId = selectedMemberId, keyword = memberKeyword) {
    setError('');
    try {
      const payload = await loadTenantMembers({ keyword, limit: 80 });
      const nextMembers = payload.items || [];
      const nextSelected = nextMembers.find(item => item.id === preferredMemberId) || nextMembers[0] || null;
      setMembers(nextMembers);
      setSelectedMemberId(nextSelected?.id || '');
      setMemberForm(nextSelected ? memberFormFrom(nextSelected) : emptyMemberForm());
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '成员加载失败');
    }
  }

  useEffect(() => {
    void reloadSettings('');
    void reloadMembers('');
  }, []);

  function startNewRole() {
    setSelectedRoleId('');
    setRoleForm(emptyRoleTemplateForm());
  }

  function selectRole(item: TenantRoleTemplateItem) {
    setSelectedRoleId(item.id);
    setRoleForm(roleTemplateFormFrom(item));
  }

  function startNewMember() {
    setSelectedMemberId('');
    setMemberForm(emptyMemberForm());
  }

  function selectMember(item: TenantMemberItem) {
    setSelectedMemberId(item.id);
    setMemberForm(memberFormFrom(item));
  }

  function selectThemeTemplate(item: TenantThemeTemplateItem) {
    setThemeForm(prev => ({
      ...themeFormFrom(null, item),
      logoUrl: prev.logoUrl,
      shareImageUrl: prev.shareImageUrl,
      templateCode: item.code,
    }));
  }

  function updateBooleanMap(field: BooleanMapField, key: string) {
    setRoleForm(prev => ({
      ...prev,
      [field]: {
        ...prev[field],
        [key]: !prev[field][key],
      },
    }));
  }

  function updateMemberPermission(key: string) {
    setMemberForm(prev => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [key]: !prev.permissions[key],
      },
    }));
  }

  async function submitRoleTemplate() {
    if (!roleForm.name.trim() || !roleForm.code.trim()) {
      Taro.showToast({ title: '名称和编码必填', icon: 'none' });
      return;
    }
    if (editingSystemRole) {
      Taro.showToast({ title: '系统模板不可编辑', icon: 'none' });
      return;
    }
    const sortOrder = Number(roleForm.sortOrder || 100);
    if (!Number.isFinite(sortOrder)) {
      Taro.showToast({ title: '排序值无效', icon: 'none' });
      return;
    }

    setBusy('save-role');
    setError('');
    try {
      const result = await upsertRoleTemplate({
        id: roleForm.id,
        code: roleForm.code.trim(),
        name: roleForm.name.trim(),
        description: roleForm.description.trim() || null,
        baseRole: roleForm.baseRole,
        status: roleForm.status,
        sortOrder: Math.trunc(sortOrder),
        permissions: roleForm.permissions,
        menuPermissions: roleForm.menuPermissions,
        modulePermissions: roleForm.modulePermissions,
        fieldPermissions: roleForm.fieldPermissions,
        dataScope: {
          mode: roleForm.dataScopeMode,
          ownLeadsOnly: roleForm.ownLeadsOnly,
        },
      });
      const nextId = result.item?.id || roleForm.id || '';
      Taro.showToast({ title: '角色已保存', icon: 'success' });
      await reloadSettings(nextId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '角色保存失败');
    } finally {
      setBusy('');
    }
  }

  async function disableTemplate(item: TenantRoleTemplateItem) {
    if (item.isSystem) {
      Taro.showToast({ title: '系统模板不可停用', icon: 'none' });
      return;
    }
    const confirmed = await Taro.showModal({
      title: '停用角色模板',
      content: `确认停用 ${item.name || item.code}？`,
      confirmText: '停用',
      cancelText: '取消',
    });
    if (!confirmed.confirm) return;

    setBusy(`disable:${item.id}`);
    setError('');
    try {
      await disableRoleTemplate(item.id);
      Taro.showToast({ title: '已停用', icon: 'success' });
      await reloadSettings(item.id);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '角色停用失败');
    } finally {
      setBusy('');
    }
  }

  async function submitMember() {
    const hasIdentity = memberForm.userId.trim() || memberForm.phone.trim() || memberForm.email.trim() || memberForm.username.trim() || memberForm.name.trim();
    if (!hasIdentity) {
      Taro.showToast({ title: '请填写成员身份', icon: 'none' });
      return;
    }
    setBusy('save-member');
    setError('');
    try {
      const selectedTemplate = activeRoleTemplates.find(item => item.id === memberForm.roleTemplateId);
      const result = await upsertTenantMember({
        membershipId: memberForm.membershipId,
        userId: memberForm.userId.trim() || undefined,
        username: memberForm.username.trim() || null,
        name: memberForm.name.trim() || null,
        phone: memberForm.phone.trim() || null,
        email: memberForm.email.trim() || null,
        primaryRole: selectedTemplate?.baseRole || memberForm.role,
        role: selectedTemplate?.baseRole || memberForm.role,
        status: memberForm.status,
        roleTemplateId: memberForm.roleTemplateId || null,
        permissions: memberForm.permissions,
      });
      const nextId = result.item?.id || memberForm.membershipId || '';
      Taro.showToast({ title: '成员已保存', icon: 'success' });
      await reloadMembers(nextId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '成员保存失败');
    } finally {
      setBusy('');
    }
  }

  async function disableMember(item: TenantMemberItem) {
    const confirmed = await Taro.showModal({
      title: '停用成员',
      content: `确认停用 ${item.name || item.username || item.phone || item.email || item.userId}？`,
      confirmText: '停用',
      cancelText: '取消',
    });
    if (!confirmed.confirm) return;
    setBusy(`disable-member:${item.id}`);
    setError('');
    try {
      await disableTenantMember(item.id);
      Taro.showToast({ title: '成员已停用', icon: 'success' });
      await reloadMembers(item.id);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '成员停用失败');
    } finally {
      setBusy('');
    }
  }

  async function previewTheme() {
    if (!themeForm.templateCode) {
      Taro.showToast({ title: '请选择主题模板', icon: 'none' });
      return;
    }
    setBusy('preview-theme');
    setError('');
    try {
      await previewTenantTheme({
        templateCode: themeForm.templateCode,
        theme: {
          primaryColor: themeForm.primaryColor.trim(),
          accentColor: themeForm.accentColor.trim(),
        },
        publicAssets: {
          ...(themeForm.logoUrl.trim() ? { logoUrl: themeForm.logoUrl.trim() } : {}),
          ...(themeForm.shareImageUrl.trim() ? { shareImageUrl: themeForm.shareImageUrl.trim() } : {}),
          ...(themeForm.iconSet.trim() ? { iconSet: themeForm.iconSet.trim() } : {}),
          ...(themeForm.shareCardStyle.trim() ? { shareCardStyle: themeForm.shareCardStyle.trim() } : {}),
        },
      });
      Taro.showToast({ title: '主题草稿已保存', icon: 'success' });
      await reloadSettings(selectedRoleId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '主题预览失败');
    } finally {
      setBusy('');
    }
  }

  async function publishTheme() {
    const confirmed = await Taro.showModal({
      title: '发布主题',
      content: themeConfig?.draftTemplateCode ? '确认发布当前主题草稿？发布后学生端和后台会读取新主题。' : '当前没有草稿，将按表单配置直接发布主题。',
      confirmText: '发布',
      cancelText: '取消',
    });
    if (!confirmed.confirm) return;

    setBusy('publish-theme');
    setError('');
    try {
      await publishTenantTheme(themeConfig?.draftTemplateCode ? { useDraft: true } : {
        useDraft: false,
        templateCode: themeForm.templateCode,
        theme: {
          primaryColor: themeForm.primaryColor.trim(),
          accentColor: themeForm.accentColor.trim(),
        },
        publicAssets: {
          ...(themeForm.logoUrl.trim() ? { logoUrl: themeForm.logoUrl.trim() } : {}),
          ...(themeForm.shareImageUrl.trim() ? { shareImageUrl: themeForm.shareImageUrl.trim() } : {}),
          ...(themeForm.iconSet.trim() ? { iconSet: themeForm.iconSet.trim() } : {}),
          ...(themeForm.shareCardStyle.trim() ? { shareCardStyle: themeForm.shareCardStyle.trim() } : {}),
        },
      });
      Taro.showToast({ title: '主题已发布', icon: 'success' });
      await reloadSettings(selectedRoleId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '主题发布失败');
    } finally {
      setBusy('');
    }
  }

  function renderToggleGroup(items: TenantPermissionCatalogItem[], field: BooleanMapField) {
    if (!items.length) return <View className='admin-empty'>暂无可配置项。</View>;
    return (
      <View className='admin-actions compact'>
        {items.map(item => (
          <Button
            key={item.key}
            className={`admin-mini-button ${roleForm[field][item.key] ? 'primary' : ''}`}
            onClick={() => updateBooleanMap(field, item.key)}
          >
            {catalogLabel(item)}
          </Button>
        ))}
      </View>
    );
  }

  function renderMemberPermissionGroup(items: TenantPermissionCatalogItem[]) {
    if (!items.length) return <View className='admin-empty'>暂无可配置项。</View>;
    return (
      <View className='admin-actions compact'>
        {items.map(item => (
          <Button
            key={item.key}
            className={`admin-mini-button ${memberForm.permissions[item.key] ? 'primary' : ''}`}
            onClick={() => updateMemberPermission(item.key)}
          >
            {catalogLabel(item)}
          </Button>
        ))}
      </View>
    );
  }

  return (
    <View className='admin-page'>
      <View className='admin-shell'>
        <View className='admin-header'>
          <Text className='admin-kicker'>Settings</Text>
          <Text className='admin-title'>租户设置</Text>
          <Text className='admin-subtitle'>品牌、域名、支付商户、登录 provider 和自定义角色模板。</Text>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>品牌信息</Text>
          <View className='admin-row'>
            <Text className='admin-row-main'>{overview?.brandName || overview?.name || '未配置品牌名'}</Text>
            <Text className='admin-row-meta'>{overview?.slogan || overview?.shortName || '暂无标语'}</Text>
            <Text className='admin-row-meta'>状态 {overview?.status || '-'} · slug {overview?.slug || '-'}</Text>
          </View>
        </View>

        <View className='admin-section'>
          <View className='admin-actions compact'>
            <Text className='admin-section-title'>主题模板</Text>
            <Button className='admin-button' onClick={() => reloadSettings(selectedRoleId)}>刷新主题</Button>
          </View>
          <View className='admin-grid three'>
            {themeTemplates.map(item => (
              <View
                className={`admin-metric theme-template ${themeForm.templateCode === item.code ? 'selected' : ''}`}
                key={item.code}
                onClick={() => selectThemeTemplate(item)}
              >
                <View className='theme-swatch-row'>
                  <View className='theme-swatch' style={{ backgroundColor: String(item.theme?.primaryColor || '#2563eb') }} />
                  <View className='theme-swatch' style={{ backgroundColor: String(item.theme?.accentColor || '#0f766e') }} />
                </View>
                <Text className='admin-metric-value'>{item.name}</Text>
                <Text className='admin-row-meta'>{item.description || item.code}</Text>
              </View>
            ))}
          </View>
          {!themeTemplates.length ? <View className='admin-empty'>暂无主题模板。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>主题草稿</Text>
          <View className='admin-row'>
            <Text className='admin-row-main'>当前发布：{themeConfig?.activeTemplateName || themeConfig?.activeTemplateCode || '未发布模板'}</Text>
            <Text className='admin-row-meta'>草稿：{themeConfig?.draftTemplateName || themeConfig?.draftTemplateCode || '无草稿'} · 状态 {themeConfig?.status || 'published'}</Text>
            <Text className='admin-row-meta'>前端通过 /api/tenant/resolve 读取已发布主题；草稿仅租户后台可见。</Text>
          </View>
          <View className='admin-form-grid'>
            <Input
              className='admin-input'
              placeholder='主色 #2563eb'
              value={themeForm.primaryColor}
              onInput={event => setThemeForm(prev => ({ ...prev, primaryColor: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='强调色 #0f766e'
              value={themeForm.accentColor}
              onInput={event => setThemeForm(prev => ({ ...prev, accentColor: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='Logo URL 或 /assets/...'
              value={themeForm.logoUrl}
              onInput={event => setThemeForm(prev => ({ ...prev, logoUrl: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='分享图 URL 或 /assets/...'
              value={themeForm.shareImageUrl}
              onInput={event => setThemeForm(prev => ({ ...prev, shareImageUrl: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='图标集，例如 classic/focus/contrast'
              value={themeForm.iconSet}
              onInput={event => setThemeForm(prev => ({ ...prev, iconSet: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='分享卡片样式，例如 clean/study/bold'
              value={themeForm.shareCardStyle}
              onInput={event => setThemeForm(prev => ({ ...prev, shareCardStyle: String(event.detail.value || '') }))}
            />
          </View>
          <View className='theme-preview-panel'>
            <View className='theme-preview-banner' style={{ backgroundColor: themeForm.primaryColor || '#2563eb' }}>
              <Text className='theme-preview-title'>{overview?.shortName || overview?.brandName || '租户题库'}</Text>
              <Text className='theme-preview-subtitle'>模板 {selectedThemeTemplate?.name || themeForm.templateCode}</Text>
            </View>
            <View className='theme-preview-actions'>
              <View className='theme-preview-pill' style={{ backgroundColor: themeForm.accentColor || '#0f766e' }} />
              <Text className='admin-row-meta'>主色 {themeForm.primaryColor || '-'} · 强调色 {themeForm.accentColor || '-'}</Text>
            </View>
          </View>
          <View className='admin-actions compact'>
            <Button className='admin-button primary' loading={busy === 'preview-theme'} onClick={previewTheme}>保存草稿</Button>
            <Button className='admin-button' loading={busy === 'publish-theme'} onClick={publishTheme}>发布主题</Button>
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>域名</Text>
          <View className='admin-list'>
            {domains.map((item, index) => (
              <View className='admin-row' key={String(item.id || index)}>
                <Text className='admin-row-main'>{String(item.host || '未命名域名')}</Text>
                <Text className='admin-row-meta'>{String(item.domainType || 'custom')} · {String(item.status || 'pending')} · {item.isPrimary ? '主域名' : '备用'}</Text>
              </View>
            ))}
          </View>
          {!domains.length ? <View className='admin-empty'>暂无域名配置。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>支付账户</Text>
          <View className='admin-grid'>
            {payments.map((item, index) => (
              <View className='admin-metric' key={String(item.id || index)}>
                <Text className='admin-metric-label'>{String(item.provider || 'provider')}</Text>
                <Text className='admin-metric-value'>{String(item.status || 'disabled')}</Text>
                <Text className='admin-row-meta'>{String(item.mode || 'platform_collect')}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>登录配置</Text>
          <View className='admin-list'>
            {authProviders.map((item, index) => (
              <View className='admin-row' key={String(item.id || index)}>
                <Text className='admin-row-main'>{String(item.provider || 'provider')}</Text>
                <Text className='admin-row-meta'>{String(item.status || 'disabled')}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <View className='admin-actions compact'>
            <Text className='admin-section-title'>角色模板</Text>
            <Button className='admin-button primary' onClick={startNewRole}>新建模板</Button>
          </View>
          <View className='admin-list'>
            {roles.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.name || item.code}</Text>
                <Text className='admin-row-meta'>{item.code} · {item.baseRole || '-'} · {item.status || 'active'}{item.isSystem ? ' · system' : ''}</Text>
                <View className='admin-row-actions'>
                  <Button className='admin-mini-button primary' onClick={() => selectRole(item)}>编辑</Button>
                  {!item.isSystem ? (
                    <Button className='admin-mini-button' loading={busy === `disable:${item.id}`} onClick={() => disableTemplate(item)}>停用</Button>
                  ) : null}
                </View>
              </View>
            ))}
          </View>
          {!roles.length ? <View className='admin-empty'>暂无自定义角色模板。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>{selectedRoleId ? '编辑角色模板' : '新建角色模板'}</Text>
          {editingSystemRole ? <View className='admin-empty'>系统模板不可编辑，可新建自定义模板承载租户权限方案。</View> : null}
          <View className='admin-form-grid'>
            <Input
              className='admin-input'
              placeholder='模板名称'
              value={roleForm.name}
              onInput={event => setRoleForm(prev => ({ ...prev, name: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='模板编码，例如 ops-marketing'
              value={roleForm.code}
              disabled={Boolean(roleForm.id)}
              onInput={event => setRoleForm(prev => ({ ...prev, code: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='排序，数字越小越靠前'
              type='number'
              value={roleForm.sortOrder}
              onInput={event => setRoleForm(prev => ({ ...prev, sortOrder: String(event.detail.value || '') }))}
            />
            <Textarea
              className='admin-textarea'
              placeholder='角色说明'
              value={roleForm.description}
              onInput={event => setRoleForm(prev => ({ ...prev, description: String(event.detail.value || '') }))}
            />
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>基础角色</Text>
          <View className='admin-actions compact'>
            {BASE_ROLE_OPTIONS.map(item => (
              <Button
                key={item.key}
                className={`admin-button ${roleForm.baseRole === item.key ? 'active' : ''}`}
                onClick={() => setRoleForm(prev => ({ ...prev, baseRole: item.key }))}
              >
                {item.label}
              </Button>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>模板状态</Text>
          <View className='admin-actions compact'>
            {STATUS_OPTIONS.map(item => (
              <Button
                key={item.key}
                className={`admin-button ${roleForm.status === item.key ? 'active' : ''}`}
                onClick={() => setRoleForm(prev => ({ ...prev, status: item.key }))}
              >
                {item.label}
              </Button>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>权限点</Text>
          {renderToggleGroup(permissionsPayload.permissions || [], 'permissions')}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>菜单可见</Text>
          {renderToggleGroup(permissionsPayload.menuGroups || [], 'menuPermissions')}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>模块可见</Text>
          {renderToggleGroup(MODULE_CATALOG, 'modulePermissions')}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>字段可见</Text>
          {renderToggleGroup(fieldCatalog, 'fieldPermissions')}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>数据范围</Text>
          <View className='admin-actions compact'>
            {DATA_SCOPE_OPTIONS.map(item => (
              <Button
                key={item.key}
                className={`admin-button ${roleForm.dataScopeMode === item.key ? 'active' : ''}`}
                onClick={() => setRoleForm(prev => ({ ...prev, dataScopeMode: item.key }))}
              >
                {item.label}
              </Button>
            ))}
            <Button
              className={`admin-button ${roleForm.ownLeadsOnly ? 'active' : ''}`}
              onClick={() => setRoleForm(prev => ({ ...prev, ownLeadsOnly: !prev.ownLeadsOnly }))}
            >
              本人客资
            </Button>
          </View>
        </View>

        <View className='admin-section'>
          <View className='admin-actions compact'>
            <Button className='admin-button primary' loading={busy === 'save-role'} onClick={submitRoleTemplate}>保存模板</Button>
            <Button className='admin-button' onClick={() => reloadSettings(selectedRoleId)}>刷新</Button>
          </View>
        </View>

        <View className='admin-section'>
          <View className='admin-actions compact'>
            <Text className='admin-section-title'>成员与模板绑定</Text>
            <Button className='admin-button primary' onClick={startNewMember}>新建成员</Button>
          </View>
          <View className='admin-form-grid'>
            <Input
              className='admin-input'
              placeholder='搜索姓名、手机号、邮箱、用户名'
              value={memberKeyword}
              onInput={event => setMemberKeyword(String(event.detail.value || ''))}
            />
            <Button className='admin-button primary' onClick={() => reloadMembers('', memberKeyword)}>搜索成员</Button>
          </View>
          <View className='admin-list'>
            {members.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.name || item.username || item.phone || item.email || item.userId}</Text>
                <Text className='admin-row-meta'>{item.role} · {item.status || 'active'} · {item.roleTemplateName || item.roleTemplateCode || '未绑定模板'}</Text>
                <Text className='admin-row-meta'>{item.phone || '-'} · {item.email || '-'}</Text>
                <View className='admin-row-actions'>
                  <Button className='admin-mini-button primary' onClick={() => selectMember(item)}>编辑</Button>
                  {item.status !== 'disabled' ? (
                    <Button className='admin-mini-button' loading={busy === `disable-member:${item.id}`} onClick={() => disableMember(item)}>停用</Button>
                  ) : null}
                </View>
              </View>
            ))}
          </View>
          {!members.length ? <View className='admin-empty'>暂无成员或搜索无结果。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>{selectedMemberId ? '编辑成员权限' : '新建成员权限'}</Text>
          <View className='admin-form-grid'>
            <Input
              className='admin-input'
              placeholder='已有用户 ID，可留空用手机号/邮箱创建或匹配'
              value={memberForm.userId}
              disabled={Boolean(memberForm.membershipId)}
              onInput={event => setMemberForm(prev => ({ ...prev, userId: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='姓名'
              value={memberForm.name}
              onInput={event => setMemberForm(prev => ({ ...prev, name: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='用户名'
              value={memberForm.username}
              onInput={event => setMemberForm(prev => ({ ...prev, username: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='手机号'
              type='number'
              value={memberForm.phone}
              onInput={event => setMemberForm(prev => ({ ...prev, phone: String(event.detail.value || '') }))}
            />
            <Input
              className='admin-input'
              placeholder='邮箱'
              value={memberForm.email}
              onInput={event => setMemberForm(prev => ({ ...prev, email: String(event.detail.value || '') }))}
            />
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>绑定角色模板</Text>
          <View className='admin-actions compact'>
            <Button
              className={`admin-button ${memberForm.roleTemplateId ? '' : 'active'}`}
              onClick={() => setMemberForm(prev => ({ ...prev, roleTemplateId: '' }))}
            >
              不绑定
            </Button>
            {activeRoleTemplates.map(item => (
              <Button
                key={item.id}
                className={`admin-button ${memberForm.roleTemplateId === item.id ? 'active' : ''}`}
                onClick={() => setMemberForm(prev => ({ ...prev, roleTemplateId: item.id, role: item.baseRole || prev.role }))}
              >
                {item.name || item.code}
              </Button>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>成员基础角色</Text>
          <View className='admin-actions compact'>
            {BASE_ROLE_OPTIONS.map(item => (
              <Button
                key={item.key}
                className={`admin-button ${memberForm.role === item.key ? 'active' : ''}`}
                onClick={() => setMemberForm(prev => ({ ...prev, role: item.key, roleTemplateId: '' }))}
              >
                {item.label}
              </Button>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>成员状态</Text>
          <View className='admin-actions compact'>
            {MEMBER_STATUS_OPTIONS.map(item => (
              <Button
                key={item.key}
                className={`admin-button ${memberForm.status === item.key ? 'active' : ''}`}
                onClick={() => setMemberForm(prev => ({ ...prev, status: item.key }))}
              >
                {item.label}
              </Button>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>成员额外权限覆盖</Text>
          {renderMemberPermissionGroup(permissionsPayload.permissions || [])}
        </View>

        <View className='admin-section'>
          <View className='admin-actions compact'>
            <Button className='admin-button primary' loading={busy === 'save-member'} onClick={submitMember}>保存成员</Button>
            <Button className='admin-button' onClick={() => reloadMembers(selectedMemberId)}>刷新成员</Button>
          </View>
        </View>

        {error ? <Text className='admin-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
