import {
  DeleteOutlined,
  EditOutlined,
  EllipsisOutlined,
  EyeOutlined,
  GlobalOutlined,
  MailOutlined,
  ReloadOutlined,
  SearchOutlined,
  SendOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import {
  Alert,
  App,
  Button,
  Card,
  Dropdown,
  Form,
  Grid,
  Input,
  List,
  Modal,
  Pagination,
  Result,
  Select,
  Skeleton,
  Space,
  Table,
  Tooltip,
  Typography
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

import { EmptyState } from '../../components/common/EmptyState';
import { PageHeader } from '../../components/common/PageHeader';
import { SectionCard } from '../../components/common/SectionCard';
import { StatusPill } from '../../components/common/StatusPill';
import { AddDomainDrawer } from '../../components/domain/AddDomainDrawer';
import { useAppContext } from '../../frontend/app-context';
import { buildDomainHealth, getRecordStatusMeta } from '../../frontend/domain-model.js';
import { useI18n } from '../../frontend/i18n/react';
import { api } from '../../frontend/services/api';
import type { AddDomainPayload, DnsCredential, DnsRecord, Domain, SendEvent, SmtpRelay } from '../../frontend/types';

interface DomainsData {
  domains: Domain[];
  events: SendEvent[];
  dnsCredentials: DnsCredential[];
  smtpRelays: SmtpRelay[];
}

const DEFAULT_PAGE = 1;
const DEFAULT_PAGE_SIZE = 20;

interface DomainSetupOperations {
  createDomain: (values: AddDomainPayload) => Promise<{ domain: Domain }>;
  applyDns: (id: number) => Promise<{ domain: Domain; apply?: Domain['status']['apply'] }>;
  checkDomain: (id: number) => Promise<{ domain: Domain }>;
}

export interface DomainSetupResult {
  domain: Domain;
  setup: 'complete' | 'partial';
  followUp: 'apply' | 'check' | 'none';
  error?: string;
}

export async function createDomainWithSetup(
  values: AddDomainPayload,
  operations: DomainSetupOperations
): Promise<DomainSetupResult> {
  const created = await operations.createDomain(values);
  const credentialId = Number(values.dnsCredentialId || 0);
  const followUp = credentialId > 0 ? 'apply' : (values.immediateCheck ? 'check' : 'none');

  if (followUp === 'none') {
    return { domain: created.domain, setup: 'complete', followUp };
  }

  try {
    if (followUp === 'apply') {
      const result = await operations.applyDns(created.domain.id);
      const apply = result.apply || result.domain.status?.apply;
      if (apply?.ok === false) {
        return {
          domain: result.domain,
          setup: 'partial',
          followUp,
          error: firstDnsApplyError(apply)
        };
      }
      return { domain: result.domain, setup: 'complete', followUp };
    }

    const result = await operations.checkDomain(created.domain.id);
    return { domain: result.domain, setup: 'complete', followUp };
  } catch (reason) {
    return {
      domain: created.domain,
      setup: 'partial',
      followUp,
      error: reason instanceof Error ? reason.message : undefined
    };
  }
}

export function readDomainPagination(searchParams: URLSearchParams) {
  const requestedPageSize = positiveInteger(searchParams.get('pageSize'), DEFAULT_PAGE_SIZE);
  return {
    page: positiveInteger(searchParams.get('page'), DEFAULT_PAGE),
    pageSize: [10, 20, 50, 100].includes(requestedPageSize) ? requestedPageSize : DEFAULT_PAGE_SIZE
  };
}

export function paginateDomains<T>(items: T[], page: number, pageSize: number) {
  const start = (page - 1) * pageSize;
  return items.slice(start, start + pageSize);
}

export default function DomainsPage() {
  const { config } = useAppContext();
  const { locale } = useI18n();
  const copy = locale.startsWith('en') ? enCopy : zhCopy;
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const screens = Grid.useBreakpoint();
  const { message } = App.useApp();
  const [data, setData] = useState<DomainsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [auxiliaryErrors, setAuxiliaryErrors] = useState({ dns: '', relays: '', activity: '' });
  const [deleteTarget, setDeleteTarget] = useState<Domain | null>(null);
  const [deleteConfirmation, setDeleteConfirmation] = useState('');
  const [testTarget, setTestTarget] = useState<Domain | null>(null);
  const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
  const [testForm] = Form.useForm<{ to: string; subject: string; text: string }>();

  const query = searchParams.get('q') || '';
  const status = searchParams.get('status') || undefined;
  const addOpen = searchParams.get('create') === '1';
  const { page, pageSize } = readDomainPagination(searchParams);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    setAuxiliaryErrors({ dns: '', relays: '', activity: '' });
    const [domainsResult, credentialsResult, relaysResult, eventsResult] = await Promise.allSettled([
      api.domains(),
      api.dnsCredentials(),
      api.smtpRelays(),
      api.events({ page: 1, pageSize: 100 })
    ]);
    if (domainsResult.status === 'rejected') {
      setError(domainsResult.reason instanceof Error ? domainsResult.reason.message : copy.loadFailed);
    } else {
      setData((current) => ({
        domains: domainsResult.value.domains,
        dnsCredentials: credentialsResult.status === 'fulfilled' ? credentialsResult.value.credentials : current?.dnsCredentials || [],
        smtpRelays: relaysResult.status === 'fulfilled' ? relaysResult.value.relays : current?.smtpRelays || [],
        events: eventsResult.status === 'fulfilled' ? eventsResult.value.events : current?.events || []
      }));
    }
    setAuxiliaryErrors({
      dns: credentialsResult.status === 'rejected' ? errorText(credentialsResult.reason, copy.auxUnavailable) : '',
      relays: relaysResult.status === 'rejected' ? errorText(relaysResult.reason, copy.auxUnavailable) : '',
      activity: eventsResult.status === 'rejected' ? errorText(eventsResult.reason, copy.auxUnavailable) : ''
    });
    setLoading(false);
  }, [copy.loadFailed]);

  useEffect(() => {
    void load();
  }, [load]);

  const filtered = useMemo(() => {
    if (!data) return [];
    const normalizedQuery = query.trim().toLowerCase();
    return data.domains.filter((domain) => {
      const health = buildDomainHealth(domain);
      const matchesQuery = !normalizedQuery
        || domain.domain.toLowerCase().includes(normalizedQuery)
        || domain.senderHost.toLowerCase().includes(normalizedQuery);
      return matchesQuery && (!status || health.status === status);
    });
  }, [data, query, status]);
  const pagedDomains = useMemo(() => paginateDomains(filtered, page, pageSize), [filtered, page, pageSize]);

  useEffect(() => {
    if (!data) return;
    const maxPage = Math.max(DEFAULT_PAGE, Math.ceil(filtered.length / pageSize));
    const normalizedPage = Math.min(page, maxPage);
    if (searchParams.get('page') === String(normalizedPage) && searchParams.get('pageSize') === String(pageSize)) return;
    const next = new URLSearchParams(searchParams);
    next.set('page', String(normalizedPage));
    next.set('pageSize', String(pageSize));
    setSearchParams(next, { replace: true });
  }, [data, filtered.length, page, pageSize, searchParams, setSearchParams]);

  const credentialNames = useMemo(() => new Map(data?.dnsCredentials.map((item) => [item.id, item.name]) || []), [data?.dnsCredentials]);
  const lastActivity = useMemo(() => {
    const map = new Map<string, SendEvent>();
    for (const event of data?.events || []) {
      if (event.domain && !map.has(event.domain)) map.set(event.domain, event);
    }
    return map;
  }, [data?.events]);

  function updateFilter(key: 'q' | 'status', value?: string) {
    const next = new URLSearchParams(searchParams);
    if (value) next.set(key, value);
    else next.delete(key);
    next.set('page', String(DEFAULT_PAGE));
    setSearchParams(next, { replace: key === 'q' });
  }

  function setCreateOpen(open: boolean) {
    const next = new URLSearchParams(searchParams);
    if (open) next.set('create', '1');
    else next.delete('create');
    setSearchParams(next, { replace: !open });
  }

  function updatePagination(nextPage: number, nextPageSize: number) {
    const next = new URLSearchParams(searchParams);
    next.set('page', String(nextPageSize === pageSize ? nextPage : DEFAULT_PAGE));
    next.set('pageSize', String(nextPageSize));
    setSearchParams(next);
  }

  async function runAction<T>(domain: Domain, action: string, operation: () => Promise<T>) {
    const key = `${domain.id}:${action}`;
    setActionLoading((current) => ({ ...current, [key]: true }));
    try {
      return await operation();
    } finally {
      setActionLoading((current) => ({ ...current, [key]: false }));
    }
  }

  async function createDomain(values: AddDomainPayload) {
    const key = 'new:create';
    setActionLoading((current) => ({ ...current, [key]: true }));
    try {
      const result = await createDomainWithSetup(values, api);
      setData((current) => current ? { ...current, domains: [result.domain, ...current.domains] } : current);
      setCreateOpen(false);
      if (result.setup === 'partial') message.warning(result.error ? `${copy.createdPartial}：${result.error}` : copy.createdPartial);
      else message.success(copy.created);
      navigate(`/domains/${result.domain.id}/dns?setup=${result.setup}`);
    } catch (reason) {
      message.error(reason instanceof Error ? reason.message : copy.createFailed);
      throw reason;
    } finally {
      setActionLoading((current) => ({ ...current, [key]: false }));
    }
  }

  async function checkDomain(domain: Domain) {
    try {
      const result = await runAction(domain, 'check', () => api.checkDomain(domain.id));
      replaceDomain(result.domain);
      message.success(copy.checked);
    } catch (reason) {
      message.error(reason instanceof Error ? reason.message : copy.actionFailed);
    }
  }

  async function applyDns(domain: Domain) {
    try {
      const result = await runAction(domain, 'dns', () => api.applyDns(domain.id));
      replaceDomain(result.domain);
      if (result.apply?.ok === false) message.warning(copy.dnsPartiallyApplied);
      else message.success(copy.dnsApplied);
    } catch (reason) {
      message.error(reason instanceof Error ? reason.message : copy.actionFailed);
    }
  }

  async function deleteDomain() {
    if (!deleteTarget || deleteConfirmation !== deleteTarget.domain) return;
    try {
      await runAction(deleteTarget, 'delete', () => api.deleteDomain(deleteTarget.id));
      setData((current) => current ? { ...current, domains: current.domains.filter((item) => item.id !== deleteTarget.id) } : current);
      setDeleteTarget(null);
      setDeleteConfirmation('');
      message.success(copy.deleted);
    } catch (reason) {
      message.error(reason instanceof Error ? reason.message : copy.actionFailed);
    }
  }

  async function sendTest() {
    if (!testTarget) return;
    let values: { to: string; subject: string; text: string };
    try {
      values = await testForm.validateFields();
    } catch {
      return;
    }
    try {
      await runAction(testTarget, 'test', () => api.sendTest(testTarget.id, values));
      setTestTarget(null);
      testForm.resetFields();
      message.success(copy.testQueued);
    } catch (reason) {
      message.error(reason instanceof Error ? reason.message : copy.actionFailed);
    }
  }

  function replaceDomain(domain: Domain) {
    setData((current) => current ? { ...current, domains: current.domains.map((item) => item.id === domain.id ? domain : item) } : current);
  }

  function openTest(domain: Domain) {
    setTestTarget(domain);
    testForm.setFieldsValue({
      to: '',
      subject: copy.testSubject(domain.domain),
      text: copy.testBody(domain.domain)
    });
  }

  function menuItems(domain: Domain): MenuProps['items'] {
    return [
      { key: 'check', icon: <ReloadOutlined />, label: copy.checkDns, onClick: () => void checkDomain(domain) },
      { key: 'apply', icon: <ThunderboltOutlined />, label: copy.autoDns, disabled: !domain.dnsCredentialId, onClick: () => void applyDns(domain) },
      { key: 'test', icon: <SendOutlined />, label: copy.sendTest, onClick: () => openTest(domain) },
      { key: 'edit', icon: <EditOutlined />, label: copy.edit, onClick: () => navigate(`/domains/${domain.id}/sending?edit=1`) },
      { type: 'divider' },
      { key: 'delete', icon: <DeleteOutlined />, danger: true, label: copy.delete, onClick: () => { setDeleteTarget(domain); setDeleteConfirmation(''); } }
    ];
  }

  if (loading && !data) {
    return <Space direction="vertical" size={20} className="full-width" aria-label={copy.loading}><Skeleton active title={{ width: '28%' }} paragraph={{ rows: 2 }} /><SectionCard><Skeleton active paragraph={{ rows: 9 }} /></SectionCard></Space>;
  }

  if (error && !data) {
    return <Result status="error" title={copy.loadFailed} subTitle={error} extra={<Button type="primary" onClick={() => void load()}>{copy.retry}</Button>} />;
  }

  if (!data) return null;

  const columns: ColumnsType<Domain> = [
    {
      title: copy.domain,
      dataIndex: 'domain',
      width: 220,
      render: (value: string, domain) => (
        <Button type="link" className="table-link" onClick={() => navigate(`/domains/${domain.id}/overview`)}>{value}</Button>
      )
    },
    {
      title: copy.capabilities,
      width: 220,
      render: (_, domain) => <CapabilitySummary domain={domain} copy={copy} />
    },
    {
      title: copy.authentication,
      width: 160,
      render: (_, domain) => <AuthenticationHealth domain={domain} copy={copy} />
    },
    {
      title: copy.dnsIntegration,
      width: 180,
      render: (_, domain) => domain.dnsCredentialId
        ? <StatusPill tone={credentialNames.has(domain.dnsCredentialId) ? 'info' : 'warning'}>{auxiliaryErrors.dns ? copy.auxUnavailable : credentialNames.get(domain.dnsCredentialId) || copy.credentialUnavailable}</StatusPill>
        : <StatusPill tone="neutral">{copy.manualDns}</StatusPill>
    },
    {
      title: copy.lastActivity,
      width: 190,
      render: (_, domain) => {
        if (auxiliaryErrors.activity) return <Typography.Text type="secondary">{copy.auxUnavailable}</Typography.Text>;
        const event = lastActivity.get(domain.domain);
        return event ? <Space direction="vertical" size={0}><Typography.Text>{new Date(event.createdAt).toLocaleString()}</Typography.Text><Typography.Text type="secondary">{event.subject || event.status}</Typography.Text></Space> : <Typography.Text type="secondary">{copy.noActivity}</Typography.Text>;
      }
    },
    {
      title: copy.actions,
      width: 132,
      fixed: 'right',
      render: (_, domain) => (
        <Space size={4}>
          <Tooltip title={copy.view}>
            <Button aria-label={`${copy.view} ${domain.domain}`} icon={<EyeOutlined />} onClick={() => navigate(`/domains/${domain.id}/overview`)} />
          </Tooltip>
          <Dropdown menu={{ items: menuItems(domain) }} trigger={['click']}>
            <Button aria-label={`${copy.moreActions} ${domain.domain}`} icon={<EllipsisOutlined />} loading={Object.entries(actionLoading).some(([key, value]) => key.startsWith(`${domain.id}:`) && value)} />
          </Dropdown>
        </Space>
      )
    }
  ];
  const pagination = {
    current: page,
    pageSize,
    total: filtered.length,
    showSizeChanger: true,
    pageSizeOptions: [10, 20, 50, 100],
    onChange: updatePagination,
    showTotal: (total: number) => copy.paginationTotal(total)
  };

  return (
    <Space direction="vertical" size={20} className="full-width">
      <PageHeader title={copy.title} subtitle={copy.subtitle} extra={<Button type="primary" style={{ minHeight: 44 }} onClick={() => setCreateOpen(true)}>{copy.addDomain}</Button>} />

      {error ? (
        <Alert
          type="error"
          showIcon
          message={copy.loadFailed}
          description={error}
          action={<Button icon={<ReloadOutlined aria-hidden />} loading={loading} onClick={() => void load()}>{copy.retry}</Button>}
        />
      ) : null}

      <SectionCard className="domains-toolbar-card">
        <div className="page-toolbar">
          <Space wrap>
            <Input
              allowClear
              aria-label={copy.search}
              prefix={<SearchOutlined />}
              placeholder={copy.searchPlaceholder}
              value={query}
              onChange={(event) => updateFilter('q', event.target.value)}
              className="toolbar-search"
              style={{ minHeight: 44 }}
            />
            <Select
              allowClear
              aria-label={copy.statusFilter}
              placeholder={copy.statusFilter}
              value={status}
              onChange={(value) => updateFilter('status', value)}
              options={[
                { value: 'success', label: copy.healthy },
                { value: 'warning', label: copy.pending },
                { value: 'error', label: copy.needsAction }
              ]}
              className="toolbar-select"
              style={{ minHeight: 44 }}
            />
          </Space>
          <Typography.Text type="secondary">{copy.resultCount(filtered.length, data.domains.length)}</Typography.Text>
        </div>
      </SectionCard>

      {auxiliaryErrors.dns || auxiliaryErrors.relays || auxiliaryErrors.activity ? (
        <Alert
          type="warning"
          showIcon
          message={copy.partialLoad}
          description={[auxiliaryErrors.dns && `${copy.dnsIntegration}: ${auxiliaryErrors.dns}`, auxiliaryErrors.relays && `SMTP: ${auxiliaryErrors.relays}`, auxiliaryErrors.activity && `${copy.lastActivity}: ${auxiliaryErrors.activity}`].filter(Boolean).join('；')}
          action={<Button icon={<ReloadOutlined aria-hidden />} onClick={() => void load()}>{copy.retry}</Button>}
        />
      ) : null}

      {filtered.length ? screens.md ? (
        <SectionCard>
          <Table rowKey="id" columns={columns} dataSource={pagedDomains} pagination={pagination} scroll={{ x: 1120 }} />
        </SectionCard>
      ) : (
        <Space direction="vertical" size={16} className="full-width">
          <List
            dataSource={pagedDomains}
            renderItem={(domain) => (
              <List.Item>
                <DomainCard domain={domain} credentialName={domain.dnsCredentialId ? credentialNames.get(domain.dnsCredentialId) : undefined} event={lastActivity.get(domain.domain)} auxiliaryErrors={auxiliaryErrors} menuItems={menuItems(domain)} onView={() => navigate(`/domains/${domain.id}/overview`)} copy={copy} />
              </List.Item>
            )}
          />
          <Pagination {...pagination} responsive />
        </Space>
      ) : (
        <SectionCard><EmptyState description={query || status ? copy.noMatches : copy.noDomains} action={!data.domains.length ? <Button onClick={() => setCreateOpen(true)}>{copy.addFirstDomain}</Button> : undefined} /></SectionCard>
      )}

      <AddDomainDrawer
        open={addOpen}
        loading={Boolean(actionLoading['new:create'])}
        config={config}
        dnsCredentials={data.dnsCredentials}
        smtpRelays={data.smtpRelays}
        onClose={() => setCreateOpen(false)}
        onSubmit={createDomain}
      />

      <Modal
        title={copy.deleteTitle}
        open={Boolean(deleteTarget)}
        okText={copy.delete}
        okButtonProps={{ danger: true, disabled: !deleteTarget || deleteConfirmation !== deleteTarget.domain, loading: Boolean(deleteTarget && actionLoading[`${deleteTarget.id}:delete`]) }}
        cancelText={copy.cancel}
        onCancel={() => { setDeleteTarget(null); setDeleteConfirmation(''); }}
        onOk={() => void deleteDomain()}
      >
        <Space direction="vertical" size={16} className="full-width">
          <Typography.Paragraph>{copy.deleteWarning}</Typography.Paragraph>
          <Typography.Text>{copy.typeDomain} <Typography.Text code>{deleteTarget?.domain}</Typography.Text></Typography.Text>
          <Input autoFocus value={deleteConfirmation} onChange={(event) => setDeleteConfirmation(event.target.value)} aria-label={copy.deleteConfirmation} style={{ minHeight: 44 }} />
        </Space>
      </Modal>

      <Modal
        title={testTarget ? copy.testTitle(testTarget.domain) : copy.sendTest}
        open={Boolean(testTarget)}
        okText={copy.queueTest}
        cancelText={copy.cancel}
        confirmLoading={Boolean(testTarget && actionLoading[`${testTarget.id}:test`])}
        onCancel={() => { setTestTarget(null); testForm.resetFields(); }}
        onOk={() => void sendTest()}
      >
        <Form form={testForm} layout="vertical">
          <Form.Item name="to" label={copy.recipient} rules={[{ required: true, type: 'email', message: copy.validRecipient }]}><Input placeholder="you@example.com" style={{ minHeight: 44 }} /></Form.Item>
          <Form.Item name="subject" label={copy.subject} rules={[{ required: true }]}><Input style={{ minHeight: 44 }} /></Form.Item>
          <Form.Item name="text" label={copy.body} rules={[{ required: true }]}><Input.TextArea rows={5} /></Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}

function AuthenticationHealth({ domain, copy }: { domain: Domain; copy: typeof zhCopy }) {
  const records = domain.status?.records || [];
  const keys = ['spf', 'dkim', 'dmarc'];
  const passed = keys.filter((key) => {
    const record = records.find((item) => item.key === key);
    return record && getRecordStatusMeta(record).key === 'success';
  }).length;
  const tone = passed === 3 ? 'success' : passed ? 'warning' : 'error';
  return (
    <Tooltip title={keys.map((key) => `${key.toUpperCase()}: ${recordState(records.find((item) => item.key === key), copy)}`).join('\n')}>
      <span><StatusPill tone={tone}>{passed}/3 {passed === 3 ? copy.passed : copy.incomplete}</StatusPill></span>
    </Tooltip>
  );
}

function CapabilitySummary({ domain, copy }: { domain: Domain; copy: typeof zhCopy }) {
  return (
    <Space direction="vertical" size={4}>
      <StatusPill tone={domain.status?.verified ? 'success' : 'warning'}><SendOutlined /> {domain.status?.verified ? copy.sendReady : copy.sendPending}</StatusPill>
      <StatusPill tone={domain.catchAllAddress ? 'info' : 'neutral'}><MailOutlined /> {domain.catchAllAddress ? copy.receiveRouted : copy.receiveConfigurable}</StatusPill>
    </Space>
  );
}

function DomainCard({ domain, credentialName, event, auxiliaryErrors, menuItems, onView, copy }: { domain: Domain; credentialName?: string; event?: SendEvent; auxiliaryErrors: { dns: string; relays: string; activity: string }; menuItems: MenuProps['items']; onView: () => void; copy: typeof zhCopy }) {
  return (
    <Card
      style={{ width: '100%' }}
      title={<Space><GlobalOutlined /><Typography.Text strong>{domain.domain}</Typography.Text></Space>}
      extra={<Dropdown menu={{ items: menuItems }} trigger={['click']}><Button aria-label={`${copy.moreActions} ${domain.domain}`} icon={<EllipsisOutlined />} /></Dropdown>}
      actions={[<Button key="view" type="link" icon={<EyeOutlined />} onClick={onView}>{copy.view}</Button>]}
    >
      <Space direction="vertical" size={12} className="full-width">
        <CapabilitySummary domain={domain} copy={copy} />
        <Space wrap><Typography.Text type="secondary">{copy.authentication}</Typography.Text><AuthenticationHealth domain={domain} copy={copy} /></Space>
        <Space wrap><Typography.Text type="secondary">{copy.dnsIntegration}</Typography.Text><StatusPill tone={credentialName ? 'info' : domain.dnsCredentialId && auxiliaryErrors.dns ? 'warning' : 'neutral'}>{domain.dnsCredentialId && auxiliaryErrors.dns ? copy.auxUnavailable : credentialName || copy.manualDns}</StatusPill></Space>
        <Typography.Text type="secondary">{copy.lastActivity}: {auxiliaryErrors.activity ? copy.auxUnavailable : event ? new Date(event.createdAt).toLocaleString() : copy.noActivity}</Typography.Text>
      </Space>
    </Card>
  );
}

function firstDnsApplyError(apply: NonNullable<Domain['status']['apply']>) {
  return apply.results?.find((result) => !result.ok && result.error)?.error;
}

function errorText(reason: unknown, fallback: string) {
  return reason instanceof Error ? reason.message : fallback;
}

function positiveInteger(value: string | null, fallback: number) {
  const parsed = Number(value);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}

function recordState(record: DnsRecord | undefined, copy: typeof zhCopy) {
  if (!record) return copy.missing;
  const state = getRecordStatusMeta(record).key;
  if (state === 'success') return copy.passed;
  if (state === 'pending') return copy.pending;
  return copy.needsAction;
}

const zhCopy = {
  title: '发信域名', subtitle: '统一管理域名认证、发送能力和最近投递状态。', loading: '正在加载域名', loadFailed: '域名列表加载失败', retry: '重试', partialLoad: '部分辅助信息暂不可用', auxUnavailable: '暂不可用', domain: '域名', capabilities: '发送 / 接收能力', authentication: '认证健康度', dnsIntegration: 'DNS 集成', lastActivity: '最近活动', actions: '操作', view: '查看', moreActions: '更多操作',
  addDomain: '添加域名', addFirstDomain: '添加第一个域名', search: '搜索域名', searchPlaceholder: '搜索域名或发信主机', statusFilter: '认证状态', healthy: '健康', pending: '等待生效', needsAction: '需要处理', noMatches: '没有符合当前条件的域名', noDomains: '还没有发信域名', resultCount: (filtered: number, total: number) => `${filtered} / ${total} 个域名`,
  checkDns: '检查 DNS', autoDns: '自动写入 DNS', sendTest: '测试发送', edit: '编辑配置', delete: '删除域名', manualDns: '手动配置', credentialUnavailable: '凭据不可用', noActivity: '尚无发送活动', passed: '已通过', incomplete: '未完整', missing: '未配置', sendReady: '发送可用', sendPending: '发送待验证', receiveRouted: '接收已路由', receiveConfigurable: '接收可配置',
  created: '域名已创建，后续 DNS 操作已完成', createdPartial: '域名已创建，但后续 DNS 操作未完全成功，请在详情页继续处理', createFailed: '创建域名失败', checked: 'DNS 检查已完成', dnsApplied: 'DNS 记录写入已完成', dnsPartiallyApplied: '部分 DNS 记录写入失败，请查看详情', deleted: '域名已删除', testQueued: '测试邮件已加入队列', actionFailed: '操作失败', paginationTotal: (total: number) => `共 ${total} 个域名`,
  deleteTitle: '删除域名', deleteWarning: '删除后，该域名的发送配置将立即不可用。此操作不可撤销。', typeDomain: '请输入域名以确认：', deleteConfirmation: '域名删除确认', cancel: '取消', testTitle: (domain: string) => `通过 ${domain} 测试发送`, queueTest: '加入发送队列', recipient: '收件人', validRecipient: '请输入有效的收件邮箱', subject: '主题', body: '正文', testSubject: (domain: string) => `MailHub ${domain} 测试邮件`, testBody: (domain: string) => `这是一封来自 ${domain} 的 MailHub 投递测试邮件。`
};

const enCopy: typeof zhCopy = {
  title: 'Sending domains', subtitle: 'Manage authentication, sending capability, and recent delivery health.', loading: 'Loading domains', loadFailed: 'Unable to load domains', retry: 'Retry', partialLoad: 'Some supporting data is temporarily unavailable', auxUnavailable: 'Unavailable', domain: 'Domain', capabilities: 'Send / receive', authentication: 'Authentication', dnsIntegration: 'DNS integration', lastActivity: 'Last activity', actions: 'Actions', view: 'View', moreActions: 'More actions',
  addDomain: 'Add domain', addFirstDomain: 'Add your first domain', search: 'Search domains', searchPlaceholder: 'Search domain or sending host', statusFilter: 'Authentication status', healthy: 'Healthy', pending: 'Pending', needsAction: 'Needs action', noMatches: 'No domains match these filters', noDomains: 'No sending domains yet', resultCount: (filtered: number, total: number) => `${filtered} of ${total} domains`,
  checkDns: 'Check DNS', autoDns: 'Apply DNS automatically', sendTest: 'Send test', edit: 'Edit configuration', delete: 'Delete domain', manualDns: 'Manual', credentialUnavailable: 'Credential unavailable', noActivity: 'No activity yet', passed: 'passed', incomplete: 'incomplete', missing: 'Missing', sendReady: 'Sending ready', sendPending: 'Sending pending', receiveRouted: 'Receiving routed', receiveConfigurable: 'Receiving available',
  created: 'Domain created and DNS follow-up completed', createdPartial: 'Domain created, but the DNS follow-up needs attention', createFailed: 'Unable to create domain', checked: 'DNS check completed', dnsApplied: 'DNS records applied', dnsPartiallyApplied: 'Some DNS records could not be applied', deleted: 'Domain deleted', testQueued: 'Test email queued', actionFailed: 'Action failed', paginationTotal: (total: number) => `${total} domains`,
  deleteTitle: 'Delete domain', deleteWarning: 'Sending configuration for this domain will stop working immediately. This cannot be undone.', typeDomain: 'Type the domain to confirm:', deleteConfirmation: 'Domain deletion confirmation', cancel: 'Cancel', testTitle: (domain: string) => `Test sending from ${domain}`, queueTest: 'Queue test', recipient: 'Recipient', validRecipient: 'Enter a valid recipient email', subject: 'Subject', body: 'Body', testSubject: (domain: string) => `MailHub ${domain} test email`, testBody: (domain: string) => `This is a MailHub delivery test from ${domain}.`
};
