const STORAGE_KEY = 'huamed-mvp-leads-v1';
const WEBHOOK_KEY = 'huamed-mvp-webhook';
const DOCTOR_STORAGE_KEY = 'huamed-mvp-doctors-v1';
const AUTH_STORAGE_KEY = 'huamed-mvp-client-session-v1';
const CLIENT_LANG_KEY = 'huamed-client-lang-v2';
const LEGAL_CONSENT_VERSION = '2026-05-11-stage10';
const PORTAL = window.HUAMED_PORTAL || (window.location.pathname.includes('ops') ? 'ops' : window.location.pathname.includes('doctor') ? 'doctor' : 'client');
const CLIENT_PAGE = window.HUAMED_CLIENT_PAGE || 'home';
const API_BASE = '';
const DEFAULT_CLIENT_CONFIG = {
  googleConfigured: false,
  whatsappConfigured: false,
  whatsappNumber: '',
  legalConsentVersion: LEGAL_CONSENT_VERSION
};
const CLIENT_PAGE_PATHS = {
  home: 'index.html',
  team: 'team.html',
  hospitals: 'hospitals.html',
  system: 'system.html',
  medical: 'cross-border-medical.html',
  frontier: 'frontier-medicine.html',
  knowledge: 'knowledge.html',
  intake: 'intake.html',
  'service-plan': 'service-plan.html',
  process: 'process.html',
  privacy: 'privacy.html',
  terms: 'terms.html'
};
const OPS_STATUSES = ['New', 'Triage', 'Records Pending', 'Case Packaging', 'Doctor Review', 'Pathway Consult', 'Paid', 'China Visit Interest', 'Rejected', 'Closed'];
const SOURCE_OPTIONS = ['Website intake', 'WhatsApp referral', 'Partner clinic', 'Community event', 'Returning family', 'Manual entry'];
const REJECTION_REASONS = ['', 'Emergency / acute', 'Out of scope', 'Records unavailable', 'No paid intent', 'Local care first', 'Unable to contact', 'Other'];
const MAX_ATTACHMENT_COUNT = 10;
const MAX_ATTACHMENT_BYTES = 200 * 1024 * 1024;
const COUNTRY_DIAL_CODES = {
  Malaysia: '60',
  Singapore: '65',
  Indonesia: '62',
  Thailand: '66',
  Philippines: '63',
  Vietnam: '84',
  Brunei: '673',
  Cambodia: '855',
  China: '86',
  'Hong Kong': '852',
  Macau: '853'
};

const apiJson = async (path, options = {}) => {
  const response = await fetch(`${API_BASE}${path}`, {
    credentials: 'include',
    headers: { 'content-type': 'application/json', ...(options.headers || {}) },
    ...options
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(data.error || `Request failed: ${response.status}`);
    error.status = response.status;
    error.data = data;
    throw error;
  }
  return data;
};

const loadStoredClientSession = () => {
  try {
    const session = JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY) || 'null');
    return session?.role === 'client' ? session : { role: 'guest', user: null };
  } catch {
    return { role: 'guest', user: null };
  }
};

const createLocalClientSession = (lang = 'zh') => ({
  role: 'client',
  user: {
    id: 'local-client',
    googleId: 'mock-client',
    email: 'client@huamed.local',
    name: lang === 'zh' ? '华医畅客户' : 'HuaMed Client',
    avatar: '',
    provider: 'local-mock'
  }
});

const isStaticPreviewApiError = (err) => [404, 405, 501].includes(err?.status);

const validateContactForCountry = (contact, country) => {
  const digits = String(contact || '').replace(/\D/g, '');
  const raw = String(contact || '').trim();
  const code = COUNTRY_DIAL_CODES[country];
  if (!raw) return false;
  if (code) return digits.startsWith(code) && digits.length >= code.length + 6;
  return raw.includes('+') && digits.length >= 8;
};

const contactHintForCountry = (country, lang) => {
  const code = COUNTRY_DIAL_CODES[country];
  if (code) {
    return lang === 'zh'
      ? `请输入带国家/地区区号的 WhatsApp 手机号，例如 +${code} ...`
      : `Enter a WhatsApp number with country/region code, e.g. +${code} ...`;
  }
  return lang === 'zh' ? '请输入带国际区号的 WhatsApp 手机号，例如 +86 ...' : 'Enter a WhatsApp number with international code, e.g. +86 ...';
};

const dialPrefixForCountry = (country) => COUNTRY_DIAL_CODES[country] ? `+${COUNTRY_DIAL_CODES[country]} ` : '+';

const shouldReplaceDialPrefix = (contact = '') => {
  const value = String(contact).trim();
  if (!value) return true;
  return Object.values(COUNTRY_DIAL_CODES).some((code) => value === `+${code}` || value === `+${code} `);
};

const clientDisplayName = (user = {}, lang = 'zh') => {
  const name = String(user.name || '').trim();
  if (!name || ['华医畅客户', 'HuaMed Client'].includes(name)) return lang === 'zh' ? '华医畅客户' : 'HuaMed Client';
  return name;
};

const STATUS_LABELS = {
  New: { zh: '新线索', en: 'New' },
  Triage: { zh: '初步判断', en: 'Triage' },
  'Records Pending': { zh: '待补资料', en: 'Records Pending' },
  'Case Packaging': { zh: '病例包整理', en: 'Case Packaging' },
  'Doctor Review': { zh: '医生预评估', en: 'Doctor Review' },
  'Pathway Consult': { zh: '路径咨询', en: 'Pathway Consult' },
  Paid: { zh: '已付费', en: 'Paid' },
  'China Visit Interest': { zh: '有来华意向', en: 'China Visit Interest' },
  Rejected: { zh: '不承接', en: 'Rejected' },
  Closed: { zh: '已关闭', en: 'Closed' }
};

const RECORD_LABELS = {
  complete: { zh: '资料较完整', en: 'Mostly complete' },
  partial: { zh: '部分资料', en: 'Partial records' },
  none: { zh: '暂无资料', en: 'No records' }
};

const INTENT_LABELS = {
  yes: { zh: '是', en: 'Yes' },
  maybe: { zh: '考虑中', en: 'Maybe' },
  no: { zh: '暂不考虑', en: 'No' }
};

const NEXT_ACTION_LABELS = {
  'Local emergency first': { zh: '当地急诊优先', en: 'Local emergency first' },
  'Collect records': { zh: '先补齐资料', en: 'Collect records' },
  'Pathway consult': { zh: '路径咨询', en: 'Pathway consult' },
  'Specialist review': { zh: '中国专家二诊预评估', en: 'Specialist review' },
  'Free triage': { zh: '免费初步判断', en: 'Free triage' }
};

const labelOf = (labels, value, lang) => labels[value]?.[lang] || value || '-';

const emptyForm = {
  name: '',
  country: 'Malaysia',
  city: '',
  language: 'English',
  contact: '',
  serviceScene: 'medical',
  conditionId: 'lung',
  hasRecords: 'partial',
  doctorAdvice: '',
  timeframe: '1-3 months',
  considersChina: 'maybe',
  acceptsPaid: 'maybe',
  attachmentSummary: [],
  notes: ''
};

const getCondition = (id) => CONDITIONS.find((item) => item.id === id) || ({
  checkup: {
    id: 'checkup',
    icon: 'heart-pulse',
    priority: 'A',
    tone: 'sea',
    name: { zh: '高端体检服务', en: 'Premium checkup service' },
    short: { zh: '希望在中国顶级医院或高端体检中心完成系统体检。', en: 'Seeking a structured checkup in top hospitals or premium centers in China.' },
    docs: [{ zh: '既往体检报告', en: 'Prior checkup reports' }, { zh: '基础病和用药清单', en: 'Comorbidities and medication list' }, { zh: '关注项目', en: 'Checkup priorities' }],
    next: { zh: '先由服务团队确认城市、医院类型和体检项目范围。', en: 'The service team first confirms city, hospital type, and checkup scope.' }
  },
  frontier: {
    id: 'frontier',
    icon: 'flask-conical',
    priority: 'B',
    tone: 'marble',
    name: { zh: '前沿医学服务', en: 'Frontier medicine service' },
    short: { zh: '关注合规创新药械、研究型成果和前沿诊疗方向。', en: 'Interested in regulated innovation programs and research-led care directions.' },
    docs: [{ zh: '诊断和治疗史', en: 'Diagnosis and treatment history' }, { zh: '基因 / 病理资料，如有', en: 'Genomic / pathology records if available' }, { zh: '本地医生建议', en: 'Local doctor recommendation' }],
    next: { zh: '先判断适应证、资料完整度和风险边界。', en: 'Start by reviewing eligibility, record readiness, and risk boundaries.' }
  }
})[id] || {
  id: 'other',
  icon: 'circle-help',
  priority: 'B',
  tone: 'marble',
  name: { zh: '其他问题', en: 'Other concern' },
  short: { zh: '需要先由华医畅人工判断是否适合承接。', en: 'Needs manual review to decide whether HuaMed can support it.' },
  docs: [
    { zh: '现有报告', en: 'Available reports' },
    { zh: '影像或病理，如有', en: 'Imaging or pathology if available' },
    { zh: '本地医生建议', en: 'Local doctor recommendation' }
  ],
  next: { zh: '先提交基础情况，人工判断是否适合。', en: 'Submit the basic case first for manual fit review.' }
};
const getFocusConditions = () => FOCUS_CONDITION_IDS.map(getCondition);
const getSupportConditions = () => SUPPORT_CONDITION_IDS.map(getCondition);
const getConditionGroupLabel = (condition, lang) => FOCUS_CONDITION_IDS.includes(condition.id)
  ? (lang === 'zh' ? '首期重点' : 'Focus')
  : (lang === 'zh' ? '也可初步评估' : 'Screening');

const SERVICE_SCENES = [
  {
    id: 'medical',
    icon: 'stethoscope',
    tone: 'gold',
    name: { zh: '中国专家二诊与来华就医服务', en: 'China specialist second opinion and care coordination' },
    short: {
      zh: '面向已有明确症状、检查异常或复杂诊疗需求的海外用户，先通过病例整理和中国专家二诊判断是否需要来华，再协助推进医院、专家、检查和就医路径。',
      en: 'For overseas users with symptoms, abnormal findings, or complex care needs: organize records and obtain China-side specialist input first, then coordinate hospitals, specialist direction, tests, and care pathways when China travel fits.'
    },
    cta: { zh: '了解来华就医服务', en: 'Learn about China care services' },
    href: 'cross-border-medical.html',
    highlights: {
      zh: ['肺结节 / 早期肺癌', '甲状腺、乳腺、消化道早癌', '心血管、骨科、妇科等择期方向'],
      en: ['Lung nodules / early lung cancer', 'Thyroid, breast, and GI early cancer', 'Elective cardiovascular, orthopedic, and gynecology directions']
    }
  },
  {
    id: 'checkup',
    icon: 'heart-pulse',
    tone: 'sea',
    name: { zh: '中国三甲医院高端体检服务', en: 'Premium checkups in China tertiary hospitals' },
    short: {
      zh: '面向希望在北京、上海等城市完成高质量体检的海外用户，协助理解三甲医院国际医疗部、特需门诊和体检中心服务路径。',
      en: 'For overseas users seeking high-quality checkups in Beijing, Shanghai, and other major cities, with support understanding international departments, VIP clinics, and checkup center pathways.'
    },
    cta: { zh: '了解体检服务', en: 'Learn about checkup services' },
    href: 'intake.html?scene=checkup',
    highlights: {
      zh: ['高端筛查与深度体检', '报告解读和复查建议', '后续异常结果路径衔接'],
      en: ['Premium screening and comprehensive checkups', 'Report interpretation and follow-up direction', 'Pathway support if abnormal findings appear']
    }
  },
  {
    id: 'frontier',
    icon: 'flask-conical',
    tone: 'marble',
    name: { zh: '前沿医学咨询', en: 'Frontier medicine consultation' },
    short: {
      zh: '面向关注合规创新药械、研究型医学成果和先行项目的用户，帮助理解适用条件、资料要求和沟通边界。该内容放入二级页面，不在首页展开。',
      en: 'For users interested in regulated innovative drugs or devices, research-led medical advances, and pilot programs; helps clarify eligibility, record needs, and communication boundaries on a dedicated page.'
    },
    cta: { zh: '查看前沿医学咨询', en: 'View frontier medicine consultation' },
    href: 'frontier-medicine.html',
    highlights: {
      zh: ['乐城等合规创新方向', '研究成果展示', '适应证与风险边界预评估'],
      en: ['Regulated innovation pathways such as Lecheng', 'Research outcome showcases', 'Eligibility and boundary pre-review']
    }
  }
];

const getServiceScene = (id) => SERVICE_SCENES.find((item) => item.id === id) || SERVICE_SCENES[0];

const whatsappUrlFromConfig = (config = {}, lead) => {
  const number = String(config.whatsappNumber || '').replace(/\D/g, '');
  if (!number) return '';
  const name = lead?.name ? ` ${lead.name}` : '';
  const condition = lead?.conditionId ? getCondition(lead.conditionId).name.zh : '';
  const text = lead
    ? `你好，华医畅团队。我${name}已在官网提交咨询资料${condition ? `，咨询方向：${condition}` : ''}，想继续了解下一步服务安排。`
    : '你好，华医畅团队。我想了解中国专家二诊和来华就医服务，想先和人工客服沟通。';
  return `https://wa.me/${number}?text=${encodeURIComponent(text)}`;
};

const leadMatchesClient = (lead, user = {}, form = {}) => {
  const safeUser = user || {};
  const contact = String(form.contact || safeUser.whatsapp || safeUser.phone || '').trim();
  if (contact && String(lead.contact || '').trim() === contact) return true;
  if (safeUser.email && lead.email && safeUser.email === lead.email) return true;
  if (form.name && lead.name && form.name === lead.name) return true;
  return false;
};

const makeLeadId = () => {
  const stamp = new Date().toISOString().slice(2, 10).replaceAll('-', '');
  const suffix = Math.floor(100 + Math.random() * 900);
  return `HMD-${stamp}-${suffix}`;
};

const scoreLead = (form) => {
  if (form.timeframe === 'Emergency / acute') {
    return { score: 25, tier: 'Urgent local care', nextAction: 'Local emergency first' };
  }

  const condition = getCondition(form.conditionId);
  let score = 30;
  score += condition.priority === 'S' ? 18 : condition.priority === 'A' ? 12 : 8;
  score += form.hasRecords === 'complete' ? 24 : form.hasRecords === 'partial' ? 12 : 0;
  score += form.acceptsPaid === 'yes' ? 16 : form.acceptsPaid === 'maybe' ? 7 : -4;
  score += form.considersChina === 'yes' ? 12 : form.considersChina === 'maybe' ? 6 : 0;
  score += form.timeframe === 'Within 1 month' ? 10 : form.timeframe === '1-3 months' ? 8 : 3;
  score = Math.max(0, Math.min(100, score));

  let tier = 'Low';
  let nextAction = 'Free triage';
  if (form.hasRecords === 'none') {
    tier = 'Record gap';
    nextAction = 'Collect records';
  } else if (score >= 80) {
    tier = 'High';
    nextAction = 'Specialist review';
  } else if (score >= 58) {
    tier = 'Medium';
    nextAction = 'Pathway consult';
  }

  return { score, tier, nextAction };
};

const normalizeNextAction = (action) => {
  if (action === 'Second opinion') return 'Specialist review';
  return action || 'Free triage';
};

const emptyDoctorFeedback = {
  status: 'Not started',
  reviewerName: '',
  reviewedAt: '',
  pathwayFit: 'Needs ops follow-up',
  urgency: 'Routine',
  recordGaps: '',
  assessment: '',
  recommendations: '',
  chinaVisitFit: 'To be assessed',
  doctorNote: ''
};

const DOCTOR_FEEDBACK_STATUS_LABELS = {
  'Not started': { zh: '未反馈', en: 'Not started' },
  Draft: { zh: '草稿', en: 'Draft' },
  Submitted: { zh: '已提交', en: 'Submitted' }
};

const PATHWAY_FIT_OPTIONS = ['Suitable for specialist review', 'Needs more records', 'Local care first', 'Out of scope', 'Needs ops follow-up'];
const URGENCY_OPTIONS = ['Routine', 'Soon', 'Urgent local care'];
const CHINA_VISIT_FIT_OPTIONS = ['Likely suitable', 'Possible after records', 'Local care first', 'Not suitable now', 'To be assessed'];
const DOCTOR_FEEDBACK_VALUE_LABELS = {
  'Suitable for specialist review': { zh: '适合继续专家二诊评估', en: 'Suitable for specialist review' },
  'Needs more records': { zh: '需先补充资料', en: 'Needs more records' },
  'Local care first': { zh: '建议本地治疗优先', en: 'Local care first' },
  'Out of scope': { zh: '暂不适合承接', en: 'Out of scope' },
  'Needs ops follow-up': { zh: '需运营继续跟进', en: 'Needs ops follow-up' },
  Routine: { zh: '常规择期', en: 'Routine' },
  Soon: { zh: '建议尽快安排', en: 'Soon' },
  'Urgent local care': { zh: '当地急诊优先', en: 'Urgent local care' },
  'Likely suitable': { zh: '较适合来华进一步评估', en: 'Likely suitable' },
  'Possible after records': { zh: '补齐资料后再判断', en: 'Possible after records' },
  'Not suitable now': { zh: '当前不适合来华', en: 'Not suitable now' },
  'To be assessed': { zh: '待评估', en: 'To be assessed' }
};

const feedbackLabel = (value, lang) => DOCTOR_FEEDBACK_VALUE_LABELS[value]?.[lang] || value || '-';

const normalizeDoctorFeedback = (feedback) => ({
  ...emptyDoctorFeedback,
  ...(feedback || {}),
  status: ['Not started', 'Draft', 'Submitted'].includes(feedback?.status) ? feedback.status : 'Not started'
});

const hasSubmittedDoctorFeedback = (lead) => lead.doctorFeedback?.status === 'Submitted';

const buildClientPathwaySummary = (lead, lang = 'zh') => {
  const feedback = normalizeDoctorFeedback(lead.doctorFeedback);
  if (!hasSubmittedDoctorFeedback({ doctorFeedback: feedback })) return lead.clientPathwaySummary || '';
  if (lang === 'zh') {
    return [
      `医生预评估结论：${feedbackLabel(feedback.pathwayFit, lang)}`,
      feedback.assessment ? `核心判断：${feedback.assessment}` : '',
      feedback.recommendations ? `建议下一步：${feedback.recommendations}` : '',
      feedback.recordGaps ? `仍需补充资料：${feedback.recordGaps}` : '',
      `来华评估适配度：${feedbackLabel(feedback.chinaVisitFit, lang)}`,
      '以上为基于现有资料的路径预评估，不替代线下面诊或正式诊疗结论。'
    ].filter(Boolean).join('\n');
  }
  return [
    `Doctor pre-assessment: ${feedback.pathwayFit}`,
    feedback.assessment ? `Key assessment: ${feedback.assessment}` : '',
    feedback.recommendations ? `Suggested next step: ${feedback.recommendations}` : '',
    feedback.recordGaps ? `Record gaps: ${feedback.recordGaps}` : '',
    `China visit fit: ${feedback.chinaVisitFit}`,
    'This is a pathway pre-assessment based on available records, not a diagnosis or treatment decision.'
  ].filter(Boolean).join('\n');
};

const defaultCaseSummary = (lead) => {
  const condition = getCondition(lead.conditionId);
  const attachments = (lead.attachmentSummary || []).map((item) => item.name).filter(Boolean);
  return [
    `${lead.name || 'Client'} · ${condition.name.zh}`,
    lead.doctorAdvice ? `本地医生建议：${lead.doctorAdvice}` : '',
    lead.notes ? `家庭主要问题：${lead.notes}` : '',
    attachments.length ? `客户上传附件：${attachments.join('、')}` : '',
    `资料状态：${lead.hasRecords}`
  ].filter(Boolean).join('\n');
};

const normalizeLead = (lead) => ({
  source: 'Website intake',
  considersChina: 'maybe',
  acceptsPaid: 'maybe',
  doctorAdvice: '',
  rejectionReason: '',
  recordChecklist: {},
  matchedDoctorId: '',
  casePackageNote: '',
  attachmentSummary: [],
  clientPathwaySummary: '',
  owner: 'Ops',
  ...lead,
  attachmentSummary: Array.isArray(lead.attachmentSummary) ? lead.attachmentSummary : [],
  status: OPS_STATUSES.includes(lead.status) ? lead.status : 'New',
  nextAction: normalizeNextAction(lead.nextAction),
  caseSummary: lead.caseSummary || defaultCaseSummary(lead),
  doctorFeedback: normalizeDoctorFeedback(lead.doctorFeedback)
});

const createLocalDemoLead = (form) => {
  const assessment = scoreLead(form);
  return normalizeLead({
    ...form,
    id: makeLeadId(),
    createdAt: new Date().toISOString(),
    source: 'Website intake',
    status: 'New',
    recordReadiness: form.hasRecords,
    score: assessment.score,
    tier: assessment.tier,
    nextAction: assessment.nextAction,
    rejectionReason: '',
    matchedDoctorId: '',
    owner: 'Ops'
  });
};

const recordKey = (doc) => textOf(doc, 'en') || textOf(doc, 'zh');

const defaultRecordReady = (lead, index, total) => {
  if (lead.hasRecords === 'complete') return true;
  if (lead.hasRecords === 'none') return false;
  return index < Math.max(1, Math.ceil(total / 2));
};

const getRecordItems = (lead, lang) => {
  const docs = getCondition(lead.conditionId).docs || [];
  return docs.map((doc, index) => {
    const key = recordKey(doc);
    return {
      key,
      label: textOf(doc, lang),
      ready: lead.recordChecklist?.[key] ?? defaultRecordReady(lead, index, docs.length)
    };
  });
};

const getRecordReadiness = (lead) => {
  const items = getRecordItems(lead, 'zh');
  const ready = items.filter((item) => item.ready).length;
  return {
    ready,
    total: items.length,
    pct: items.length ? Math.round((ready / items.length) * 100) : 0
  };
};

const getCaseFlowStage = (lead) => {
  if (['Rejected', 'Closed'].includes(lead.status)) return 'Closed';
  if (lead.status === 'Doctor Review') return 'Doctor Review';
  if (lead.matchedDoctorId) return 'Doctor Review';
  if (lead.status === 'Case Packaging') return 'Case Packaging';
  if (getRecordReadiness(lead).pct < 100 || lead.status === 'Records Pending') return 'Records Pending';
  return 'Case Packaging';
};

const toLocalArray = (value) => {
  if (Array.isArray(value)) return value;
  if (!value) return [];
  return String(value).split(/\n|、|,/).map((item) => item.trim()).filter(Boolean);
};

const normalizeLangList = (value) => ({
  zh: toLocalArray(value?.zh || value),
  en: toLocalArray(value?.en || value?.zh || value)
});

const normalizeDoctorProfile = (profile) => ({
  id: profile.id || `doc-${Date.now()}-${Math.floor(100 + Math.random() * 900)}`,
  isPublished: profile.isPublished ?? false,
  accountStatus: profile.accountStatus || 'Ops managed',
  createdAt: profile.createdAt || localNow(),
  status: profile.status || { zh: profile.isPublished ? '上架展示' : '内部草稿', en: profile.isPublished ? 'Published' : 'Draft' },
  source: profile.source || { zh: '运营录入', en: 'Entered by ops' },
  name: profile.name || { zh: '', en: '' },
  displayName: profile.displayName || profile.name || { zh: '', en: '' },
  hospital: profile.hospital || { zh: '', en: '' },
  department: profile.department || { zh: '', en: '' },
  title: profile.title || { zh: '', en: '' },
  location: profile.location || { zh: '中国', en: 'China' },
  languages: normalizeLangList(profile.languages || { zh: ['中文'], en: ['Chinese'] }),
  focus: normalizeLangList(profile.focus),
  suitableCases: normalizeLangList(profile.suitableCases),
  caseRequirements: normalizeLangList(profile.caseRequirements),
  reviewScope: normalizeLangList(profile.reviewScope),
  notAccepted: normalizeLangList(profile.notAccepted),
  accountAccess: normalizeLangList(profile.accountAccess || {
    zh: ['查看运营整理后的匿名病例包', '填写二诊预评估反馈', '不直接获取客户联系方式'],
    en: ['View ops-prepared anonymized case packages', 'Submit pre-assessment feedback', 'No direct access to client contact details']
  }),
  availability: profile.availability || { zh: '待运营确认', en: 'Pending ops confirmation' },
  note: profile.note || {
    zh: '此档案由运营录入，真实上架前需确认医生授权和展示边界。',
    en: 'This profile is entered by ops. Authorization and display boundaries must be confirmed before publication.'
  }
});

const loadStoredDoctors = () => {
  try {
    const saved = localStorage.getItem(DOCTOR_STORAGE_KEY);
    const rows = saved ? JSON.parse(saved) : DOCTOR_PROFILES;
    return rows.map(normalizeDoctorProfile);
  } catch (error) {
    return DOCTOR_PROFILES.map(normalizeDoctorProfile);
  }
};

const loadStoredLeads = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    const rows = saved ? JSON.parse(saved) : SAMPLE_LEADS;
    return rows.map(normalizeLead);
  } catch (error) {
    return SAMPLE_LEADS.map(normalizeLead);
  }
};

const localNow = () => {
  const d = new Date();
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  const hh = String(d.getHours()).padStart(2, '0');
  const mi = String(d.getMinutes()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
};

const parseLeadDate = (value) => {
  const parsed = new Date(String(value || '').replace(' ', 'T'));
  return Number.isNaN(parsed.getTime()) ? null : parsed;
};

const isRecentLead = (lead) => {
  const created = parseLeadDate(lead.createdAt);
  if (!created) return true;
  return new Date() - created <= 60 * 24 * 60 * 60 * 1000;
};

const pct = (part, total) => `${total ? Math.round((part / total) * 100) : 0}%`;

const groupCounts = (rows, keyFn) => rows.reduce((acc, row) => {
  const key = keyFn(row) || 'Unknown';
  acc[key] = (acc[key] || 0) + 1;
  return acc;
}, {});

const topEntries = (counts, limit = 4) => Object.entries(counts)
  .sort((a, b) => b[1] - a[1])
  .slice(0, limit);

const getOpsInsights = (leads) => {
  const recent = leads.filter(isRecentLead);
  const total = recent.length;
  const sourceRows = Object.entries(recent.reduce((acc, lead) => {
    const key = lead.source || 'Website intake';
    const current = acc[key] || { total: 0, quality: 0 };
    current.total += 1;
    if (['High', 'Medium'].includes(lead.tier) || lead.acceptsPaid === 'yes') current.quality += 1;
    acc[key] = current;
    return acc;
  }, {})).sort((a, b) => b[1].total - a[1].total).slice(0, 4);

  return {
    recent,
    total,
    paidConversion: pct(recent.filter((lead) => lead.status === 'Paid').length, total),
    paidIntent: pct(recent.filter((lead) => lead.acceptsPaid === 'yes').length, total),
    chinaIntent: pct(recent.filter((lead) => ['yes', 'maybe'].includes(lead.considersChina)).length, total),
    recordsReady: pct(recent.filter((lead) => getRecordReadiness(lead).pct === 100).length, total),
    conditionRows: topEntries(groupCounts(recent, (lead) => lead.conditionId), 5),
    sourceRows
  };
};

const toCsv = (rows) => {
  const headers = ['id', 'createdAt', 'source', 'name', 'country', 'city', 'language', 'condition', 'hasRecords', 'recordReadiness', 'timeframe', 'acceptsPaid', 'considersChina', 'score', 'tier', 'status', 'nextAction', 'matchedDoctorId', 'doctorFeedbackStatus', 'rejectionReason', 'contact', 'doctorAdvice', 'notes'];
  const escape = (value) => `"${String(value ?? '').replaceAll('"', '""')}"`;
  const body = rows.map((row) => {
    const condition = getCondition(row.conditionId).name.en;
    const values = headers.map((key) => {
      if (key === 'condition') return condition;
      if (key === 'recordReadiness') return `${getRecordReadiness(row).pct}%`;
      if (key === 'doctorFeedbackStatus') return normalizeDoctorFeedback(row.doctorFeedback).status;
      return row[key];
    });
    return values.map(escape).join(',');
  });
  return [headers.join(','), ...body].join('\n');
};

const downloadCsv = (rows) => {
  const blob = new Blob([toCsv(rows)], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `huamed-leads-${new Date().toISOString().slice(0, 10)}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const ClientApp = () => {
  const [lang, setLang] = React.useState(() => localStorage.getItem(CLIENT_LANG_KEY) || 'en');
  const [clientPage, setClientPage] = React.useState(CLIENT_PAGE);
  const [active, setActive] = React.useState('overview');
  const [selectedCondition, setSelectedCondition] = React.useState('lung');
  const [selectedFocusCondition, setSelectedFocusCondition] = React.useState('lung');
  const [serviceId, setServiceId] = React.useState('second-opinion');
  const [checkedDocs, setCheckedDocs] = React.useState({});
  const [form, setForm] = React.useState(emptyForm);
  const [errors, setErrors] = React.useState({});
  const [lastResult, setLastResult] = React.useState(null);
  const [lastWhatsappUrl, setLastWhatsappUrl] = React.useState('');
  const [noticeOpen, setNoticeOpen] = React.useState(false);
  const [whatsappContactOpen, setWhatsappContactOpen] = React.useState(false);
  const [intakeModalOpen, setIntakeModalOpen] = React.useState(() => new URLSearchParams(window.location.search).get('form') === '1');
  const [consentOpen, setConsentOpen] = React.useState(false);
  const [profileOpen, setProfileOpen] = React.useState(false);
  const [authOpen, setAuthOpen] = React.useState(() => new URLSearchParams(window.location.search).get('auth') === 'mock-google');
  const [authSession, setAuthSession] = React.useState(loadStoredClientSession);
  const [config, setConfig] = React.useState(DEFAULT_CLIENT_CONFIG);
  const [submitError, setSubmitError] = React.useState('');
  const [leads, setLeads] = React.useState(loadStoredLeads);

  const copy = UI[lang];

  React.useEffect(() => {
    localStorage.setItem(CLIENT_LANG_KEY, lang);
    localStorage.setItem('huamed-lang', lang);
  }, [lang]);

  React.useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(leads));
  }, [leads]);

  React.useEffect(() => {
    apiJson('/api/config').then((nextConfig) => {
      setConfig({ ...DEFAULT_CLIENT_CONFIG, ...(nextConfig || {}) });
    }).catch(() => {});
    apiJson('/api/me').then((session) => {
      setAuthSession(session);
      if (session?.role === 'client') localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
    }).catch(() => {
      setAuthSession(loadStoredClientSession());
    });
  }, []);

  const updateAuthSession = (session) => {
    setAuthSession(session);
    if (session?.role === 'client') localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
    else localStorage.removeItem(AUTH_STORAGE_KEY);
  };

  const logoutClient = async () => {
    try {
      await apiJson('/api/auth/logout', { method: 'POST' });
    } catch {}
    updateAuthSession({ role: 'guest', user: null });
    setProfileOpen(false);
    setConsentOpen(false);
  };

  const hasAcceptedLegal = authSession?.user?.legalConsentStatus === 'accepted';

  React.useEffect(() => {
    if (authSession?.role === 'client' && !authSession.user?.legalConsentStatus) setConsentOpen(true);
  }, [authSession?.role, authSession?.user?.legalConsentStatus]);

  const updateLegalConsent = async (status) => {
    try {
      const session = await apiJson('/api/consent', {
        method: 'POST',
        body: JSON.stringify({ status, version: config.legalConsentVersion || LEGAL_CONSENT_VERSION })
      });
      updateAuthSession(session);
      setConsentOpen(false);
    } catch (err) {
      if (isStaticPreviewApiError(err)) {
        updateAuthSession({
          ...authSession,
          user: {
            ...(authSession.user || {}),
            legalConsentStatus: status,
            legalConsentVersion: config.legalConsentVersion || LEGAL_CONSENT_VERSION,
            legalConsentAt: new Date().toISOString()
          }
        });
        setConsentOpen(false);
      }
    }
  };

  const tr = (value) => textOf(value, lang);

  const syncConditionFromUrl = () => {
    const params = new URLSearchParams(window.location.search);
    const scene = params.get('scene');
    if (scene) {
      setForm((prev) => ({ ...prev, serviceScene: scene, conditionId: scene === 'medical' ? prev.conditionId : scene }));
    }
    const conditionId = params.get('condition');
    if (!conditionId) return;
    const condition = getCondition(conditionId);
    if (!condition?.id) return;
    setSelectedCondition(condition.id);
    setForm((prev) => ({ ...prev, conditionId: condition.id }));
    if (FOCUS_CONDITION_IDS.includes(condition.id)) setSelectedFocusCondition(condition.id);
  };

  const navigateClientPage = (page, options = {}) => {
    const path = CLIENT_PAGE_PATHS[page] || CLIENT_PAGE_PATHS.home;
    const params = new URLSearchParams();
    if (options.condition) params.set('condition', options.condition);
    if (options.scene) params.set('scene', options.scene);
    const query = params.toString() ? `?${params.toString()}` : '';
    const hash = options.hash ? `#${options.hash}` : '';
    const nextUrl = `${path}${query}${hash}`;
    if (`${window.location.pathname.split('/').pop() || 'index.html'}${window.location.search}${window.location.hash}` !== nextUrl) {
      window.history.pushState({ clientPage: page }, '', nextUrl);
    }
    setClientPage(page);
    setActive(options.hash || (page === 'home' ? 'overview' : page));
    if (options.condition) {
      const condition = getCondition(options.condition);
      setSelectedCondition(condition.id);
      setForm((prev) => ({ ...prev, conditionId: condition.id }));
      if (FOCUS_CONDITION_IDS.includes(condition.id)) setSelectedFocusCondition(condition.id);
    }
    if (options.scene) {
      setForm((prev) => ({ ...prev, serviceScene: options.scene, conditionId: options.scene === 'medical' ? prev.conditionId : options.scene }));
    }
    requestAnimationFrame(() => {
      if (options.hash) document.getElementById(options.hash)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      else window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  };

  const go = (id) => {
    if (id?.includes?.('.html')) {
      const url = new URL(id, window.location.href);
      const file = url.pathname.split('/').pop();
      const page = Object.entries(CLIENT_PAGE_PATHS).find(([, path]) => path === file)?.[0] || 'home';
      navigateClientPage(page, {
        hash: url.hash.replace('#', '') || '',
        condition: url.searchParams.get('condition') || '',
        scene: url.searchParams.get('scene') || ''
      });
      if (page === 'intake' && url.searchParams.get('form') === '1') {
        requestAnimationFrame(() => setIntakeModalOpen(true));
      }
      return;
    }
    if (document.getElementById(id)) {
      setActive(id);
      requestAnimationFrame(() => {
        document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      });
      return;
    }
    if (clientPage !== 'home' && id !== 'intake') {
      navigateClientPage('home', { hash: id });
      return;
    }
    setActive(id);
    requestAnimationFrame(() => {
      document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  };

  React.useEffect(() => {
    const onPopState = () => {
      const file = window.location.pathname.split('/').pop() || 'index.html';
      const page = Object.entries(CLIENT_PAGE_PATHS).find(([, path]) => path === file)?.[0] || 'home';
      setClientPage(page);
      syncConditionFromUrl();
      const hash = window.location.hash?.replace('#', '');
      if (hash) setActive(hash);
    };
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  React.useEffect(() => {
    syncConditionFromUrl();
  }, []);

  React.useEffect(() => {
    if (clientPage !== 'home') return;
    const id = window.location.hash?.replace('#', '');
    if (!id) return;
    setActive(id);
    requestAnimationFrame(() => {
      document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  }, [clientPage]);

  const selected = getCondition(selectedCondition);
  const selectedFocus = getFrontstageConditions().find((item) => item.id === selectedFocusCondition) || getFrontstageConditions()[0];
  const selectedService = SERVICES.find((item) => item.id === serviceId) || SERVICES[0];
  const preparedCount = selected.docs.filter((doc) => checkedDocs[doc.en]).length;
  const clientLeads = leads
    .filter((lead) => leadMatchesClient(lead, authSession?.user, form))
    .slice(0, 10);
  const latestClientLead = lastResult || clientLeads[0] || null;
  const hasSubmittedIntake = Boolean(latestClientLead);
  const supportWhatsappUrl = lastWhatsappUrl || whatsappUrlFromConfig(config, latestClientLead);

  const openWhatsappSupport = () => {
    if (supportWhatsappUrl) window.location.href = supportWhatsappUrl;
  };

  const updateForm = (key, value) => {
    setForm((prev) => {
      if (key === 'country') {
        return {
          ...prev,
          country: value,
          contact: shouldReplaceDialPrefix(prev.contact) ? dialPrefixForCountry(value) : prev.contact
        };
      }
      return { ...prev, [key]: value };
    });
    setErrors((prev) => ({ ...prev, [key]: false }));
    if (key === 'country') setErrors((prev) => ({ ...prev, contact: false }));
  };

  const validateForm = () => {
    const required = ['name', 'country', 'city', 'contact', 'serviceScene'];
    if (form.serviceScene === 'medical') required.push('conditionId');
    const nextErrors = {};
    required.forEach((key) => {
      if (!form[key]) nextErrors[key] = true;
    });
    if (form.contact && !validateContactForCountry(form.contact, form.country)) {
      nextErrors.contact = true;
      setSubmitError(contactHintForCountry(form.country, lang));
    }
    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const submitForm = async (event) => {
    event.preventDefault();
    setSubmitError('');
    if (!validateForm()) return;
    if (authSession.role !== 'client') {
      setAuthOpen(true);
      return;
    }
    if (!hasAcceptedLegal) {
      setConsentOpen(true);
      setSubmitError(lang === 'zh' ? '提交咨询前需要先阅读并接受 Privacy Policy 与 Terms & Conditions。' : 'Please review and accept the Privacy Policy and Terms & Conditions before submitting.');
      return;
    }
    try {
      const result = await apiJson('/api/intake', {
        method: 'POST',
        body: JSON.stringify(form)
      });
      setLeads((prev) => [normalizeLead(result.lead), ...prev.filter((lead) => lead.id !== result.lead.id)]);
      setLastResult(result.lead);
      setLastWhatsappUrl(result.whatsappUrl || whatsappUrlFromConfig(config, result.lead));
      setActive('intake');
      setSubmitError('');
    } catch (err) {
      if (isStaticPreviewApiError(err)) {
        const lead = createLocalDemoLead(form);
        setLeads((prev) => [lead, ...prev.filter((item) => item.id !== lead.id)]);
        setLastResult(lead);
        setLastWhatsappUrl(whatsappUrlFromConfig(config, lead));
        setActive('intake');
        setSubmitError(lang === 'zh'
          ? '资料已记录。服务团队会根据你留下的联系方式继续沟通。'
          : 'Your information has been recorded. The service team will follow up through the contact details provided.');
        return;
      }
      setSubmitError(err.status === 401
        ? (lang === 'zh' ? '请先完成 Google 登录。' : 'Please sign in with Google first.')
        : err.status === 403
        ? (lang === 'zh' ? '提交咨询前需要先接受 Privacy Policy 与 Terms & Conditions。' : 'Please accept the Privacy Policy and Terms & Conditions before submitting.')
        : (lang === 'zh' ? '提交失败，请确认本地服务已启动。' : 'Submission failed. Please confirm the local server is running.'));
      if (err.status === 401) setAuthOpen(true);
      if (err.status === 403) setConsentOpen(true);
    }
  };

  const resetForm = () => {
    setForm(emptyForm);
    setErrors({});
    setLastResult(null);
    setLastWhatsappUrl('');
  };

  const renderClientContent = () => {
    if (clientPage === 'team') {
      return <TeamPage lang={lang} go={go} />;
    }
    if (clientPage === 'hospitals') {
      return <HospitalsPage lang={lang} go={go} />;
    }
    if (clientPage === 'system') {
      return <MedicalSystemPage lang={lang} go={go} />;
    }
    if (clientPage === 'medical') {
      return (
        <CrossBorderMedicalPage
          lang={lang}
          tr={tr}
          selected={selected}
          selectedCondition={selectedCondition}
          setSelectedCondition={setSelectedCondition}
          selectedFocus={selectedFocus}
          selectedFocusCondition={selectedFocusCondition}
          setSelectedFocusCondition={setSelectedFocusCondition}
          setForm={setForm}
          go={go}
          copy={copy}
        />
      );
    }
    if (clientPage === 'frontier') {
      return <FrontierMedicinePage lang={lang} go={go} />;
    }
    if (clientPage === 'knowledge') {
      return <KnowledgeCenterPage lang={lang} go={go} />;
    }
    if (clientPage === 'service-plan') {
      return <ServicePlanPage lang={lang} go={go} />;
    }
    if (clientPage === 'process') {
      return <ProcessPage lang={lang} go={go} />;
    }
    if (clientPage === 'privacy') {
      return <LegalPage lang={lang} type="privacy" />;
    }
    if (clientPage === 'terms') {
      return <LegalPage lang={lang} type="terms" />;
    }
    if (clientPage === 'intake') {
      return (
        <>
          <SubmitFlowPage lang={lang} go={go} onOpenIntake={() => setIntakeModalOpen(true)} />
        </>
      );
    }
    return (
      <>
        <HeroSection lang={lang} copy={copy} go={go} />

        <section id="second-opinion-first" className="scroll-mt-24">
          <SecondOpinionFirstSection lang={lang} go={go} />
        </section>

        <section id="conditions" className="conditions-teaser scroll-mt-24">
          <ServiceScenesSection
            lang={lang}
            go={go}
            setForm={setForm}
            copy={copy}
          />
        </section>
        <JourneyFAQSection lang={lang} />
      </>
    );
  };

  return (
    <div className="app-shell portal-client min-h-screen">
      <main className="min-w-0 flex-1">
        <TopBar
          lang={lang}
          setLang={setLang}
          copy={copy}
          active={active}
          go={go}
          onNotice={() => setNoticeOpen(true)}
          portal="client"
          clientPage={clientPage}
          authSession={authSession}
          onProfile={() => authSession.role === 'client' ? setProfileOpen(true) : setAuthOpen(true)}
        />

        <div className="client-content-shell space-y-8 px-5 py-6 md:px-10 md:py-8">
          {renderClientContent()}
          <Footer lang={lang} go={go} portal="client" />
        </div>
      </main>

      <Modal open={noticeOpen} onClose={() => setNoticeOpen(false)} title={copy.riskNotice} lang={lang}>
        <div className="space-y-3">
          {RISK_COPY[lang].map((line, index) => (
            <div key={index} className="flex gap-3 rounded-2xl bg-marble-50 p-3.5 text-sm leading-relaxed text-sea-500 ring-1 hairline">
              <span className="mt-1 h-1.5 w-1.5 shrink-0 rounded-full bg-gold-400" />
              <span>{line}</span>
            </div>
          ))}
        </div>
        <div className="mt-5 flex justify-end">
          <Button variant="sea" icon="check" onClick={() => setNoticeOpen(false)}>{copy.close}</Button>
        </div>
      </Modal>
      <ClientAuthModal
        open={authOpen}
        onClose={() => setAuthOpen(false)}
        lang={lang}
        config={config}
        onLoggedIn={updateAuthSession}
      />
      <LegalConsentModal
        open={consentOpen}
        onClose={() => setConsentOpen(false)}
        lang={lang}
        onAccept={() => updateLegalConsent('accepted')}
        onDecline={() => updateLegalConsent('declined')}
      />
      <ClientProfileModal
        open={profileOpen}
        onClose={() => setProfileOpen(false)}
        lang={lang}
        authSession={authSession}
        form={form}
        leads={clientLeads}
        onLogout={logoutClient}
        onEditLead={(lead) => {
          setForm((prev) => ({
            ...prev,
            ...lead,
            attachmentSummary: Array.isArray(lead.attachmentSummary) ? lead.attachmentSummary : [],
            serviceScene: lead.serviceScene || 'medical',
            conditionId: lead.conditionId || prev.conditionId || 'lung'
          }));
          setLastResult(lead);
          setLastWhatsappUrl(whatsappUrlFromConfig(config, lead));
          setProfileOpen(false);
          setIntakeModalOpen(true);
        }}
        onAddLead={() => {
          resetForm();
          setProfileOpen(false);
          setIntakeModalOpen(true);
        }}
      />
      <Modal
        open={intakeModalOpen}
        onClose={() => setIntakeModalOpen(false)}
        title={lang === 'zh' ? '提交信息' : 'Submit Information'}
        lang={lang}
      >
        <IntakeSection
          lang={lang}
          tr={tr}
          form={form}
          updateForm={updateForm}
          errors={errors}
          submitForm={submitForm}
          resetForm={resetForm}
          lastResult={lastResult}
          submitError={submitError}
          authSession={authSession}
          config={config}
          whatsappUrl={lastWhatsappUrl}
          copy={copy}
        />
      </Modal>
      <WhatsAppContactModal
        open={whatsappContactOpen}
        onClose={() => setWhatsappContactOpen(false)}
        lang={lang}
        hasSubmittedIntake={hasSubmittedIntake}
        whatsappUrl={supportWhatsappUrl}
        onGoIntake={() => {
          setWhatsappContactOpen(false);
          go('intake.html');
        }}
        onOpenWhatsapp={openWhatsappSupport}
      />
      <WhatsAppFloat
        lang={lang}
        hasSubmittedIntake={hasSubmittedIntake}
        onClick={() => {
          setWhatsappContactOpen(true);
        }}
      />
    </div>
  );
};

const SideNav = ({ active, go, lang, setLang, copy, portal = 'client', navItems }) => {
  const items = navItems || [
    { id: 'overview', icon: 'layout-dashboard', label: copy.nav.overview },
    { id: 'conditions', icon: 'scan-search', label: copy.nav.conditions },
    { id: 'hospitals', icon: 'building-2', label: copy.nav.hospitals },
    { id: 'services', icon: 'route', label: copy.nav.services },
    { id: 'checklist', icon: 'clipboard-list', label: copy.nav.checklist },
    { id: 'intake', icon: 'file-pen-line', label: copy.nav.intake }
  ];
  const subline = {
    client: { en: 'China Care Coordination', zh: '中国专家二诊与来华协调' },
    ops: { en: 'Operations Console', zh: '线索与病例流转后台' },
    doctor: { en: 'Doctor Partnership', zh: '中国合作医生与医院资源' }
  }[portal] || {};

  return (
    <aside className="side-nav w-[268px] shrink-0 border-r hairline bg-white/68 backdrop-blur-md">
      <div className="side-nav-shell flex h-full flex-col">
        <div className="brand-panel px-6 pb-5 pt-7">
          <div className="flex items-center gap-3">
            <BrandMark size={44} />
            <div>
              <div className="font-zh text-[20px] font-semibold leading-tight text-sea-500">华医畅</div>
              <div className="font-serif-display text-[16px] leading-tight text-gold-600">HuaMed</div>
            </div>
          </div>
          <div className="brand-subline mt-4 text-[10px] uppercase tracking-[0.24em] text-sea-300">{subline.en}</div>
          <div className="brand-subline font-zh mt-1 text-[11px] tracking-wider text-sea-300">{subline.zh}</div>
        </div>

        <nav className="nav-list flex-1 space-y-1 px-4 pb-4">
          {items.map(({ id, icon, label }, index) => {
            const isActive = active === id;
            return (
              <button
                key={id}
                onClick={() => go(id)}
                className={`flex w-full items-center gap-3 rounded-2xl px-3.5 py-2.5 text-left transition ${isActive ? 'bg-sea-400/10 shadow-soft' : 'hover:bg-marble-200/60'}`}
              >
                <span className={`flex h-8 w-8 items-center justify-center rounded-xl ${isActive ? 'gold-gradient text-sea-600' : 'bg-marble-100 text-sea-400'}`}>
                  <Icon name={icon} size={15} />
                </span>
                <span className="min-w-0 flex-1 text-[13px] font-medium text-sea-500">{label}</span>
                <span className="nav-index font-mono-display text-[10px] text-marble-400">{String(index + 1).padStart(2, '0')}</span>
              </button>
            );
          })}
        </nav>

        <div className="language-card m-4 rounded-3xl sea-gradient p-4 text-marble-100 shadow-deep">
          <div className="mb-3 flex items-center justify-between">
            <div>
              <div className="text-[10px] uppercase tracking-[0.22em] text-gold-300">{copy.language}</div>
              <div className="font-zh text-[12px] text-marble-100/70">中文 / English</div>
            </div>
            <Icon name="languages" size={18} className="text-gold-300" />
          </div>
          <div className="grid grid-cols-2 gap-1 rounded-2xl bg-white/10 p-1">
            {[
              ['zh', copy.chinese],
              ['en', copy.english]
            ].map(([id, label]) => (
              <button key={id} onClick={() => setLang(id)} className={`h-9 rounded-xl text-[12px] font-medium transition ${lang === id ? 'gold-gradient text-sea-600' : 'text-marble-100/75 hover:bg-white/10'}`}>
                {label}
              </button>
            ))}
          </div>
        </div>
      </div>
    </aside>
  );
};

const PortalLinks = ({ lang, current }) => {
  const links = [
    { id: 'client', href: 'index.html', label: lang === 'zh' ? '客户端' : 'Client' },
    { id: 'ops', href: 'ops.html', label: lang === 'zh' ? '运营端' : 'Ops' },
    { id: 'doctor', href: 'doctor.html', label: lang === 'zh' ? '医生端' : 'Doctor' }
  ];
  return (
    <div className="hidden rounded-2xl bg-white p-1 ring-1 hairline md:flex">
      {links.map((link) => (
        <a key={link.id} href={link.href} className={`inline-flex h-8 items-center rounded-xl px-3 text-[12px] font-medium transition ${current === link.id ? 'gold-gradient text-sea-600' : 'text-sea-400 hover:bg-marble-100'}`}>
          {link.label}
        </a>
      ))}
    </div>
  );
};

const ClientTopNav = ({ active, go, copy, lang, clientPage }) => {
  const [openMenu, setOpenMenu] = React.useState('');
  const navRef = React.useRef(null);
  const canHoverNav = () => window.matchMedia?.('(hover: hover) and (pointer: fine)').matches;
  React.useEffect(() => {
    const close = (event) => {
      if (!navRef.current?.contains(event.target)) setOpenMenu('');
    };
    document.addEventListener('pointerdown', close);
    return () => document.removeEventListener('pointerdown', close);
  }, []);
  const serviceItems = SERVICE_SCENES.map((scene) => ({
    id: scene.id,
    icon: scene.icon,
    name: scene.name,
    short: scene.short,
    href: scene.href
  }));
  const items = [
    { id: 'overview', icon: 'layout-dashboard', label: lang === 'zh' ? '首页' : 'Home', href: 'index.html' },
    {
      id: 'conditions',
      icon: 'sparkles',
      label: lang === 'zh' ? '服务场景' : 'Service Scenarios',
      href: 'index.html#conditions',
      menu: [
        { title: lang === 'zh' ? '三大服务场景' : 'Three service scenarios', items: serviceItems }
      ]
    },
    { id: 'team', icon: 'users-round', label: lang === 'zh' ? '团队介绍' : 'Team', href: 'team.html' },
    { id: 'hospitals', icon: 'building-2', label: lang === 'zh' ? '医院介绍' : 'Hospitals', href: 'hospitals.html' },
    {
      id: 'process',
      icon: 'route',
      label: lang === 'zh' ? '定制就医旅程' : 'Custom Care Journey',
      href: 'intake.html',
      special: true
    },
  ];
  return (
    <nav ref={navRef} className="client-top-nav" aria-label="HuaMed navigation">
      {items.map(({ id, icon, label, href, menu, special }) => {
        const isActive = clientPage === 'home'
          ? active === id || (id === 'overview' && active === 'overview')
          : clientPage === id || (['medical', 'frontier'].includes(clientPage) && id === 'conditions') || (clientPage === 'intake' && id === 'process');
        return (
          <div
            key={id}
            className={`client-nav-group ${openMenu === id ? 'is-open' : ''}`}
            onMouseEnter={() => menu && canHoverNav() && setOpenMenu(id)}
            onMouseLeave={() => menu && canHoverNav() && setOpenMenu('')}
            onFocus={() => menu && canHoverNav() && setOpenMenu(id)}
          >
            <button
              type="button"
              onClick={(event) => {
                if (menu) {
                  event.preventDefault();
                  setOpenMenu((current) => current === id ? '' : id);
                  return;
                }
                go(href);
              }}
              className={`client-top-nav-item ${special ? 'is-special' : ''} ${isActive ? 'is-active' : ''}`}
              title={label}
              aria-label={label}
              aria-expanded={menu ? openMenu === id : undefined}
            >
              <Icon name={icon} size={15} />
              <span>{label}</span>
              {menu && <Icon name="chevron-down" size={12} className="nav-chevron" />}
            </button>
            {menu && (
              <div className={`client-nav-menu ${id === 'conditions' ? 'is-wide is-conditions' : ''}`}>
                {menu.map((group) => (
                  <div key={group.title} className="client-nav-menu-column">
                    <div className="client-nav-menu-title">{group.title}</div>
                    {group.items.map((item) => (
                      <button
                        key={item.id}
                        type="button"
                        className="client-nav-menu-item"
                        onClick={() => {
                          setOpenMenu('');
                          item.href ? go(item.href) : go(`index.html#conditions`);
                        }}
                      >
                        <Icon name={item.icon} size={14} />
                        <span className="min-w-0 flex-1">
                          <span className="block truncate">{textOf(item.name, lang)}</span>
                          {item.short && <span className="mt-0.5 block truncate text-[10px] font-normal text-marble-500">{textOf(item.short, lang)}</span>}
                        </span>
                      </button>
                    ))}
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })}
    </nav>
  );
};

const UserAvatarButton = ({ lang, authSession, onClick }) => {
  if (authSession?.role !== 'client') {
    return (
      <Button variant="ghost" icon="log-in" onClick={onClick} className="user-avatar-button h-10 px-3">
        {lang === 'zh' ? '登录' : 'Sign in'}
      </Button>
    );
  }
  const user = authSession.user || {};
  const displayName = clientDisplayName(user, lang);
  const initial = (displayName || user.email || 'H').trim().slice(0, 1).toUpperCase();
  return (
    <button
      type="button"
      onClick={onClick}
      className="user-avatar-button flex h-10 items-center gap-2 rounded-2xl bg-white px-2.5 text-left shadow-soft ring-1 hairline transition hover:ring-gold-300"
      title={lang === 'zh' ? '查看用户信息' : 'View profile'}
    >
      {user.avatar ? (
        <img src={user.avatar} alt="" className="h-7 w-7 rounded-xl object-cover" />
      ) : (
        <span className="flex h-7 w-7 items-center justify-center rounded-xl sea-gradient text-xs font-semibold text-gold-300">{initial}</span>
      )}
      <span className="hidden max-w-[120px] truncate text-[12px] font-medium text-sea-500 md:block">{displayName || user.email}</span>
    </button>
  );
};

const TopBar = ({ lang, setLang, copy, active, go, onNotice, portal = 'client', clientPage = CLIENT_PAGE, authSession, onProfile }) => {
  const badge = {
    client: { tone: 'gold', icon: 'map-pin', zh: '客户端', en: 'Client portal' },
    ops: { tone: 'sea', icon: 'lock-keyhole', zh: '运营端', en: 'Ops portal' },
    doctor: { tone: 'green', icon: 'stethoscope', zh: '医生合作端', en: 'Doctor portal' }
  }[portal] || { tone: 'gold', icon: 'map-pin', zh: '客户端', en: 'Client portal' };
  return (
    <header className="top-bar sticky top-0 z-10 flex h-[72px] items-center justify-between border-b hairline bg-marble-100/82 px-5 backdrop-blur-md md:px-10">
      <div className="flex min-w-0 items-center gap-4">
        <a href="#overview" onClick={(event) => { event.preventDefault(); go?.('overview'); }} className="top-brand-link" aria-label="HuaMed">
          <BrandMark size={portal === 'client' ? 42 : 34} />
          {portal === 'client' ? (
            <span className="top-brand-wordmark">
              <span>{lang === 'zh' ? '华医畅 HuaMed' : 'HuaMed'}</span>
              <small>{lang === 'zh' ? '来华就医服务平台' : 'China care platform'}</small>
            </span>
          ) : (
            <span className="top-brand-wordmark">
              <span>HuaMed</span>
              <small>{lang === 'zh' ? '内部协作端' : 'Internal portal'}</small>
            </span>
          )}
        </a>
        {portal === 'client' && <ClientTopNav active={active} go={go} copy={copy} lang={lang} clientPage={clientPage} />}
        {portal !== 'client' && (
          <>
            <Pill tone={badge.tone} icon={badge.icon}>{lang === 'zh' ? badge.zh : badge.en}</Pill>
            <div className="hidden text-[12px] text-marble-500 md:block">
              HuaMed · <span className="font-zh">{lang === 'zh' ? '领先的来华就医服务平台' : 'Leading China medical service platform'}</span>
            </div>
          </>
        )}
      </div>
      <div className="flex items-center gap-2">
        {portal !== 'client' && <PortalLinks lang={lang} current={portal} />}
        <div className="language-switch rounded-2xl bg-white p-1 ring-1 hairline">
          <button onClick={() => setLang('zh')} className={`h-8 rounded-xl px-3 text-[12px] font-medium ${lang === 'zh' ? 'gold-gradient text-sea-600' : 'text-sea-400'}`}>中文</button>
          <button onClick={() => setLang('en')} className={`h-8 rounded-xl px-3 text-[12px] font-medium ${lang === 'en' ? 'gold-gradient text-sea-600' : 'text-sea-400'}`}>EN</button>
        </div>
        {portal !== 'client' && (
          <button
            type="button"
            onClick={onNotice}
            aria-label={copy.riskNotice}
            title={copy.riskNotice}
            className="top-risk-button"
          >
            <Icon name="shield-alert" size={16} />
            <span className="top-risk-dot" aria-hidden="true" />
          </button>
        )}
        {portal === 'client' && <UserAvatarButton lang={lang} authSession={authSession} onClick={onProfile} />}
      </div>
    </header>
  );
};

const ClientProfileModal = ({ open, onClose, lang, authSession, form, leads = [], onEditLead, onAddLead, onLogout }) => {
  const user = authSession?.user || {};
  const displayName = clientDisplayName(user, lang);
  const rows = [
    [lang === 'zh' ? '姓名' : 'Name', form.name || displayName || '-'],
    [lang === 'zh' ? '邮箱' : 'Email', user.email || '-'],
    [lang === 'zh' ? '国家 / 地区' : 'Country / region', form.country || user.country || '-'],
    [lang === 'zh' ? '城市' : 'City', form.city || user.city || '-'],
    [lang === 'zh' ? 'WhatsApp 手机号' : 'WhatsApp number', form.contact || user.whatsapp || user.phone || '-'],
    [lang === 'zh' ? '沟通语言' : 'Language', form.language || user.language || '-']
  ];
  return (
    <Modal open={open} onClose={onClose} title={lang === 'zh' ? '我的资料' : 'My profile'} lang={lang} className="profile-modal-panel">
      <div className="space-y-4">
        <div className="flex items-center gap-4 rounded-3xl bg-marble-50 p-4 ring-1 hairline">
          {user.avatar ? (
            <img src={user.avatar} alt="" className="h-14 w-14 rounded-2xl object-cover" />
          ) : (
            <div className="flex h-14 w-14 items-center justify-center rounded-2xl sea-gradient text-lg font-semibold text-gold-300">
              {(displayName || user.email || 'H').slice(0, 1).toUpperCase()}
            </div>
          )}
          <div className="min-w-0">
            <div className="truncate text-base font-semibold text-sea-500">{displayName || (lang === 'zh' ? '华医畅用户' : 'HuaMed client')}</div>
            <div className="mt-1 truncate text-sm text-marble-500">{user.email || '-'}</div>
          </div>
        </div>
        <div className="grid gap-3 md:grid-cols-2">
          {rows.map(([label, value]) => (
            <div key={label} className="rounded-2xl bg-white p-3 ring-1 hairline">
              <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{label}</div>
              <div className="mt-1 min-h-[20px] break-words text-sm text-sea-500">{value}</div>
            </div>
          ))}
        </div>
        <div className="rounded-2xl bg-gold-50 p-3 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
          {lang === 'zh'
            ? '这里展示你的注册信息和本次咨询基础资料，方便你核对联系方式和服务场景。'
            : 'Review your account details and current consultation basics, including contact information and service scenario.'}
        </div>
        <div className="flex justify-end">
          <Button variant="ghost" icon="log-out" onClick={onLogout}>
            {lang === 'zh' ? '退出登录' : 'Sign out'}
          </Button>
        </div>
        <div className="rounded-3xl bg-white p-4 ring-1 hairline">
          <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.18em] text-gold-600">{lang === 'zh' ? '咨询资料' : 'Consultation profiles'}</div>
              <div className="mt-1 text-sm text-sea-400/78">
                {lang === 'zh' ? `最多可保留 10 份资料，当前 ${leads.length} 份。` : `Up to 10 profiles can be kept. Current: ${leads.length}.`}
              </div>
            </div>
            <Button
              icon="plus"
              variant="ghost"
              disabled={leads.length >= 10}
              onClick={onAddLead}
            >
              {lang === 'zh' ? '新增资料' : 'Add profile'}
            </Button>
          </div>
          <div className="space-y-2">
            {leads.length ? leads.map((lead, index) => (
              <button
                key={lead.id || `${lead.name}-${index}`}
                type="button"
                onClick={() => onEditLead?.(lead)}
                className="flex w-full items-center justify-between gap-3 rounded-2xl bg-marble-50 p-3 text-left ring-1 hairline transition hover:ring-gold-200"
              >
                <span className="min-w-0">
                  <span className="block truncate text-sm font-semibold text-sea-500">{lead.name || displayName} · {textOf(getCondition(lead.conditionId).name, lang)}</span>
                  <span className="mt-0.5 block truncate text-xs text-marble-500">{lead.createdAt ? new Date(lead.createdAt).toLocaleDateString() : (lang === 'zh' ? '已提交资料' : 'Submitted')}</span>
                </span>
                <span className="inline-flex items-center gap-1 text-[12px] font-semibold text-gold-700">
                  {lang === 'zh' ? '修改' : 'Edit'}
                  <Icon name="arrow-right" size={13} />
                </span>
              </button>
            )) : (
              <div className="rounded-2xl bg-marble-50 p-3 text-sm text-sea-400/78 ring-1 hairline">
                {lang === 'zh' ? '还没有已提交的咨询资料。' : 'No submitted consultation profile yet.'}
              </div>
            )}
          </div>
        </div>
      </div>
    </Modal>
  );
};

const ClientAuthModal = ({ open, onClose, lang, config, onLoggedIn }) => {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  if (!open) return null;

  const mockLogin = async () => {
    setLoading(true);
    setError('');
    try {
      const session = await apiJson('/api/auth/google/mock', {
        method: 'POST',
        body: JSON.stringify({
          googleId: 'mock-client',
          email: 'client@huamed.local',
          name: lang === 'zh' ? '华医畅客户' : 'HuaMed Client'
        })
      });
      onLoggedIn(session);
      onClose();
    } catch (err) {
      if (isStaticPreviewApiError(err)) {
        onLoggedIn(createLocalClientSession(lang));
        onClose();
        return;
      }
      setError(lang === 'zh' ? '登录失败，请确认本地服务已启动或刷新后重试。' : 'Login failed. Please confirm the local server is running or refresh and retry.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={lang === 'zh' ? '使用 Google 登录，提交咨询表单' : 'Continue with Google to submit'} lang={lang}>
      <div className="space-y-4">
        <div className="rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
          {lang === 'zh'
            ? '华医畅使用 Google 登录确认客户身份。登录后请阅读并接受 Privacy / Terms，再提交咨询表单和 WhatsApp 联系方式。'
            : 'HuaMed uses Google sign-in to confirm client identity. After signing in, review and accept Privacy / Terms, then submit the consultation form and WhatsApp contact.'}
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          <Button icon="chrome" onClick={() => { window.location.href = '/api/auth/google/start'; }} className="w-full">
            {lang === 'zh' ? '使用 Google 登录' : 'Continue with Google'}
          </Button>
          {!config.googleConfigured && (
            <Button variant="ghost" icon="badge-check" disabled={loading} onClick={mockLogin} className="w-full">
              {loading ? (lang === 'zh' ? '登录中...' : 'Signing in...') : (lang === 'zh' ? '本地模拟 Google' : 'Mock Google locally')}
            </Button>
          )}
        </div>
        {!config.googleConfigured && (
          <p className="text-xs leading-relaxed text-marble-500">
            {lang === 'zh'
              ? '当前登录服务暂不可用，请先通过 WhatsApp 服务窗口联系华医畅团队。'
              : 'Sign-in is temporarily unavailable. Please contact the HuaMed team through the WhatsApp service window.'}
          </p>
        )}
        {error && <div className="rounded-2xl bg-rose-50 p-3 text-sm text-rose-700 ring-1 ring-rose-100">{error}</div>}
      </div>
    </Modal>
  );
};

const LegalConsentModal = ({ open, onClose, lang, onAccept, onDecline }) => {
  if (!open) return null;
  return (
    <Modal open={open} onClose={onClose} title={lang === 'zh' ? '请先确认隐私与服务条款' : 'Please review privacy and terms'} lang={lang}>
      <div className="space-y-4">
        <div className="rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
          {lang === 'zh'
            ? '为了继续提交咨询表单，华医畅需要记录你已阅读并同意 Privacy Policy 与 Terms & Conditions。你可以继续浏览网站；如果选择暂不同意，将不能提交医疗资料或咨询请求。'
            : 'To submit a consultation form, HuaMed needs to record that you have reviewed and accepted the Privacy Policy and Terms & Conditions. You may continue browsing; if you decline, medical records or consultation requests cannot be submitted.'}
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          <a href="privacy.html" className="rounded-2xl bg-marble-50 p-4 text-sm font-semibold text-sea-500 ring-1 hairline hover:bg-white">
            <Icon name="lock-keyhole" size={15} className="mr-2 inline text-gold-600" />
            Privacy Policy
          </a>
          <a href="terms.html" className="rounded-2xl bg-marble-50 p-4 text-sm font-semibold text-sea-500 ring-1 hairline hover:bg-white">
            <Icon name="file-check-2" size={15} className="mr-2 inline text-gold-600" />
            Terms & Conditions
          </a>
        </div>
        <div className="flex flex-wrap justify-end gap-3">
          <Button variant="ghost" icon="x" onClick={onDecline}>{lang === 'zh' ? '暂不同意' : 'Decline for now'}</Button>
          <Button icon="check" onClick={onAccept}>{lang === 'zh' ? '我已阅读并同意' : 'I have read and accept'}</Button>
        </div>
      </div>
    </Modal>
  );
};

const WhatsAppContactModal = ({ open, onClose, lang, hasSubmittedIntake, whatsappUrl, onGoIntake, onOpenWhatsapp }) => (
  <Modal open={open} onClose={onClose} title={lang === 'zh' ? 'WhatsApp 人工客服' : 'WhatsApp support'} lang={lang} className="whatsapp-contact-modal">
    <div className="grid gap-5 md:grid-cols-[minmax(0,1fr)_190px] md:items-center">
      <div className="space-y-4">
        <div className="rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
          {hasSubmittedIntake
            ? (lang === 'zh'
              ? '你已提交咨询资料，可以继续通过 WhatsApp 与人工客服沟通下一步安排。'
              : 'Your consultation profile has been submitted. Continue on WhatsApp for the next step.')
            : (lang === 'zh'
              ? '填写初筛资料能让客服更快判断服务场景、资料状态和下一步；你也可以先直接通过 WhatsApp 建立联系。'
              : 'Completing the intake helps support review your service scenario, record status, and next step faster. You can also start with WhatsApp first.')}
        </div>
        <div className={`whatsapp-contact-actions ${hasSubmittedIntake ? 'flex justify-end' : 'grid grid-cols-1 gap-3 sm:grid-cols-2'}`}>
          {!hasSubmittedIntake && (
            <Button variant="ghost" icon="file-pen-line" className="w-full whitespace-nowrap" onClick={onGoIntake}>
              {lang === 'zh' ? '先去填写资料' : 'Complete intake first'}
            </Button>
          )}
          <Button
            icon="message-circle"
            className={`${hasSubmittedIntake ? '' : 'w-full'} whitespace-nowrap whatsapp-direct-button`}
            disabled={!whatsappUrl}
            onClick={onOpenWhatsapp}
          >
            {lang === 'zh' ? '直接打开 WhatsApp' : 'Open WhatsApp'}
          </Button>
        </div>
      </div>
      <div className="rounded-3xl bg-white p-3 text-center shadow-soft ring-1 hairline">
        <img
          src="assets/contact/whatsapp-qr.png"
          alt={lang === 'zh' ? '华医畅 WhatsApp 二维码' : 'HuaMed WhatsApp QR code'}
          className="mx-auto aspect-square w-full max-w-[172px] rounded-2xl"
        />
        <div className="mt-2 text-[11px] leading-relaxed text-sea-400">
          {lang === 'zh' ? '电脑端可扫码联系' : 'Scan on desktop'}
        </div>
      </div>
    </div>
  </Modal>
);

const WhatsAppFloat = ({ lang, hasSubmittedIntake, onClick }) => (
  <button
    type="button"
    onClick={onClick}
    className="whatsapp-float fixed bottom-5 right-5 z-40 flex max-w-[calc(100vw-40px)] items-center gap-3 rounded-3xl sea-gradient px-4 py-3 text-left text-marble-100 shadow-deep ring-1 ring-white/15 transition hover:-translate-y-0.5"
    aria-label={lang === 'zh' ? '打开 WhatsApp 人工客服' : 'Open WhatsApp support'}
  >
    <span className="whatsapp-float-icon flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl bg-emerald-500 text-white">
      <Icon name="message-circle" size={22} />
    </span>
    <span className="whatsapp-float-text min-w-0">
      <span className="block text-sm font-semibold">{lang === 'zh' ? '24 小时人工客服' : '24h Human Support'}</span>
      <span className="block text-[11px] text-marble-100/72">
        {hasSubmittedIntake ? (lang === 'zh' ? '继续沟通下一步' : 'Continue next step') : (lang === 'zh' ? '可先直接沟通' : 'Start with WhatsApp')}
      </span>
    </span>
  </button>
);

const LINE_SCENES = [
  'assets/stage7-line-scenes/scene-01-submit.svg',
  'assets/stage7-line-scenes/scene-02-specialists.svg',
  'assets/stage7-line-scenes/scene-03-flight.svg',
  'assets/stage7-line-scenes/scene-04-hospital-surgery.svg',
  'assets/stage7-line-scenes/scene-05-recovery.svg',
  'assets/stage7-line-scenes/scene-06-followup.svg'
];

const HERO_VIDEOS = [
  'assets/stage7-videos/01.mp4',
  'assets/stage7-videos/02.mp4',
  'assets/stage7-videos/03.mp4',
  'assets/stage7-videos/4.mp4',
  'assets/stage7-videos/5.mp4',
  'assets/stage7-videos/06.mp4',
  'assets/stage7-videos/07.mp4',
  'assets/stage7-videos/08.mp4',
  'assets/stage7-videos/09.mp4',
  'assets/stage7-videos/10.mp4',
  'assets/stage7-videos/11.mp4',
  'assets/stage7-videos/12.mp4'
];

const HERO_VIDEO_TITLES = [
  'When Everything Feels Uncertain',
  'Connecting to Expert Care',
  'A Clear Path Forward',
  'Taking the First Step',
  'You\'re in Safe Hands',
  'Entering Professional Care',
  'Expert Decisions, Together',
  'Precision in Action',
  'Recovery Begins',
  'Returning to Life',
  'Care That Continues'
];

const HERO_VIDEO_DESCRIPTIONS = {
  zh: [
    '从看不懂报告开始，先把问题、资料和下一步选择整理清楚。',
    '把病例摘要交给合适的中国专科方向，先做资料层面的预评估。',
    '明确是否适合线上二诊、来华面诊、继续观察或先在当地处理。',
    '通过 Google 登录提交资料，再进入 WhatsApp 人工服务承接。',
    '运营团队协助梳理风险、边界和沟通重点，不替代医生诊断。',
    '适合来华时，协助理解门诊、检查、住院和院内沟通流程。',
    '围绕专家意见和家庭目标，一起判断更现实的就医路径。',
    '需要手术或专项评估时，重点协调资料、流程和风险告知。',
    '治疗后继续关注康复、复查、出院资料和家属沟通。',
    '回到当地后，保留复查节奏、用药提醒和后续资料整理。',
    '服务不止于一次咨询，而是持续支持家庭理解下一步。'
  ],
  en: [
    'Start by organizing the concern, records, and practical next-step options.',
    'Turn the case into a specialist-ready brief for China-side pre-assessment.',
    'Clarify whether second opinion, China visit, local care, or monitoring fits best.',
    'Submit records through Google sign-in, then continue with WhatsApp support.',
    'HuaMed helps organize risk, boundaries, and questions without replacing physicians.',
    'When China care is suitable, understand outpatient, testing, admission, and communication flow.',
    'Compare expert input with family goals to choose a realistic care pathway.',
    'For surgery or advanced review, coordinate records, process, and risk notice.',
    'After care, keep recovery, follow-up, discharge records, and family updates clear.',
    'Return home with review rhythm, medication notes, and follow-up records organized.',
    'The service continues beyond one consultation by helping families understand what comes next.'
  ]
};

const HeroSection = ({ lang, copy, go }) => (
  <section id="overview" className="home-hero relative overflow-hidden rounded-4xl p-6 text-marble-100 shadow-deep md:p-10">
    <HeroFilm lang={lang} />
    <HeroBrandWatermark />

    <div className="home-hero-content relative z-[2] grid gap-8 xl:items-center">
      <div className="home-hero-copy">
        <div className="mb-6 inline-flex max-w-full items-center gap-2 rounded-full bg-white/10 px-3 py-2 ring-1 ring-white/14 backdrop-blur-sm">
          <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-gold-300 pulse-dot" />
          <span className="truncate text-[11px] font-medium uppercase tracking-[0.2em] text-gold-200">{copy.heroEyebrow}</span>
        </div>
        <h1 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} max-w-[620px] text-[36px] font-semibold leading-tight text-white md:text-[48px] xl:text-[54px]`}>
          {copy.heroTitle}
        </h1>
        <p className="mt-5 max-w-[590px] text-[14px] leading-7 text-marble-100/78 md:text-[15px]">{copy.heroText}</p>
        <div className="mt-7 flex flex-wrap gap-3">
          <Button icon="file-pen-line" onClick={() => go('intake.html')}>{copy.primaryCta}</Button>
        </div>
        <HeroServiceTicker lang={lang} />
      </div>

      <div className="home-hero-animation">
        <HeroVideoSequence lang={lang} />
      </div>
    </div>
  </section>
);

const HeroServiceTicker = ({ lang }) => {
  const labels = [
    ...SERVICE_SCENES.map((scene) => textOf(scene.name, lang)),
    ...FOCUS_CONDITION_IDS.map((id) => getCondition(id).name[lang])
  ];
  return (
    <div className="hero-service-strip mt-8" aria-label={lang === 'zh' ? '服务内容' : 'Services'}>
      <div className="hero-service-track">
        {[...labels, ...labels].map((label, index) => (
          <span key={`${label}-${index}`} className="hero-service-chip">{label}</span>
        ))}
      </div>
    </div>
  );
};

const ServiceScenesSection = ({ lang, go, setForm, copy }) => (
  <>
    <SectionHeader
      eyebrow="Service Scenarios"
      lang={lang}
      title={{ zh: copy.sectionConditions, en: copy.sectionConditions }}
      subtitle={{
        zh: '如果你已经有异常报告、想安排高端体检，或想了解中国前沿医学资源，可以先从这里判断适合自己的服务路径。',
        en: 'If you have abnormal reports, need a premium checkup, or want to understand frontier medical resources in China, start here to find the right service path.'
      }}
      right={<Pill tone="gold" icon="sparkles">{lang === 'zh' ? '三大服务入口' : 'Three service entries'}</Pill>}
    />
    <div className="service-scene-grid">
      {SERVICE_SCENES.map((scene) => (
        <button
          key={scene.id}
          type="button"
          className={`service-scene-card is-${scene.id}`}
          onClick={() => {
            setForm((prev) => ({
              ...prev,
              serviceScene: scene.id,
              conditionId: scene.id === 'medical' ? prev.conditionId || 'lung' : scene.id
            }));
            go(scene.href);
          }}
        >
          <div className="mb-5 flex items-start justify-between gap-4">
            <span className={`flex h-12 w-12 items-center justify-center rounded-2xl ${scene.tone === 'gold' ? 'gold-gradient text-sea-600' : scene.tone === 'sea' ? 'sea-gradient text-gold-300' : 'bg-marble-100 text-sea-500'}`}>
              <Icon name={scene.icon} size={22} />
            </span>
            <Icon name="arrow-up-right" size={18} className="text-gold-600" />
          </div>
          <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-[28px] leading-tight text-sea-500`}>{textOf(scene.name, lang)}</h3>
          <p className="mt-3 min-h-[90px] text-sm leading-relaxed text-sea-400/78">{textOf(scene.short, lang)}</p>
          <div className="mt-5 flex flex-wrap gap-2">
            {scene.highlights[lang].map((item) => <Pill key={item} tone={scene.tone === 'gold' ? 'gold' : 'marble'}>{item}</Pill>)}
          </div>
          <div className="mt-5 inline-flex items-center gap-1.5 text-[12px] font-semibold text-gold-700">
            {textOf(scene.cta, lang)}
            <Icon name="arrow-right" size={13} />
          </div>
        </button>
      ))}
    </div>
  </>
);

const SecondOpinionFirstSection = ({ lang, go }) => {
  const steps = [
    ['upload-cloud', lang === 'zh' ? '提交病例资料' : 'Submit medical records', lang === 'zh' ? '上传既往病历、检查报告、影像、病理、用药记录和当地医生建议。' : 'Upload prior records, reports, imaging, pathology, medication history, and local doctor advice.'],
    ['languages', lang === 'zh' ? '病例整理与翻译' : 'Case organization and translation', lang === 'zh' ? '华医畅将零散资料整理成中国医生能够快速理解的病例摘要和关键问题。' : 'HuaMed organizes scattered records into a China-specialist-ready case brief and key questions.'],
    ['stethoscope', lang === 'zh' ? '中国专家二诊评估' : 'China specialist second opinion', lang === 'zh' ? '协调中国三甲医院相关专科专家进行远程二诊或方向判断。' : 'Coordinate remote second opinion or directional review with relevant China tertiary-hospital specialist resources.'],
    ['route', lang === 'zh' ? '判断是否需要来华' : 'Decide whether China travel is needed', lang === 'zh' ? '根据专家意见，判断是否需要来中国进一步面诊、检查、住院或手术评估。' : 'Use the specialist view to decide whether in-person consultation, testing, admission, or surgery assessment in China is needed.'],
    ['plane', lang === 'zh' ? '推进来华就医服务' : 'Move into China care coordination', lang === 'zh' ? '如适合来华，继续协助医院、科室、专家方向、检查安排、保险沟通和到院服务。' : 'If China travel fits, coordinate hospital, department, specialist direction, testing, insurance communication, and arrival-day support.']
  ];
  return (
    <Card padding="p-7 md:p-9" className="second-opinion-first-card">
      <SectionHeader
        eyebrow="Second Opinion First"
        lang={lang}
        title={{ zh: '先获得中国专家意见，再决定是否来华', en: 'Get a China specialist view before deciding whether to travel' }}
        subtitle={{
          zh: '海外患者面对中国医疗体系时，真正困难的往往不是“找到一家医院”，而是判断自己是否适合来华、应该看哪个专科、需要准备哪些资料，以及如何把有限的来华时间安排到合适的医院和专家路径中。',
          en: 'For overseas patients, the hard part is often not finding a hospital, but knowing whether China travel fits, which specialty direction matters, what records are required, and how to use limited time in China effectively.'
        }}
        right={<Pill tone="gold" icon="search-check">{lang === 'zh' ? '先判断，再来华' : 'Assess first'}</Pill>}
      />
      <div className="second-opinion-steps">
        {steps.map(([icon, title, text], index) => (
          <div key={title} className="second-opinion-step">
            <div className="second-opinion-step-index">{String(index + 1).padStart(2, '0')}</div>
            <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl gold-gradient text-sea-600">
              <Icon name={icon} size={19} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
          </div>
        ))}
      </div>
      <div className="mt-7 flex flex-wrap gap-3">
        <Button icon="file-pen-line" onClick={() => go('intake.html?form=1')}>{lang === 'zh' ? '提交病例资料' : 'Submit records'}</Button>
        <Button variant="ghost" icon="receipt-text" onClick={() => go('intake.html#packages')}>{lang === 'zh' ? '了解服务套餐' : 'View service packages'}</Button>
      </div>
    </Card>
  );
};

const FrontierPreviewSection = ({ lang }) => (
  <Card padding="p-7" className="frontier-preview">
    <SectionHeader
      eyebrow="Frontier Medicine"
      lang={lang}
      title={{ zh: '前沿医学资源咨询与适配评估', en: 'Frontier medicine resource consultation and fit review' }}
      subtitle={{
        zh: '围绕合规创新药械、研究型医学成果和先行项目方向，帮助用户理解适用条件、资料要求和沟通边界。',
        en: 'Review regulated innovation programs, research-led medical advances, and pilot directions with clear eligibility, record needs, and communication boundaries.'
      }}
      right={<Pill tone="marble" icon="message-circle">{lang === 'zh' ? '详细请咨询助理' : 'Ask an assistant for details'}</Pill>}
    />
    <div className="grid gap-4 md:grid-cols-3">
      {[
        ['dna', lang === 'zh' ? '基因治疗方向' : 'Gene therapy directions', lang === 'zh' ? '关注合规路径下的适应证、检测资料、既往治疗史和可及性。' : 'Review eligibility, genetic testing records, prior treatment history, and realistic access under regulated pathways.'],
        ['activity', lang === 'zh' ? '细胞与干细胞疗法' : 'Cell and stem cell therapies', lang === 'zh' ? '介绍研究型医学进展和合规边界，先判断疾病阶段、风险和资料完整度。' : 'Introduce research-led advances and compliance boundaries, starting with disease stage, risk, and record readiness.'],
        ['flask-conical', lang === 'zh' ? '创新药械与先行项目' : 'Innovative drugs and devices', lang === 'zh' ? '围绕特许药械、创新器械和研究项目做信息整理与适配预评估。' : 'Organize information and fit pre-review around special-access drugs, devices, and research programs.']
      ].map(([icon, title, text]) => (
        <div key={title} className="rounded-3xl bg-white/72 p-5 ring-1 hairline">
          <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl bg-marble-100 text-sea-500">
            <Icon name={icon} size={19} />
          </div>
          <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
          <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
        </div>
      ))}
    </div>
  </Card>
);

const FrontierMedicinePage = ({ lang, go }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Frontier Medicine"
      icon="flask-conical"
      heroImage="assets/page-heroes/frontier-medicine.png"
      title={lang === 'zh' ? '前沿医学咨询' : 'Frontier Medicine Consultation'}
      subtitle={lang === 'zh'
        ? '面向关注合规创新药械、研究型医学成果和先行项目的用户，帮助理解适用条件、资料要求和沟通边界。华医畅仅提供信息整理、资料适配和沟通协助，不承诺治疗可及性或疗效。'
        : 'For users interested in regulated innovative drugs or devices, research-led medical advances, and pilot programs. HuaMed helps clarify eligibility, record requirements, and communication boundaries without promising access or outcomes.'}
    />
    <FrontierPreviewSection lang={lang} />
    <Card padding="p-7" className="frontier-page-boundary">
      <SectionHeader
        eyebrow="Fit Review"
        lang={lang}
        title={{ zh: '先看资料是否适配，再讨论下一步', en: 'Review record fit before discussing next steps' }}
        subtitle={{
          zh: '前沿医学方向通常对诊断、病理、基因检测、既往治疗史和疾病阶段有严格要求。华医畅可以协助整理资料、理解公开信息和沟通边界，但不替代医生判断，不承诺项目接收、药械可及性或治疗效果。',
          en: 'Frontier medicine directions often require specific diagnosis, pathology, genomic testing, prior treatment history, and disease-stage records. HuaMed can help organize records and clarify public information and communication boundaries, but does not replace physician judgment or promise program acceptance, access, or outcomes.'
        }}
        right={<Button icon="file-pen-line" onClick={() => go('intake.html?scene=frontier&form=1')}>{lang === 'zh' ? '提交资料咨询' : 'Submit records'}</Button>}
      />
      <div className="grid gap-5 md:grid-cols-3">
        {[
          ['file-search', lang === 'zh' ? '资料适配' : 'Record fit', lang === 'zh' ? '先核对诊断、病理、影像、基因检测和既往治疗记录是否足以沟通。' : 'Check whether diagnosis, pathology, imaging, genomic, and prior-treatment records are sufficient for discussion.'],
          ['shield-alert', lang === 'zh' ? '合规边界' : 'Compliance boundary', lang === 'zh' ? '只讨论合规公开路径和资料要求，不包装为确定治疗机会。' : 'Discuss regulated public pathways and record needs only, not guaranteed treatment opportunities.'],
          ['message-circle', lang === 'zh' ? '人工沟通' : 'Human coordination', lang === 'zh' ? '适合继续时，再由服务团队协助理解沟通流程和补充材料。' : 'When suitable, the service team helps clarify communication flow and additional records.']
        ].map(([icon, title, text]) => (
          <div key={title} className="rounded-3xl bg-white/75 p-5 ring-1 hairline">
            <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl bg-marble-100 text-sea-500">
              <Icon name={icon} size={19} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
          </div>
        ))}
      </div>
    </Card>
  </>
);

const CrossBorderMedicalPage = ({ lang, tr, selected, selectedCondition, setSelectedCondition, selectedFocus, selectedFocusCondition, setSelectedFocusCondition, setForm, go, copy }) => (
  <>
    <Card padding="p-0" className="cross-border-hero overflow-hidden">
      <div className="grid gap-8 p-7 lg:grid-cols-12 lg:p-10">
        <div className="lg:col-span-7">
          <div className="mb-4 inline-flex items-center gap-2 rounded-full bg-gold-50 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-gold-700 ring-1 ring-gold-100">
            <Icon name="stethoscope" size={13} />
            {lang === 'zh' ? '跨国医疗服务' : 'Cross-border Medical Service'}
          </div>
          <h1 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} max-w-3xl text-[36px] leading-tight text-sea-500 md:text-[46px]`}>
            {lang === 'zh' ? '从异常报告到中国专家二诊和来华路径评估' : 'From abnormal reports to China specialist review and care pathway planning'}
          </h1>
          <p className="mt-4 max-w-3xl text-sm leading-7 text-sea-400/78 md:text-[15px]">
            {lang === 'zh'
              ? '适合已经拿到检查结果、影像、病理或本地医生建议的家庭。华医畅先帮助整理资料、识别关键问题，再判断是否适合专家二诊、门诊评估、择期手术沟通或来华诊疗协调。'
              : 'For families with test results, imaging, pathology, or local doctor advice. HuaMed helps organize records, identify key questions, and review whether specialist second opinion, outpatient review, elective surgery communication, or China care coordination is appropriate.'}
          </p>
          <div className="mt-6 flex flex-wrap gap-2">
            {[
              lang === 'zh' ? '专家二诊预评估' : 'Specialist pre-review',
              lang === 'zh' ? '病种资料清单' : 'Record checklist',
              lang === 'zh' ? '来华路径判断' : 'China pathway fit',
              lang === 'zh' ? '不替代医生诊断' : 'No diagnostic replacement'
            ].map((item) => <Pill key={item} tone="gold">{item}</Pill>)}
          </div>
          <div className="mt-7 flex flex-wrap gap-3">
            <Button icon="file-pen-line" onClick={() => go('intake.html?scene=medical')}>{lang === 'zh' ? '提交资料，先免费判断' : 'Submit records for initial review'}</Button>
            <Button icon="arrow-down" variant="ghost" onClick={() => go('condition-detail')}>{lang === 'zh' ? '查看病种方向' : 'View condition directions'}</Button>
          </div>
        </div>
        <div className="lg:col-span-5">
          <div className="grid h-full content-start gap-3 rounded-3xl bg-white/70 p-5 ring-1 hairline">
            {[
              ['file-search', lang === 'zh' ? '先看资料是否足够' : 'Record readiness first', lang === 'zh' ? '报告、影像、病理、既往治疗史决定能否进入下一步。' : 'Reports, imaging, pathology, and treatment history determine the next step.'],
              ['messages-square', lang === 'zh' ? '再整理专家问题' : 'Then prepare specialist questions', lang === 'zh' ? '把家庭关心的问题转成医生可判断的病例摘要。' : 'Turn family concerns into a doctor-readable case brief.'],
              ['route', lang === 'zh' ? '最后判断现实路径' : 'Finally review realistic pathways', lang === 'zh' ? '二诊、继续当地处理、门诊或来华安排都需要边界清晰。' : 'Second opinion, local care, outpatient review, and China visits all need clear boundaries.']
            ].map(([icon, title, text]) => (
              <div key={title} className="rounded-2xl bg-white p-4 ring-1 hairline">
                <div className="mb-2 flex items-center gap-2 text-sm font-semibold text-sea-500">
                  <Icon name={icon} size={16} className="text-gold-600" />
                  {title}
                </div>
                <p className="text-sm leading-relaxed text-sea-400/75">{text}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Card>

    <section id="condition-detail" className="scroll-mt-24">
      <ConditionDetailSection
        lang={lang}
        tr={tr}
        condition={selectedFocus}
        selectedConditionId={selectedFocusCondition}
        setSelectedCondition={(condition) => {
          setSelectedFocusCondition(condition.id);
          setSelectedCondition(condition.sourceId);
          setForm((prev) => ({ ...prev, serviceScene: 'medical', conditionId: condition.sourceId }));
        }}
        go={go}
      />
    </section>

    <section id="checklist" className="scroll-mt-24">
      <ChecklistSection
        lang={lang}
        tr={tr}
        selected={selected}
        selectedCondition={selectedCondition}
        setSelectedCondition={(conditionId) => {
          setSelectedCondition(conditionId);
          setForm((prev) => ({ ...prev, serviceScene: 'medical', conditionId }));
          if (FOCUS_CONDITION_IDS.includes(conditionId)) setSelectedFocusCondition(conditionId);
        }}
        copy={copy}
      />
    </section>
  </>
);

const HeroBrandWatermark = () => (
  <img src="assets/brand/icon.png" alt="" className="hero-brand-watermark" aria-hidden="true" />
);

const getJourneySteps = (lang) => ([
  {
    icon: 'file-heart',
    marker: '01',
    title: lang === 'zh' ? '找到 HuaMed，线上提交资料' : 'Find HuaMed and submit records online',
    text: lang === 'zh' ? '客户有异常报告或症状困惑时，先通过 HuaMed 提交基础情况、报告和 WhatsApp 联系方式。' : 'When a family has abnormal reports or health concerns, they submit basics, records, and WhatsApp contact through HuaMed.'
  },
  {
    icon: 'stethoscope',
    marker: '02',
    title: lang === 'zh' ? '专家团队协助二诊预评估' : 'Specialists support pre-assessment',
    text: lang === 'zh' ? '运营整理病例摘要和问题清单，再协调中国专科医生围绕资料做二诊预评估。' : 'Ops prepares the case brief and questions, then coordinates China specialists for record-based pre-assessment.'
  },
  {
    icon: 'plane',
    marker: '03',
    title: lang === 'zh' ? '适合时来华就诊' : 'Travel to China when suitable',
    text: lang === 'zh' ? '确认适合继续后，再协助规划来华城市、医院方向、门诊和检查流程。' : 'When the case is suitable, HuaMed helps plan city, hospital direction, outpatient visits, and tests in China.'
  },
  {
    icon: 'hospital',
    marker: '04',
    title: lang === 'zh' ? '高端医院环境内治疗协调' : 'Treatment coordination in a premium hospital',
    text: lang === 'zh' ? '需要手术或住院评估时，协助客户理解院内流程、术前准备、风险告知和沟通安排。' : 'For surgery or inpatient assessment, HuaMed helps with hospital flow, pre-op preparation, risk notice, and communication.'
  },
  {
    icon: 'heart-pulse',
    marker: '05',
    title: lang === 'zh' ? '术后康复与院内支持' : 'Post-op recovery and hospital support',
    text: lang === 'zh' ? '术后阶段关注康复节奏、出院资料、复查安排和家属沟通，让客户知道下一步。' : 'After care, HuaMed focuses on recovery rhythm, discharge records, follow-up checks, and family communication.'
  },
  {
    icon: 'home',
    marker: '06',
    title: lang === 'zh' ? '健康回国，持续随访' : 'Return home with follow-up',
    text: lang === 'zh' ? '回到当地后继续整理复查提醒、用药和随访资料，形成长期服务闭环。' : 'After returning home, follow-up reminders, medication notes, and review records continue the service loop.'
  }
]);

const HeroJourneyAnimation = ({ lang, activeStep }) => {
  const steps = getJourneySteps(lang);
  const active = steps[activeStep] || steps[0];
  const [svgMarkup, setSvgMarkup] = React.useState('');
  const [loadError, setLoadError] = React.useState(false);
  const sceneRef = React.useRef(null);
  const painterRef = React.useRef(null);
  const sceneSrc = LINE_SCENES[activeStep] || LINE_SCENES[0];

  React.useEffect(() => {
    let cancelled = false;
    setLoadError(false);
    fetch(sceneSrc)
      .then((response) => {
        if (!response.ok) throw new Error(`Scene failed: ${response.status}`);
        return response.text();
      })
      .then((markup) => {
        if (!cancelled) setSvgMarkup(markup);
      })
      .catch(() => {
        if (!cancelled) {
          setSvgMarkup('');
          setLoadError(true);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [sceneSrc]);

  React.useEffect(() => {
    const svg = sceneRef.current?.querySelector('svg');
    const Painter = window.LazyLinePainter || window['lazy-line-painter']?.default || window['lazy-line-painter'];
    const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
    painterRef.current?.pause?.();
    painterRef.current = null;
    if (!svg || !Painter || reduceMotion) return;
    const painter = new Painter(svg, {
      strokeWidth: 4,
      strokeColor: '#F4E9BE',
      strokeCap: 'round',
      strokeJoin: 'round',
      ease: 'easeInOutQuad',
      repeat: 0,
      log: false
    });
    painterRef.current = painter;
    painter.paint();
    return () => {
      painter.pause?.();
    };
  }, [svgMarkup]);

  return (
    <div className="hero-journey-panel relative overflow-hidden">
      <div className="hero-journey-scene" ref={sceneRef}>
        {svgMarkup ? (
          <div dangerouslySetInnerHTML={{ __html: svgMarkup }} />
        ) : (
          <div className="flex min-h-[320px] items-center justify-center text-sm text-marble-100/58">
            {loadError ? (lang === 'zh' ? '线稿加载失败' : 'Scene failed to load') : (lang === 'zh' ? '线稿载入中...' : 'Loading line art...')}
          </div>
        )}
      </div>

      <div className="hero-journey-caption">
        <div className="flex items-center justify-between gap-3">
          <span className="font-mono-display text-[11px] uppercase tracking-[0.22em] text-gold-300">{active.marker}</span>
          <div className="flex gap-1.5">
            {steps.map((step, index) => (
              <span key={step.marker} className={`hero-journey-dot ${activeStep === index ? 'is-active' : ''}`} />
            ))}
          </div>
        </div>
        <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-2 text-[22px] leading-tight text-white`}>{active.title}</h3>
        <p className="mt-2 text-[12px] leading-relaxed text-marble-100/68">{active.text}</p>
      </div>
    </div>
  );
};

const HeroVideoSequence = ({ lang }) => {
  const videoRef = React.useRef(null);
  const [activeVideo, setActiveVideo] = React.useState(0);
  const currentSrc = HERO_VIDEOS[activeVideo] || HERO_VIDEOS[0];
  const nextSrc = HERO_VIDEOS[(activeVideo + 1) % HERO_VIDEOS.length];
  const title = HERO_VIDEO_TITLES[activeVideo];
  const description = HERO_VIDEO_DESCRIPTIONS[lang]?.[activeVideo];

  const requestPlayback = React.useCallback(() => {
    if (!videoRef.current) return;
    const video = videoRef.current;
    video.muted = true;
    video.playsInline = true;
    const play = video.play?.();
    if (play?.catch) play.catch(() => {});
  }, []);

  const goNextVideo = React.useCallback(() => {
    setActiveVideo((current) => (current + 1) % HERO_VIDEOS.length);
  }, []);

  React.useEffect(() => {
    requestPlayback();
    const onVisible = () => {
      if (document.visibilityState === 'visible') requestPlayback();
    };
    const onFocus = () => requestPlayback();
    const onFirstGesture = () => requestPlayback();
    document.addEventListener('visibilitychange', onVisible);
    window.addEventListener('focus', onFocus);
    window.addEventListener('pointerdown', onFirstGesture, { once: true });
    window.addEventListener('touchstart', onFirstGesture, { once: true });
    return () => {
      document.removeEventListener('visibilitychange', onVisible);
      window.removeEventListener('focus', onFocus);
      window.removeEventListener('pointerdown', onFirstGesture);
      window.removeEventListener('touchstart', onFirstGesture);
    };
  }, [currentSrc, requestPlayback]);

  return (
    <div className="hero-video-stack">
      <div className="hero-video-panel relative overflow-hidden">
        <video
          ref={videoRef}
          key={currentSrc}
          className="hero-video"
          src={currentSrc}
          autoPlay
          muted
          playsInline
          preload="auto"
          onLoadedData={requestPlayback}
          onCanPlay={requestPlayback}
          onEnded={goNextVideo}
          onError={goNextVideo}
        />
        <video className="hidden" src={nextSrc} preload="metadata" aria-hidden="true" />
        <div className="hero-video-shade" />
        <div className="hero-video-watermark-cover" aria-hidden="true" />
      </div>
      {title && (
        <div className="hero-video-caption" key={title}>
          <span className="hero-video-caption-title">{title}</span>
          <span className="hero-video-caption-text">{description}</span>
        </div>
      )}
    </div>
  );
};

const HeroFilm = () => (
  <div className="hero-film">
    <div className="hero-film-grid" />
  </div>
);

const JourneyCardContent = ({ step }) => (
  <>
    <div className="mb-2 flex items-center justify-between gap-3">
      <div className="flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-gold-300">
        <Icon name={step.icon} size={12} />
        <span>{step.marker}</span>
      </div>
    </div>
    <div className="text-sm font-medium leading-tight text-white">{step.title}</div>
    <div className="mt-2 text-[12px] leading-relaxed text-marble-100/68">{step.text}</div>
  </>
);

const MobileHeroFilm = ({ lang }) => {
  const [playing, setPlaying] = React.useState(true);
  const steps = getJourneySteps(lang);
  return (
    <div className={`relative mt-7 overflow-hidden rounded-3xl border border-white/15 bg-white/8 p-4 backdrop-blur-sm lg:hidden ${playing ? 'is-playing' : 'is-paused'}`}>
      <div className="scan-sweep" />
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="h-2 w-2 rounded-full bg-gold-300 pulse-dot" />
          <span className="font-mono-display text-[10px] uppercase tracking-[0.2em] text-gold-300">{lang === 'zh' ? 'HuaMed 服务路径' : 'HuaMed service journey'}</span>
        </div>
        <button
          onClick={() => setPlaying(!playing)}
          className="inline-flex h-8 items-center gap-1.5 rounded-full bg-white/10 px-3 text-[11px] font-medium text-marble-100 ring-1 ring-white/15"
        >
          <Icon name={playing ? 'pause' : 'play'} size={11} />
          {playing ? (lang === 'zh' ? '暂停' : 'Pause') : (lang === 'zh' ? '播放' : 'Play')}
        </button>
      </div>
      <div className="grid gap-3">
        {steps.map((step) => (
          <div key={step.marker} className="film-card flex items-start gap-3 rounded-2xl bg-white/10 p-3 ring-1 ring-white/10">
            <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl gold-gradient text-sea-600">
              <Icon name={step.icon} size={15} />
            </span>
            <span className="min-w-0 flex-1">
              <span className="block text-sm font-medium text-white">{step.title}</span>
              <span className="mt-1 block text-[11px] leading-relaxed text-marble-100/62">{step.text}</span>
            </span>
            <span className="font-mono-display text-[11px] text-gold-300">{step.marker}</span>
          </div>
        ))}
      </div>
      <div className="mt-4 h-1.5 overflow-hidden rounded-full bg-white/12">
        <div className="video-progress h-full rounded-full gold-gradient" />
      </div>
    </div>
  );
};

const getFrontstageConditions = () => {
  const detail = {
    lung: {
      video: { zh: '肺结节报告怎么看：大小、密度、边界和随访节奏', en: 'How to read a lung nodule report: size, density, margin, and follow-up timing' },
      image: 'assets/conditions/lung.png',
      points: {
        zh: ['磨玻璃、实性、混合性结节的常见关注点', '随访、穿刺、消融、手术评估通常看哪些资料', '既往 CT 对比为什么很重要'],
        en: ['Common concerns for ground-glass, solid, and mixed nodules', 'What records support follow-up, biopsy, ablation, or surgery review', 'Why prior CT comparison matters']
      },
      specialists: { zh: ['胸外科', '影像科', '呼吸专科'], en: ['Thoracic surgery', 'Radiology', 'Respiratory medicine'] }
    },
    thyroid: {
      video: { zh: '甲状腺结节下一步：TI-RADS、穿刺与手术必要性', en: 'Thyroid nodule next steps: TI-RADS, FNA, and surgery necessity' },
      image: 'assets/conditions/thyroid.png',
      points: {
        zh: ['TI-RADS 分级如何影响下一步', '什么时候需要穿刺，什么时候可以观察', '如何避免过度治疗或延误治疗'],
        en: ['How TI-RADS category affects next steps', 'When FNA is considered and when surveillance may be enough', 'How to avoid overtreatment or delayed treatment']
      },
      specialists: { zh: ['甲状腺外科', '超声科', '内分泌科'], en: ['Thyroid surgery', 'Ultrasound', 'Endocrinology'] }
    },
    breast: {
      video: { zh: '乳腺结节和早癌：影像、病理与治疗路径比较', en: 'Breast nodules and early cancer: imaging, pathology, and pathway comparison' },
      image: 'assets/conditions/breast.png',
      points: {
        zh: ['BI-RADS 4 类后常见选择', '穿刺病理和免疫组化如何影响方案', '保乳、切除、重建等路径如何准备问题'],
        en: ['Common options after BI-RADS 4 findings', 'How biopsy pathology and IHC influence planning', 'How to prepare questions around lumpectomy, mastectomy, and reconstruction']
      },
      specialists: { zh: ['乳腺外科', '病理科', '肿瘤科'], en: ['Breast surgery', 'Pathology', 'Oncology'] }
    },
    colorectal: {
      video: { zh: '结直肠息肉和早癌：内镜切除还是外科手术', en: 'Colorectal polyps and early cancer: endoscopic removal or surgery' },
      image: 'assets/conditions/colorectal.png',
      points: {
        zh: ['息肉大小、形态、位置和病理如何影响选择', 'EMR / ESD / 外科手术的资料准备', '高级别病变为什么需要尽快厘清路径'],
        en: ['How size, shape, location, and pathology affect choices', 'Records needed for EMR, ESD, or surgical review', 'Why high-grade lesions need timely pathway clarity']
      },
      specialists: { zh: ['消化内镜', '胃肠外科', '病理科'], en: ['GI endoscopy', 'Colorectal surgery', 'Pathology'] }
    },
    stomach: {
      video: { zh: '胃息肉、早期胃癌和高级别病变：ESD、手术或观察', en: 'Gastric polyps, early gastric cancer, and high-grade lesions: ESD, surgery, or surveillance' },
      image: 'assets/conditions/stomach.png',
      points: {
        zh: ['胃镜图片和病理报告如何一起看', 'ESD 适应证通常需要哪些信息', '复杂息肉和早癌来华评估的准备方向'],
        en: ['How gastroscopy images and pathology are reviewed together', 'What information usually supports ESD suitability review', 'How to prepare for China review of complex polyps or early cancer']
      },
      specialists: { zh: ['消化内镜', '胃肿瘤外科', '病理科'], en: ['GI endoscopy', 'Gastric oncology surgery', 'Pathology'] }
    }
  };
  return getFocusConditions().map((condition) => ({ ...condition, sourceId: condition.id, detail: detail[condition.id] }));
};

const ConditionsGrid = ({ lang, tr, setSelectedCondition, copy }) => (
  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
    {getFrontstageConditions().map((condition) => (
      <button
        key={condition.id}
        type="button"
        onClick={() => setSelectedCondition(condition)}
        className="home-condition-card min-w-0 text-left transition hover:-translate-y-0.5 hover:shadow-lift"
      >
        <div className="mb-4 flex items-start justify-between gap-3">
          <div className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl ${condition.tone === 'gold' ? 'gold-gradient text-sea-600' : condition.tone === 'sea' ? 'sea-gradient text-gold-300' : 'bg-marble-100 text-sea-400'}`}>
            <Icon name={condition.icon} size={21} />
          </div>
          <span className="font-mono-display text-[11px] text-marble-500">0{getFrontstageConditions().findIndex((item) => item.id === condition.id) + 1}</span>
        </div>
        <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} min-h-[54px] text-lg font-semibold leading-tight text-sea-500`}>{tr(condition.name)}</h3>
        <p className="mt-2 min-h-[92px] text-sm leading-relaxed text-sea-400/78">{tr(condition.short)}</p>
        <div className="mt-4 border-t hairline pt-4">
          <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{copy.documents}</div>
          <div className="flex flex-wrap gap-1.5">
            {condition.docs.slice(0, 3).map((doc) => <Pill key={doc.en} tone="marble">{tr(doc)}</Pill>)}
          </div>
        </div>
        <div className="mt-4 inline-flex items-center gap-1.5 text-[12px] font-medium text-gold-700">
          {lang === 'zh' ? '查看这类情况' : 'Review this concern'}
          <Icon name="arrow-right" size={13} />
        </div>
      </button>
    ))}
  </div>
);

const ConditionVisual = ({ lang, title, image, name }) => (
  <div className="condition-visual">
    <img src={image} alt={textOf(name, lang)} className="condition-visual-img" />
    <div className="condition-visual-shade" />
    <div className="condition-visual-caption">
      <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-200">{lang === 'zh' ? '资料解读方向' : 'Record review focus'}</div>
      <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-2 max-w-xl text-[24px] leading-tight text-white md:text-[26px]`}>{title}</h3>
    </div>
  </div>
);

const ConditionDetailSection = ({ lang, tr, condition, selectedConditionId, setSelectedCondition, go }) => {
  const conditions = getFrontstageConditions();
  const initialIndex = Math.max(0, conditions.findIndex((item) => item.id === selectedConditionId || item.id === condition.id));
  const [activeIndex, setActiveIndex] = React.useState(initialIndex);
  React.useEffect(() => {
    setActiveIndex(initialIndex);
  }, [initialIndex]);
  React.useEffect(() => {
    const timer = window.setInterval(() => {
      setActiveIndex((current) => {
        const next = (current + 1) % conditions.length;
        setSelectedCondition?.(conditions[next]);
        return next;
      });
    }, 6500);
    return () => window.clearInterval(timer);
  }, [conditions.length, setSelectedCondition]);
  const activeCondition = conditions[activeIndex] || conditions[0];
  const detail = activeCondition.detail;
  const showIndex = (nextIndex) => {
    const normalized = (nextIndex + conditions.length) % conditions.length;
    setActiveIndex(normalized);
    setSelectedCondition?.(conditions[normalized]);
  };
  return (
    <div className="condition-carousel">
      <SectionHeader
        eyebrow="Condition Guide"
        lang={lang}
        title={{ zh: '高频诊疗场景', en: 'High-frequency care scenarios' }}
        subtitle={{
          zh: '你可以先了解每类问题通常关注什么、需要准备哪些资料，再提交信息让服务团队进行初步判断。',
          en: 'Review what each scenario usually involves and what records are needed before submitting information for an initial team review.'
        }}
        right={(
          <div className="flex gap-2">
            <button type="button" className="carousel-arrow" onClick={() => showIndex(activeIndex - 1)} aria-label={lang === 'zh' ? '上一个场景' : 'Previous scenario'}>
              <Icon name="chevron-left" size={16} />
            </button>
            <button type="button" className="carousel-arrow" onClick={() => showIndex(activeIndex + 1)} aria-label={lang === 'zh' ? '下一个场景' : 'Next scenario'}>
              <Icon name="chevron-right" size={16} />
            </button>
          </div>
        )}
      />
      <Card padding="p-0" className="overflow-hidden">
        <div className="condition-carousel-tabs">
          {conditions.map((item, index) => (
            <button
              key={item.id}
              type="button"
              className={`condition-carousel-tab ${index === activeIndex ? 'is-active' : ''}`}
              onClick={() => showIndex(index)}
            >
              <span>{String(index + 1).padStart(2, '0')}</span>
              {tr(item.name)}
            </button>
          ))}
        </div>
        <div className="condition-detail-grid grid gap-6 p-5 lg:grid-cols-12 lg:p-7">
          <div className="lg:col-span-7">
            <ConditionVisual lang={lang} title={textOf(detail.video, lang)} image={detail.image} name={activeCondition.name} />
          </div>
          <div className="condition-detail-panel lg:col-span-5">
          <div className="mb-4 flex items-start justify-between gap-4">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{lang === 'zh' ? '重点看什么' : 'What to review'}</div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-[28px] leading-tight text-sea-500`}>{tr(activeCondition.name)}</h3>
            </div>
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl sea-gradient text-gold-300">
              <Icon name={activeCondition.icon} size={21} />
            </div>
          </div>
          <div className="space-y-3">
            {detail.points[lang].map((item) => (
              <div key={item} className="flex gap-3 rounded-2xl bg-marble-50 p-3.5 text-sm leading-relaxed text-sea-500 ring-1 hairline">
                <Icon name="check" size={15} className="mt-0.5 shrink-0 text-gold-600" />
                <span>{item}</span>
              </div>
            ))}
          </div>
          <div className="mt-5 border-t hairline pt-4">
            <div className="mb-3">
              <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{lang === 'zh' ? '通常需要资料' : 'Typical records'}</div>
              <div className="flex flex-wrap gap-2">
                {activeCondition.docs.slice(0, 4).map((doc) => <Pill key={doc.en} tone="marble">{tr(doc)}</Pill>)}
              </div>
            </div>
            <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{lang === 'zh' ? '可能涉及专科' : 'Specialist directions'}</div>
            <div className="flex flex-wrap gap-2">
              {detail.specialists[lang].map((item) => <Pill key={item} tone="sea">{item}</Pill>)}
            </div>
          </div>
          <Button icon="file-pen-line" onClick={() => go('intake.html')} className="mt-5">
            {lang === 'zh' ? '提交资料，先免费判断' : 'Submit records for free review'}
          </Button>
          </div>
        </div>
      </Card>
    </div>
  );
};

const HOSPITALS = [
  {
    id: 'pumch',
    name: { zh: '北京协和医院', en: 'Peking Union Medical College Hospital' },
    city: { zh: '北京', en: 'Beijing' },
    image: 'assets/hospitals/pumch.png',
    website: 'https://www.pumch.cn/',
    tag: { zh: '妇产、内分泌、风湿免疫、消化与疑难综合评估', en: 'Gynecology, endocrine, rheumatology, GI, and complex assessment' },
    focus: {
      zh: ['妇科肿瘤、复杂妇产和生殖相关问题', '内分泌代谢、甲状腺、风湿免疫与疑难病', '消化、呼吸、复杂症状和跨专科综合评估'],
      en: ['Gynecologic oncology, complex gynecology, and reproductive concerns', 'Endocrine-metabolic, thyroid, rheumatology, and rare diseases', 'GI, respiratory, complex symptoms, and cross-specialty assessment']
    },
    metrics: {
      zh: [
        { value: '29', label: '个国家临床重点专科', text: '适合承接多专科疑难病例的资料整理和问题清单设计。' },
        { value: '1921', label: '年创建', text: '长期代表中国头部综合医院的综合诊疗和医学训练体系。' }
      ],
      en: [
        { value: '29', label: 'national clinical key specialties', text: 'Supports multi-specialty case briefing and question-list design.' },
        { value: '1921', label: 'founded', text: 'A long-standing representative of China’s top comprehensive medical system.' }
      ]
    },
    note: {
      zh: '北京协和医院创建于 1921 年，是中国具有代表性的现代化综合三级甲等医院，适合用于说明中国头部综合医院在疑难复杂病情评估、多学科协作和专科资源整合方面的能力。',
      en: 'Founded in 1921, Peking Union Medical College Hospital is a leading comprehensive tertiary hospital in China and is useful for explaining complex-case assessment, multidisciplinary collaboration, and integrated specialty resources.'
    },
    pathway: {
      zh: '可用于疑难复杂病例、诊断不清、跨专科问题和多学科路径梳理。华医畅只协助资料整理和路径沟通，不承诺具体专家或号源。',
      en: 'Relevant for complex cases, unclear diagnoses, cross-specialty questions, and multidisciplinary pathway organization. HuaMed supports record organization and pathway communication, not specific doctor or appointment guarantees.'
    },
    records: {
      zh: ['病情时间线', '影像/病理/实验室报告', '既往治疗和用药记录', '最想确认的 3-5 个问题'],
      en: ['Case timeline', 'Imaging/pathology/lab reports', 'Prior treatment and medication history', 'Top 3-5 questions']
    }
  },
  {
    id: 'pla301',
    name: { zh: '中国人民解放军总医院（301 医院）', en: 'Chinese PLA General Hospital (301 Hospital)' },
    city: { zh: '北京', en: 'Beijing' },
    image: 'assets/hospitals/pla-301.png',
    website: 'https://www.301hospital.com.cn/',
    tag: { zh: '骨科、普外、消化、肾脏、神经与复杂手术评估', en: 'Orthopedics, general surgery, GI, kidney, neurology, and complex surgery' },
    focus: {
      zh: ['骨科关节、脊柱和运动损伤择期评估', '普外、消化、肾脏、肿瘤和复杂手术路径', '神经、心脑血管和多基础病综合评估'],
      en: ['Elective orthopedics, spine, and sports injury review', 'General surgery, GI, kidney, oncology, and complex surgical pathways', 'Neurology, cardio-cerebrovascular, and multi-comorbidity assessment']
    },
    metrics: {
      zh: [
        { value: '165', label: '个临床/医技科室', text: '覆盖复杂疾病所需的多专科资源。' },
        { value: '近9万', label: '例年手术量公开口径', text: '适合展示大型综合医院复杂手术承接能力。' }
      ],
      en: [
        { value: '165', label: 'clinical and technical departments', text: 'Broad multi-specialty resources for complex care.' },
        { value: 'nearly 90k', label: 'annual surgeries in public source', text: 'Shows large comprehensive surgical capacity.' }
      ]
    },
    note: {
      zh: '中国人民解放军总医院又称 301 医院，是大型现代化综合性医院，可用于展示中国综合医院在复杂疾病诊疗、重大手术和多专科资源整合方面的代表性能力。',
      en: 'Chinese PLA General Hospital, also known as 301 Hospital, is a large modern comprehensive hospital and illustrates China’s capacity for complex disease care, major surgery, and multi-specialty resource integration.'
    },
    pathway: {
      zh: '适合用于复杂手术评估、综合专科会诊、老年医学和来华检查住院流程的路径说明。实际安排需按医院正式流程推进。',
      en: 'Useful for complex surgery review, cross-specialty consultation, geriatric medicine, and China testing or admission pathways. Any arrangement follows formal hospital procedures.'
    },
    records: {
      zh: ['手术或住院建议', '近期影像和检查结果', '基础病和用药清单', '本地医生已给出的方案'],
      en: ['Surgery or admission advice', 'Recent imaging and test results', 'Comorbidities and medication list', 'Local doctor’s proposed plan']
    }
  },
  {
    id: 'fuwai',
    name: { zh: '中国医学科学院阜外医院', en: 'Fuwai Hospital, CAMS' },
    city: { zh: '北京', en: 'Beijing' },
    image: 'assets/hospitals/fuwai.png',
    website: 'https://www.fuwaihospital.org/',
    tag: { zh: '冠心病、瓣膜病、先心病、心律失常与心外科', en: 'Coronary, valve, congenital, arrhythmia, and cardiac surgery' },
    focus: {
      zh: ['冠脉狭窄、支架或搭桥方案二诊', '瓣膜病、先心病、心律失常和心衰方向', '心血管影像、术前评估和复杂心外科路径'],
      en: ['Coronary stenosis, stent, or bypass second opinion', 'Valve disease, congenital disease, arrhythmia, and heart failure', 'Cardiovascular imaging, pre-op review, and complex cardiac surgery pathway']
    },
    metrics: {
      zh: [
        { value: '近2万', label: '例年心血管外科手术', text: '公开资料显示其心外科手术量长期处于全球头部规模。' },
        { value: '5万余', label: '例年介入治疗', text: '适合冠脉、瓣膜和复杂心血管方案的路径咨询。' }
      ],
      en: [
        { value: 'nearly 20k', label: 'annual cardiovascular surgeries', text: 'Public materials show world-leading cardiac surgery volume.' },
        { value: '50k+', label: 'annual interventional procedures', text: 'Useful for coronary, valve, and complex cardiovascular pathway review.' }
      ]
    },
    note: {
      zh: '阜外医院是国家级三级甲等心血管病专科医院，也是国家心血管病中心所在地，适合展示中国心血管疾病诊疗、科研和术前评估方面的专科能力。',
      en: 'Fuwai Hospital is a national tertiary cardiovascular specialty hospital and the site of China’s National Center for Cardiovascular Diseases, representing specialty care, research, and preoperative assessment capacity.'
    },
    pathway: {
      zh: '适合冠脉狭窄、支架或搭桥方案二诊、瓣膜病和择期心血管评估路径。急性胸痛、卒中等情况应先在当地急诊处理。',
      en: 'Relevant for coronary stenosis, stent or bypass second opinions, valve disease, and elective cardiovascular review. Acute chest pain or stroke symptoms require local emergency care first.'
    },
    records: {
      zh: ['冠脉 CTA / 造影', '心超、心电图和动态心电', '既往支架/手术记录', '当地医生治疗建议'],
      en: ['Coronary CTA / angiography', 'Echo, ECG, Holter', 'Prior stent/surgery records', 'Local treatment recommendation']
    }
  },
  {
    id: 'ruijin',
    name: { zh: '上海交通大学医学院附属瑞金医院', en: 'Ruijin Hospital, Shanghai Jiao Tong University School of Medicine' },
    city: { zh: '上海', en: 'Shanghai' },
    image: 'assets/hospitals/ruijin.png',
    website: 'https://www.rjh.com.cn/',
    tag: { zh: '血液、内分泌代谢、甲状腺、胃肠胰腺与普外', en: 'Hematology, endocrine-metabolic, thyroid, GI-pancreas, and general surgery' },
    focus: {
      zh: ['血液病、血液肿瘤和移植相关评估', '糖尿病、甲状腺、肾上腺和代谢性疾病', '胃肠、胰腺、普外和消化复杂疾病'],
      en: ['Hematology, blood tumors, and transplant-related review', 'Diabetes, thyroid, adrenal, and metabolic diseases', 'GI, pancreas, general surgery, and complex digestive disease']
    },
    metrics: {
      zh: [
        { value: '24', label: '个国家临床重点专科', text: '覆盖血液、内分泌、烧伤、普外等多个强势方向。' },
        { value: '1907', label: '年创建', text: '上海代表性大型综合教学医院，兼具临床和转化医学平台。' }
      ],
      en: [
        { value: '24', label: 'national clinical key specialties', text: 'Covers hematology, endocrine, burns, general surgery, and more.' },
        { value: '1907', label: 'founded', text: 'A representative Shanghai teaching hospital with clinical and translational platforms.' }
      ]
    },
    note: {
      zh: '瑞金医院始建于 1907 年，是上海具有代表性的三级甲等大型综合性教学医院，以临床、教学、科研和转化医学能力见长。',
      en: 'Founded in 1907, Ruijin Hospital is a major tertiary teaching hospital in Shanghai known for clinical care, education, research, and translational medicine.'
    },
    pathway: {
      zh: '适合展示上海方向的复杂疾病、血液和内分泌代谢、消化外科、甲状腺和研究型医学资源。具体安排以正式流程和资料评估为准。',
      en: 'Relevant for Shanghai-based complex disease care, hematology, endocrine-metabolic disease, GI surgery, thyroid, and research-led medicine resources. Any arrangement depends on formal processes and record review.'
    },
    records: {
      zh: ['病理和免疫/分子检测', '血液或内分泌检验', '影像 / 内镜资料', '既往治疗和用药记录'],
      en: ['Pathology and immune/molecular tests', 'Hematology or endocrine labs', 'Imaging / endoscopy records', 'Prior treatment and medication history']
    }
  },
  {
    id: 'zhongshan-first',
    name: { zh: '中山大学附属第一医院', en: 'The First Affiliated Hospital, Sun Yat-sen University' },
    city: { zh: '广州', en: 'Guangzhou' },
    image: 'assets/hospitals/zhongshan-first.png',
    website: 'https://www.fahsysu.org.cn/',
    tag: { zh: '肝胆胰胃肠外科、器官移植、神经、妇产与肾内', en: 'HPB-GI surgery, transplant, neurology, gynecology, and nephrology' },
    focus: {
      zh: ['器官移植、普通外科、肝胆胰和胃肠外科', '神经、心血管、肾内、风湿免疫和呼吸重症', '妇产、生殖医学、医学影像、麻醉和重症医学'],
      en: ['Transplant, general surgery, HPB and GI surgery', 'Neurology, cardiovascular, nephrology, rheumatology, and respiratory critical care', 'Gynecology, reproductive medicine, imaging, anesthesia, and critical care']
    },
    metrics: {
      zh: [
        { value: '36', label: '个国家临床重点专科', text: '覆盖华南复杂外科、肾内、妇产、神经等多方向。' },
        { value: '5', label: '个国家重点学科', text: '适合华南方向复杂病例和多学科路径评估。' }
      ],
      en: [
        { value: '36', label: 'national clinical key specialties', text: 'Covers complex surgery, nephrology, gynecology, neurology, and more in South China.' },
        { value: '5', label: 'national key disciplines', text: 'Useful for South China complex case and multidisciplinary pathway review.' }
      ]
    },
    note: {
      zh: '中山一院始建于 1910 年，是华南地区具有代表性的三级甲等综合性医院，适合展示广州及华南地区疑难重症、复杂手术和多学科诊疗能力。',
      en: 'Founded in 1910, the First Affiliated Hospital of Sun Yat-sen University is a representative tertiary comprehensive hospital in South China, useful for explaining complex case, major surgery, and multidisciplinary care capacity.'
    },
    pathway: {
      zh: '适合用于华南方向的复杂外科、器官移植相关评估、妇产和肾内等专科路径说明。华医畅仅做路径协调和资料整理，不承诺医院结果。',
      en: 'Relevant for South China complex surgery, transplant-related assessment, gynecology, nephrology, and related specialty pathways. HuaMed provides pathway coordination and record organization, not hospital outcome guarantees.'
    },
    records: {
      zh: ['完整病史和手术建议', '影像、病理和检验资料', '移植/肾内/妇产相关专项资料', '基础病和用药清单'],
      en: ['Full history and surgery advice', 'Imaging, pathology, and lab records', 'Transplant/nephrology/gynecology-specific records', 'Comorbidities and medication list']
    }
  }
];

const CARE_PROCESS_STEPS = [
  {
    icon: 'upload-cloud',
    title: { zh: '提交病例资料', en: 'Submit medical records' },
    text: {
      zh: '上传既往病历、检查报告、影像、病理、用药记录和当地医生建议。',
      en: 'Upload prior records, test reports, imaging, pathology, medication history, and local doctor advice.'
    },
    output: { zh: '提交信息', en: 'Records submitted' },
    featured: true
  },
  {
    icon: 'languages',
    title: { zh: '病例整理与翻译', en: 'Case organization and translation' },
    text: {
      zh: '华医畅将零散资料整理成中国医生能够快速理解的病例摘要和关键问题。',
      en: 'HuaMed turns scattered records into a China-specialist-readable case brief and key questions.'
    },
    output: { zh: '病例摘要', en: 'Case brief' }
  },
  {
    icon: 'stethoscope',
    title: { zh: '中国专家二诊评估', en: 'China specialist second opinion' },
    text: {
      zh: '协调中国三甲医院相关专科专家进行远程二诊或方向判断。',
      en: 'Coordinate remote second opinion or directional judgment with relevant China tertiary-hospital specialist resources.'
    },
    output: { zh: '专家意见', en: 'Specialist view' }
  },
  {
    icon: 'search-check',
    title: { zh: '判断是否需要来华', en: 'Decide whether China travel is needed' },
    text: {
      zh: '根据专家意见，判断是否需要来中国进一步面诊、检查、住院或手术评估。',
      en: 'Use the specialist view to decide whether in-person consultation, testing, admission, or surgery assessment in China is needed.'
    },
    output: { zh: '来华判断', en: 'Travel fit' }
  },
  {
    icon: 'plane',
    title: { zh: '推进来华就医服务', en: 'Move into China care coordination' },
    text: {
      zh: '如适合来华，继续协助医院、科室、专家方向、检查安排、保险沟通和到院服务。',
      en: 'If China travel fits, continue with hospital, department, specialist direction, test scheduling, insurance communication, and on-site support.'
    },
    output: { zh: '执行服务', en: 'Care execution' }
  }
];

const ProcessPage = ({ lang, go }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Process"
      icon="route"
      title={lang === 'zh' ? '服务流程' : 'Service Process'}
      subtitle={lang === 'zh'
        ? '华医畅先判断资料和服务适配性，再进入二诊预评估或来华协调。流程强调清晰、边界和人工承接，不承诺医疗结果。'
        : 'HuaMed reviews records and service fit before specialist pre-assessment or China coordination. The process prioritizes clarity, boundaries, and human support without medical outcome promises.'}
    />
    <ProcessTimeline lang={lang} go={go} />
    <ProcessBoundaryGrid lang={lang} />
  </>
);

const SubmitFlowPage = ({ lang, go, onOpenIntake }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Custom Care Journey"
      icon="file-pen-line"
      variant="journey"
      heroImage="assets/page-heroes/care-journey.png"
      title={lang === 'zh' ? '定制你的中国就医旅程' : 'Customize your China care journey'}
      subtitle={lang === 'zh'
        ? '从中国专家二诊评估，到来华就医路径规划，再到医院预约、到院陪同、检查住院协调和诊后资料整理，华医畅为海外患者提供分阶段、可选择的中国就医服务。'
        : 'From China specialist second opinion to care-pathway planning, hospital appointment coordination, on-site accompaniment, testing and admission coordination, and post-visit record organization, HuaMed provides staged and selectable China care services for overseas patients.'}
    />
    <Card padding="p-6" className="journey-hero-followup">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <p className="max-w-3xl text-sm leading-8 text-sea-500">
          {lang === 'zh'
            ? '你可以先从专家二诊评估开始，判断是否值得来华；如果已经明确来华需求，可直接咨询全流程服务方案。'
            : 'You can start with specialist second opinion to decide whether China travel is worth it. If the need to travel is already clear, consult the end-to-end service plan directly.'}
        </p>
        <div className="flex flex-wrap gap-3">
          <Button icon="file-pen-line" onClick={() => onOpenIntake ? onOpenIntake() : go('intake.html?form=1')}>{lang === 'zh' ? '提交病例资料' : 'Submit records'}</Button>
          <Button variant="ghost" icon="receipt-text" onClick={() => document.getElementById('packages')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}>{lang === 'zh' ? '查看服务价格' : 'View pricing'}</Button>
        </div>
      </div>
    </Card>
    <ProcessTimeline lang={lang} go={go} onOpenIntake={onOpenIntake} />
    <PricingPlansSection lang={lang} go={go} onOpenIntake={onOpenIntake} compact />
    <InsuranceSupportSection lang={lang} />
    <OptionalServicesSection lang={lang} />
    <ProcessBoundaryGrid lang={lang} />
    <JourneyFAQSection lang={lang} />
    <JourneyFinalCta lang={lang} go={go} onOpenIntake={onOpenIntake} />
  </>
);

const ProcessTimeline = ({ lang, go, onOpenIntake }) => (
  <Card padding="p-6 md:p-8" className="stage8-process-card">
    <SectionHeader
      eyebrow="From Records to Pathway"
      lang={lang}
      title={{ zh: '从异常报告到可执行路径', en: 'From abnormal report to actionable pathway' }}
      subtitle={{
        zh: '每一步都有明确产出。客户不会看到内部评分或运营状态，只看到可理解的资料状态和下一步建议。',
        en: 'Each step has a clear output. Clients do not see internal scores or ops statuses, only understandable record status and next-step guidance.'
      }}
      right={<Button icon="send-horizontal" onClick={() => onOpenIntake ? onOpenIntake() : go('intake.html?form=1')}>{lang === 'zh' ? '提交信息' : 'Submit information'}</Button>}
    />
    <div className="stage8-process-timeline">
      {CARE_PROCESS_STEPS.map((step, index) => (
        <div key={step.title.en} className={`stage8-process-step ${step.featured ? 'is-featured' : ''}`}>
          <div className="stage8-process-marker">
            <Icon name={step.icon} size={18} />
          </div>
          <div className="stage8-process-body">
            <div className="mb-2 flex items-center justify-between gap-3">
              <span className="font-mono-display text-[11px] text-gold-700">{String(index + 1).padStart(2, '0')}</span>
              <Pill tone={step.featured || index < 2 ? 'gold' : index === 2 ? 'sea' : 'marble'}>{textOf(step.output, lang)}</Pill>
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-[22px] leading-tight text-sea-500`}>{textOf(step.title, lang)}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{textOf(step.text, lang)}</p>
          </div>
        </div>
      ))}
    </div>
  </Card>
);

const ProcessBoundaryGrid = ({ lang }) => {
  const items = [
    ['shield-alert', lang === 'zh' ? '不替代诊断' : 'Not diagnosis', lang === 'zh' ? '二诊预评估基于现有资料，不等同于线下面诊或正式诊疗结论。' : 'Pre-assessment is based on available records and is not equivalent to in-person diagnosis or treatment decision.'],
    ['badge-dollar-sign', lang === 'zh' ? '医疗费直接付医院' : 'Hospital fees paid directly', lang === 'zh' ? '华医畅只收服务费，不打包或代收医院检查、治疗、住院和手术费用。' : 'HuaMed charges service fees only and does not bundle hospital testing, treatment, admission, or surgery fees.'],
    ['ambulance', lang === 'zh' ? '急症本地优先' : 'Local emergency first', lang === 'zh' ? '急性胸痛、卒中、严重出血等情况应立即在当地急诊处理。' : 'Acute chest pain, stroke symptoms, severe bleeding, and similar cases require local emergency care first.'],
    ['message-circle', lang === 'zh' ? 'WhatsApp 人工承接' : 'WhatsApp human support', lang === 'zh' ? '提交资料后进入人工沟通，先确认资料和服务适配，再推进下一步。' : 'After submission, human support confirms record readiness and service fit before moving forward.']
  ];
  return (
    <section className="process-boundary-section">
      <SectionHeader
        eyebrow="Notice"
        lang={lang}
        title={{ zh: '服务边界', en: 'Service boundaries' }}
        subtitle={{
          zh: '华医畅提供的是来华就医咨询、病例整理、专家二诊协调、医院路径规划、陪同翻译和流程协助服务，不替代医院或医生作出诊断和治疗决策。',
          en: 'HuaMed provides China care consultation, case organization, specialist second-opinion coordination, hospital pathway planning, accompaniment, translation, and process support. It does not replace hospitals or physicians in diagnosis or treatment decisions.'
        }}
      />
      <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-4">
        {items.map(([icon, title, text]) => (
          <Card key={title} padding="p-5">
            <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl sea-gradient text-gold-300">
              <Icon name={icon} size={19} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
          </Card>
        ))}
      </div>
      <ComplianceNotice
        lang={lang}
        text={{
          zh: '服务费不包含医院收取的门诊、检查、影像、药品、住院、手术等医疗费用。华医畅不承诺具体医院接诊结果、专家号源、床位安排、手术排期、保险批准结果或治疗效果。',
          en: 'Service fees do not include hospital outpatient, testing, imaging, medication, admission, surgery, or other medical fees. HuaMed does not promise hospital acceptance, specialist appointment slots, beds, surgery timing, insurance approval, or treatment outcomes.'
        }}
      />
    </section>
  );
};

const PageIntro = ({ lang, eyebrow, title, subtitle, icon = 'sparkles', variant = 'default', heroImage = '' }) => (
  <section className={`page-intro relative overflow-hidden rounded-4xl p-7 text-marble-100 shadow-deep md:p-10 ${variant !== 'default' ? `is-${variant}` : ''} ${heroImage ? 'has-hero-image' : ''}`}>
    <HeroFilm />
    <img src="assets/brand/icon.png" alt="" className="page-intro-watermark" aria-hidden="true" />
    {heroImage && (
      <div className="page-intro-image-wrap" aria-hidden="true">
        <img src={heroImage} alt="" className="page-intro-image" />
      </div>
    )}
    <div className="relative z-[2] max-w-3xl">
      <div className="mb-4 inline-flex items-center gap-2 rounded-full bg-white/10 px-3 py-2 ring-1 ring-white/14">
        <Icon name={icon} size={14} className="text-gold-300" />
        <span className="text-[11px] font-medium uppercase tracking-[0.22em] text-gold-200">{eyebrow}</span>
      </div>
      <h1 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-[38px] font-semibold leading-tight text-white md:text-[52px]`}>{title}</h1>
      <p className="mt-4 max-w-2xl text-sm leading-8 text-marble-100/76 md:text-[15px]">{subtitle}</p>
    </div>
  </section>
);

const ComplianceNotice = ({ lang, text, icon = 'shield-alert' }) => (
  <div className="compliance-notice">
    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-gold-50 text-gold-700 ring-1 ring-gold-100">
      <Icon name={icon} size={18} />
    </div>
    <p className="text-sm leading-7 text-sea-500">{textOf(text, lang)}</p>
  </div>
);

const TeamPage = ({ lang, go }) => {
  const expertGroups = [
    {
      icon: 'scan-heart',
      title: { zh: '胸外 / 肺结节方向专家组', en: 'Thoracic / lung nodule specialist group' },
      fit: { zh: '肺结节、早期肺癌、纵隔肿瘤、食管相关问题', en: 'Lung nodules, early lung cancer, mediastinal tumors, esophageal concerns' },
      departments: { zh: ['胸外科', '影像科', '呼吸专科', '病理科'], en: ['Thoracic surgery', 'Radiology', 'Respiratory medicine', 'Pathology'] },
      records: { zh: ['薄层 CT 原片', '既往 CT 对比', '报告和吸烟/家族史'], en: ['Thin-slice CT files', 'Prior CT comparison', 'Reports and smoking/family history'] },
      boundary: { zh: '可帮助整理问题清单和二诊方向，围绕病情匹配适合的医学资源。', en: 'Supports question lists and second-opinion direction while matching suitable medical resources.' }
    },
    {
      icon: 'heart-pulse',
      title: { zh: '心血管二诊方向专家组', en: 'Cardiovascular second-opinion group' },
      fit: { zh: '冠脉狭窄、支架/搭桥选择、瓣膜病、心律失常', en: 'Coronary stenosis, stent/bypass decisions, valve disease, arrhythmia' },
      departments: { zh: ['心内科', '心外科', '介入治疗', '心血管影像'], en: ['Cardiology', 'Cardiac surgery', 'Intervention', 'Cardiovascular imaging'] },
      records: { zh: ['冠脉 CTA / 造影', '心超和心电图', '本地治疗建议'], en: ['Coronary CTA / angiography', 'Echo and ECG', 'Local recommendation'] },
      boundary: { zh: '急性胸痛等急症仍以当地急诊为先。', en: 'Acute chest pain and emergencies still require local emergency care first.' }
    },
    {
      icon: 'microscope',
      title: { zh: '消化内镜与胃肠肿瘤方向专家组', en: 'GI endoscopy and GI oncology group' },
      fit: { zh: '胃息肉、结直肠息肉、早癌、高级别病变、胰胆复杂问题', en: 'Gastric/colorectal polyps, early cancer, high-grade lesions, pancreaticobiliary issues' },
      departments: { zh: ['消化内镜', '胃肠外科', '肿瘤科', '病理科'], en: ['GI endoscopy', 'GI surgery', 'Oncology', 'Pathology'] },
      records: { zh: ['内镜图片/视频', '病理报告', '既往切除或手术记录'], en: ['Endoscopy images/video', 'Pathology report', 'Prior resection or surgery records'] },
      boundary: { zh: '先判断资料是否足够支持 ESD、手术或随访路径讨论。', en: 'First checks whether records support ESD, surgery, or surveillance discussion.' }
    },
    {
      icon: 'activity',
      title: { zh: '甲状腺 / 乳腺 / 内分泌方向专家组', en: 'Thyroid / breast / endocrine group' },
      fit: { zh: '甲状腺结节、乳腺结节、内分泌代谢和相关肿瘤问题', en: 'Thyroid nodules, breast nodules, endocrine-metabolic and related tumor concerns' },
      departments: { zh: ['甲状腺外科', '乳腺外科', '超声科', '内分泌科'], en: ['Thyroid surgery', 'Breast surgery', 'Ultrasound', 'Endocrinology'] },
      records: { zh: ['超声分级', '穿刺/病理', '激素和相关检验'], en: ['Ultrasound category', 'FNA/pathology', 'Hormone and related labs'] },
      boundary: { zh: '帮助减少过度治疗或延误治疗的路径不确定性。', en: 'Helps reduce pathway uncertainty around overtreatment or delayed treatment.' }
    }
  ];
  const cards = [
    ['graduation-cap', lang === 'zh' ? '高端医生团队背景' : 'Senior medical team background', lang === 'zh' ? '核心服务能力来自真实高端医生团队、三甲训练经历和医学科研背景。' : 'Service capability is grounded in real senior medical teams, top-hospital training, and clinical research.'],
    ['file-search', lang === 'zh' ? '病例整理能力' : 'Case-briefing capability', lang === 'zh' ? '把客户分散的报告、影像、病理和本地建议整理成医生能快速阅读的问题清单。' : 'Turns scattered reports, imaging, pathology, and local advice into specialist-readable questions.'],
    ['stethoscope', lang === 'zh' ? '合作专家资源' : 'Partner specialist resources', lang === 'zh' ? '基于客户病情和资料完整度，匹配适合的医学方向与专家资源。' : 'Based on each client condition and available records, HuaMed helps match suitable medical directions and specialist resources.'],
    ['headphones', lang === 'zh' ? '全流程服务支持' : 'End-to-end service support', lang === 'zh' ? '包含全程病例收集整理与翻译、中国就医陪同、接送安排等服务支持，协助用户及家属完成从资料准备到来华就医执行的关键环节。' : 'Includes record collection and organization, translation, China visit accompaniment, transfer coordination, and key support from record preparation through care execution.']
  ];
  const roles = [
    ['users-round', lang === 'zh' ? '客户家庭' : 'Family', lang === 'zh' ? '提供已有资料和核心困惑，参与下一步路径选择。' : 'Shares available records and main concerns, then participates in pathway decisions.'],
    ['clipboard-check', lang === 'zh' ? '华医畅运营' : 'HuaMed ops', lang === 'zh' ? '负责初筛、病例摘要、资料缺口、WhatsApp 沟通和边界说明。' : 'Handles triage, case briefs, record gaps, WhatsApp support, and boundary explanations.'],
    ['stethoscope', lang === 'zh' ? '专科医生方向' : 'Specialist direction', lang === 'zh' ? '在资料足够时围绕问题清单做资料层面的二诊预评估。' : 'Reviews the case brief and questions when records are sufficient for pre-assessment.'],
    ['building-2', lang === 'zh' ? '医院路径资源' : 'Hospital pathway resources', lang === 'zh' ? '来华适配后，再围绕门诊、检查、住院和院内沟通做协调。' : 'When a China visit fits, coordination focuses on outpatient, testing, admission, and hospital communication.']
  ];
  return (
    <>
      <PageIntro
        lang={lang}
        eyebrow="Team"
        icon="users-round"
        variant="team"
        heroImage="assets/page-heroes/team.png"
        title={lang === 'zh' ? '服务团队' : 'Service Team'}
        subtitle={lang === 'zh' ? '把复杂医疗资料，整理成可沟通、可判断、可推进的来华就医路径。华医畅不简单承诺某一位医生，而是先判断资料、方向和服务适配性。' : 'We turn complex medical records into a China care pathway that can be discussed, judged, and coordinated. HuaMed does not simply promise a named doctor; it reviews records, direction, and service fit first.'}
      />
      <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-4">
        {cards.map(([icon, title, text]) => (
          <Card key={title} padding="p-6">
            <div className="mb-5 flex h-12 w-12 items-center justify-center rounded-2xl sea-gradient text-gold-300">
              <Icon name={icon} size={21} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl text-sea-500`}>{title}</h3>
            <p className="mt-3 text-sm leading-relaxed text-sea-400/78">{text}</p>
          </Card>
        ))}
      </div>
      <MedicalBackgroundSection lang={lang} />
      <Card padding="p-7">
        <SectionHeader
          eyebrow="Partner Hospital Specialist Groups"
          lang={lang}
          title={{ zh: '合作知名医院专家组', en: 'Specialist groups from leading partner hospitals' }}
          subtitle={{
            zh: '华医畅合作专家资源覆盖协和医院、301 医院、阜外医院、北大国际医院、瑞金医院等知名三甲医院相关方向专家，可围绕客户病情和资料完整度匹配适合的医学方向与专家资源。',
            en: "HuaMed's partner specialist resources cover relevant experts from leading tertiary hospitals, including Peking Union Medical College Hospital, Chinese PLA General Hospital (301 Hospital), Fuwai Hospital, Peking University International Hospital, Ruijin Hospital, and others. Based on each client's condition and available records, HuaMed helps match suitable medical directions and specialist resources."
          }}
        />
        <div className="expert-group-grid">
          {expertGroups.map((group) => (
            <div key={group.title.en} className="expert-group-card">
              <div className="mb-4 flex items-start justify-between gap-3">
                <span className="flex h-12 w-12 items-center justify-center rounded-2xl sea-gradient text-gold-300">
                  <Icon name={group.icon} size={21} />
                </span>
              </div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl leading-tight text-sea-500`}>{textOf(group.title, lang)}</h3>
              <p className="mt-3 text-sm leading-relaxed text-sea-400/78">{textOf(group.fit, lang)}</p>
              <div className="mt-4 flex flex-wrap gap-2">
                {group.departments[lang].map((item) => <Pill key={item} tone="marble">{item}</Pill>)}
              </div>
              <div className="mt-4 rounded-2xl bg-white p-4 text-sm leading-relaxed text-sea-500 ring-1 hairline">
                <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.18em] text-gold-700">{lang === 'zh' ? '建议资料' : 'Suggested records'}</div>
                {group.records[lang].join(' / ')}
              </div>
              <p className="mt-3 text-[12px] leading-relaxed text-sea-400/70">{textOf(group.boundary, lang)}</p>
            </div>
          ))}
        </div>
      </Card>
      <Card padding="p-7">
        <SectionHeader
          eyebrow="Collaboration Model"
          lang={lang}
          title={{ zh: '从海外病例到中国专家问题清单', en: 'From overseas records to specialist questions' }}
          subtitle={{
            zh: '团队页先呈现协作模型，而不是承诺具体医生资源：客户资料先进入运营整理，再判断是否适合进一步二诊或来华路径协调。',
            en: 'The page presents a collaboration model instead of promising specific doctor resources: records are organized first, then fit for second opinion or China coordination is reviewed.'
          }}
          right={<Button icon="message-circle" onClick={() => go('intake.html')}>{lang === 'zh' ? '咨询服务团队' : 'Consult the team'}</Button>}
        />
        <div className="stage8-role-grid">
          {roles.map(([icon, title, text], index) => (
            <div key={title} className="stage8-role-card">
              <div className="mb-4 flex items-center justify-between">
                <span className="flex h-10 w-10 items-center justify-center rounded-2xl bg-marble-100 text-sea-500">
                  <Icon name={icon} size={17} />
                </span>
                <span className="font-mono-display text-[11px] text-gold-700">{String(index + 1).padStart(2, '0')}</span>
              </div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
              <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
            </div>
          ))}
        </div>
        <div className="mt-6 rounded-3xl bg-gold-50/80 p-5 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-100">
          <div className="mb-2 flex items-center gap-2 font-semibold text-gold-700">
            <Icon name="shield-alert" size={15} />
            {lang === 'zh' ? '展示边界' : 'Display boundary'}
          </div>
          {lang === 'zh'
            ? '当前团队页不公开未授权医生姓名，不暗示合作医院保证预约，也不承诺床位、手术日期或治疗结果。'
            : 'This page does not publish unauthorized doctor names, imply guaranteed hospital appointments, or promise beds, surgery dates, or outcomes.'}
        </div>
      </Card>
    </>
  );
};

const MedicalBackgroundSection = ({ lang }) => {
  const items = [
    ['search-check', lang === 'zh' ? '医学判断前置' : 'Medical judgment comes first', lang === 'zh' ? '来华前先整理病历、检查报告、影像资料和本地医生建议，判断是否适合二诊或来华路径。' : 'Before China travel, records, reports, imaging, and local advice are organized to judge whether second opinion or a China pathway fits.'],
    ['landmark', lang === 'zh' ? '熟悉中国三甲体系' : 'China tertiary-system fluency', lang === 'zh' ? '理解中国公立三甲医院、重点专科、特需门诊、国际医疗部和专家会诊流程。' : 'Understands public tertiary hospitals, key specialties, VIP clinics, international departments, and specialist consultation flow in China.'],
    ['languages', lang === 'zh' ? '病例整理与翻译' : 'Case organization and translation', lang === 'zh' ? '将跨语言、跨医院、跨时间线的资料整理成中国医生可读的病例摘要。' : 'Turns cross-language, cross-hospital, and cross-timeline records into China-specialist-readable case briefs.'],
    ['headphones', lang === 'zh' ? '全流程服务支持' : 'End-to-end support', lang === 'zh' ? '覆盖资料准备、医院沟通、到院陪同、检查流程、保险沟通和诊后资料整理。' : 'Covers record preparation, hospital communication, on-site accompaniment, testing flow, insurance communication, and post-visit record organization.'],
    ['shield-alert', lang === 'zh' ? '服务边界清晰' : 'Clear service boundaries', lang === 'zh' ? '不替代医院诊断，不承诺疗效、号源、床位、手术或保险批准结果。' : 'Does not replace hospital diagnosis or promise outcomes, appointment slots, beds, surgery, or insurance approval.']
  ];
  return (
    <Card padding="p-7" className="medical-background-card">
      <SectionHeader
        eyebrow="Medical Background"
        lang={lang}
        title={{ zh: '为什么医学背景对来华就医服务很重要？', en: 'Why medical background matters for China care services' }}
        subtitle={{
          zh: '海外患者来中国就医，不只是需要翻译和陪同，更需要在来华前把零散病例、影像、检查和当地医生建议整理成中国医生能够快速理解的病例信息。华医畅团队结合医学专家背景、三甲医院体系理解和服务运营经验，帮助用户先判断方向，再推进合适的就医路径。',
          en: 'China care for overseas patients requires more than translation and accompaniment. Before travel, scattered records, imaging, tests, and local advice must be organized into information Chinese doctors can read quickly. HuaMed combines medical-specialist background, China tertiary-system understanding, and service operations experience to clarify direction before moving into the right pathway.'
        }}
      />
      <div className="medical-background-grid">
        {items.map(([icon, title, text]) => (
          <div key={title} className="rounded-3xl bg-white/76 p-5 ring-1 hairline">
            <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl sea-gradient text-gold-300">
              <Icon name={icon} size={19} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
          </div>
        ))}
      </div>
    </Card>
  );
};

const HospitalsPage = ({ lang, go }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Hospitals"
      icon="building-2"
      variant="hospitals"
      heroImage="assets/page-heroes/hospitals.png"
      title={lang === 'zh' ? '了解中国医疗服务体系' : 'Understanding China’s Medical System'}
      subtitle={lang === 'zh' ? '帮助海外家庭先理解中国顶级三甲医院、重点科室和就医路径，再判断是否需要专家二次诊疗、体检或来华面诊协调。' : 'Helping overseas families understand top tertiary hospitals, specialty directions, and care pathways in China before deciding on specialist second opinion, checkups, or China visit coordination.'}
    />
    <HospitalsSection lang={lang} go={go} />
  </>
);

const MedicalSystemPage = ({ lang, go }) => {
  const [activeRank, setActiveRank] = React.useState('lung');
  const sections = [
    ['building-2', lang === 'zh' ? '优质资源集中在头部三甲' : 'Top resources concentrate in leading tertiary hospitals', lang === 'zh' ? '中国疑难重症、复杂手术、高难度检查和重点专科资源，往往集中在北京、上海、广州等城市的头部综合医院和国家级专科医院。' : 'Complex cases, major surgery, advanced testing, and leading specialties are often concentrated in top comprehensive and national specialty hospitals in Beijing, Shanghai, Guangzhou, and other major cities.'],
    ['route', lang === 'zh' ? '先选医院类型，再选科室方向' : 'Choose hospital type before department direction', lang === 'zh' ? '同一个病种可能涉及综合医院、专科医院、国际医疗部、特需门诊或多学科会诊。先把方向选对，能减少无效就诊和重复检查。' : 'The same condition may involve a comprehensive hospital, specialty hospital, international department, VIP clinic, or multidisciplinary review. Correct direction reduces wasted visits and repeated tests.'],
    ['file-search', lang === 'zh' ? '资料完整度决定沟通效率' : 'Record readiness drives efficiency', lang === 'zh' ? '报告、影像原片、病理、内镜资料和本地医生建议越完整，中国医生越容易快速判断是否适合二诊、面诊或来华路径。' : 'Complete reports, imaging files, pathology, endoscopy records, and local recommendations help Chinese doctors assess second opinion, in-person review, or China visit fit faster.']
  ];
  const rankItems = lang === 'zh'
    ? ['综合医院排行榜用于理解头部医院分布', '专科声誉榜用于理解胸外、肿瘤、妇产、消化等专科能力', '榜单只做参考，不等于任何医院、专家或号源承诺']
    : ['General rankings help understand leading hospital distribution', 'Specialty reputation rankings help map thoracic, oncology, gynecology, GI, and other strengths', 'Rankings are references only and do not imply hospital, doctor, or appointment guarantees'];
  const rankingGroups = {
    lung: {
      label: { zh: '肺结节 / 胸外科', en: 'Lung / thoracic surgery' },
      source: { zh: '复旦专科声誉榜 · 胸外科', en: 'Fudan specialty reputation · Thoracic surgery' },
      rows: [
        ['中国医学科学院肿瘤医院', '北京', '国家癌症中心，胸部肿瘤外科方向'],
        ['上海市肺科医院', '上海', '肺部疾病与胸外科专科资源'],
        ['上海市胸科医院', '上海', '胸部疾病、肺结节和肺癌诊疗方向'],
        ['四川大学华西医院', '成都', '综合三甲，多学科复杂病例能力'],
        ['广州医科大学附属第一医院', '广州', '呼吸与胸部疾病优势方向'],
        ['北京大学人民医院', '北京', '综合三甲，胸外科与多专科协作'],
        ['复旦大学附属中山医院', '上海', '综合三甲，胸外和心肺相关资源'],
        ['空军军医大学唐都医院', '西安', '胸外科与复杂手术方向'],
        ['中山大学肿瘤防治中心', '广州', '肿瘤专科医院，胸部肿瘤方向'],
        ['天津医科大学肿瘤医院', '天津', '肿瘤专科医院，胸部肿瘤方向']
      ]
    },
    oncology: {
      label: { zh: '肿瘤综合方向', en: 'Oncology' },
      source: { zh: '复旦专科声誉榜 · 肿瘤学', en: 'Fudan specialty reputation · Oncology' },
      rows: [
        ['中国医学科学院肿瘤医院', '北京', '国家癌症中心，肿瘤综合诊疗'],
        ['中山大学肿瘤防治中心', '广州', '华南肿瘤专科资源'],
        ['复旦大学附属肿瘤医院', '上海', '肿瘤专科医院，多癌种方向'],
        ['天津医科大学肿瘤医院', '天津', '肿瘤专科医院'],
        ['北京大学肿瘤医院', '北京', '肿瘤专科医院'],
        ['山东省肿瘤医院', '济南', '肿瘤专科资源'],
        ['浙江省肿瘤医院', '杭州', '肿瘤专科资源'],
        ['江苏省肿瘤医院', '南京', '肿瘤专科资源'],
        ['四川大学华西医院', '成都', '综合三甲，多学科肿瘤方向'],
        ['哈尔滨医科大学附属肿瘤医院', '哈尔滨', '肿瘤专科资源']
      ]
    },
    digestive: {
      label: { zh: '胃肠 / 消化内镜', en: 'GI / endoscopy' },
      source: { zh: '复旦专科声誉榜 · 消化病', en: 'Fudan specialty reputation · Gastroenterology' },
      rows: [
        ['上海交通大学医学院附属仁济医院', '上海', '消化病与内镜方向'],
        ['空军军医大学西京医院', '西安', '消化病和复杂病例方向'],
        ['北京协和医院', '北京', '综合三甲，疑难消化病方向'],
        ['海军军医大学第一附属医院（长海医院）', '上海', '消化内镜与消化病方向'],
        ['四川大学华西医院', '成都', '综合三甲，消化疑难病例方向'],
        ['中国人民解放军总医院', '北京', '综合三甲，多专科协作'],
        ['南方医科大学南方医院', '广州', '消化病方向'],
        ['中山大学附属第一医院', '广州', '综合三甲，消化与胃肠外科协作'],
        ['浙江大学医学院附属第一医院', '杭州', '综合三甲，消化病方向'],
        ['复旦大学附属中山医院', '上海', '综合三甲，消化与外科协作']
      ]
    },
    cardiovascular: {
      label: { zh: '心血管方向', en: 'Cardiovascular' },
      source: { zh: '复旦专科声誉榜 · 心血管病', en: 'Fudan specialty reputation · Cardiovascular disease' },
      rows: [
        ['中国医学科学院阜外医院', '北京', '国家心血管病中心'],
        ['复旦大学附属中山医院', '上海', '心血管综合实力方向'],
        ['首都医科大学附属北京安贞医院', '北京', '心血管专科资源'],
        ['广东省人民医院', '广州', '心血管病方向'],
        ['北部战区总医院', '沈阳', '心血管方向'],
        ['浙江大学医学院附属第二医院', '杭州', '心血管方向'],
        ['哈尔滨医科大学附属第二医院', '哈尔滨', '心血管方向'],
        ['四川大学华西医院', '成都', '综合三甲，心血管方向'],
        ['上海交通大学医学院附属瑞金医院', '上海', '综合三甲，心血管方向'],
        ['武汉亚洲心脏病医院', '武汉', '心血管专科资源']
      ]
    },
    breastThyroid: {
      label: { zh: '乳腺 / 甲状腺', en: 'Breast / thyroid' },
      source: { zh: '结合肿瘤学、普外科和内分泌方向参考', en: 'Reference across oncology, general surgery, and endocrinology' },
      rows: [
        ['复旦大学附属肿瘤医院', '上海', '乳腺肿瘤、甲状腺肿瘤相关方向'],
        ['中国医学科学院肿瘤医院', '北京', '肿瘤专科医院，多癌种方向'],
        ['中山大学肿瘤防治中心', '广州', '肿瘤专科医院'],
        ['北京大学肿瘤医院', '北京', '肿瘤专科医院'],
        ['天津医科大学肿瘤医院', '天津', '肿瘤专科医院'],
        ['北京协和医院', '北京', '内分泌、甲状腺和疑难综合评估'],
        ['上海交通大学医学院附属瑞金医院', '上海', '内分泌代谢与综合外科协作'],
        ['四川大学华西医院', '成都', '综合三甲，多学科肿瘤方向'],
        ['浙江大学医学院附属第一医院', '杭州', '综合三甲，肿瘤与外科方向'],
        ['中山大学附属第一医院', '广州', '综合三甲，外科与多学科协作']
      ]
    }
  };
  const activeRankGroup = rankingGroups[activeRank] || rankingGroups.lung;
  return (
    <>
      <PageIntro
        lang={lang}
        eyebrow="Medical System"
        icon="landmark"
        title={lang === 'zh' ? '中国医疗服务体系与顶级医疗资源' : 'China Medical System and Top Medical Resources'}
        subtitle={lang === 'zh'
          ? '来华就医的难点不是只找到一家医院，而是判断城市、医院类型、科室方向、资料完整度和正式流程是否适合当前问题。'
          : 'The hard part of China care is not finding a hospital, but matching city, hospital type, department direction, record readiness, and formal process to the case.'}
      />
      <div className="medical-system-grid">
        {sections.map(([icon, title, text]) => (
          <Card key={title} padding="p-6">
            <div className="mb-5 flex h-12 w-12 items-center justify-center rounded-2xl gold-gradient text-sea-600">
              <Icon name={icon} size={21} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl text-sea-500`}>{title}</h3>
            <p className="mt-3 text-sm leading-8 text-sea-400/80">{text}</p>
          </Card>
        ))}
      </div>
      <Card padding="p-7 md:p-10" className="medical-system-landing">
        <div className="grid gap-8 lg:grid-cols-12">
          <div className="lg:col-span-7">
            <SectionHeader
              eyebrow="How to Read the System"
              lang={lang}
              title={{ zh: '海外家庭需要先把路径看清楚', en: 'Families need pathway clarity first' }}
              subtitle={{
                zh: '华医畅会先把客户已有资料整理成医生能快速理解的病例摘要，再结合病种、城市、医院和专科方向，判断是否适合专家二诊、面诊检查或来华择期诊疗。',
                en: 'HuaMed first turns existing records into a specialist-readable case brief, then reviews condition, city, hospital, and specialty direction before recommending second opinion, in-person review, or elective China care.'
              }}
            />
            <div className="space-y-4 text-sm leading-8 text-sea-500">
              <p>{lang === 'zh' ? '中国头部三甲医院的优势，通常体现在高病例量、高复杂度、多专科协作和重点平台能力。对于海外患者，真正关键的是把“我该去哪家医院”进一步拆成“我该看哪个科室、需要什么资料、是否值得来华、是否先做二诊”。' : 'The strengths of leading Chinese tertiary hospitals are usually reflected in high case volume, complexity, multidisciplinary collaboration, and key clinical platforms. For overseas patients, the real question is which department, what records, whether China travel is worth it, and whether second opinion should come first.'}</p>
              <p>{lang === 'zh' ? '复旦版中国医院及专科声誉排行榜可作为理解医院和专科分布的参考。它不能替代正式就医流程，也不代表华医畅承诺可直接安排对应医院、专家、号源或床位。' : 'The Fudan hospital and specialty reputation rankings can be used as references to understand hospital and specialty distribution. They do not replace formal medical processes or imply that HuaMed can directly arrange a hospital, doctor, appointment, or bed.'}</p>
            </div>
            <div className="mt-6 flex flex-wrap gap-3">
              <Button icon="building-2" onClick={() => go('hospitals.html')}>{lang === 'zh' ? '查看重点医院参考' : 'View hospital references'}</Button>
              <a href="https://rank.cn-healthcare.com/fudan/national-general" target="_blank" rel="noreferrer" className="inline-flex h-11 items-center justify-center gap-2 rounded-2xl bg-white px-5 text-sm font-medium text-sea-500 ring-1 hairline transition hover:-translate-y-[1px] hover:ring-gold-300">
                <Icon name="external-link" size={16} />
                {lang === 'zh' ? '复旦榜单参考' : 'Fudan ranking reference'}
              </a>
            </div>
          </div>
          <div className="lg:col-span-5">
            <div className="medical-system-visual">
              <div className="hero-film-grid" />
              <div className="relative z-[1] mt-auto">
                <div className="mb-3 text-[10px] font-medium uppercase tracking-[0.22em] text-gold-300">{lang === 'zh' ? '图片位置预留' : 'Image placeholder'}</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-3xl text-white`}>{lang === 'zh' ? '医院、专科与资料路径' : 'Hospitals, specialties, and records'}</h3>
              </div>
            </div>
          </div>
        </div>
      </Card>
      <ComplianceNotice
        lang={lang}
        icon="book-open-check"
        text={{
          zh: '复旦版中国医院排行榜可作为理解中国医院综合实力和专科声誉的参考，但不应被理解为就医结果承诺。具体医院、科室和专家是否适合某位患者，需要结合病种、资料完整度、医疗指征、来华时间和医院正式流程综合判断。',
          en: 'The Fudan China hospital rankings can be used as a reference for understanding overall strength and specialty reputation, but should not be read as a care-outcome promise. Whether a hospital, department, or specialist direction fits a patient depends on condition, record completeness, medical indication, travel timing, and formal hospital process.'
        }}
      />
      <Card padding="p-7" className="fudan-ranking-card">
        <SectionHeader
          eyebrow="Fudan Ranking Reference"
          lang={lang}
          title={{ zh: '按病种方向查看榜单参考', en: 'Ranking reference by condition direction' }}
          subtitle={{
            zh: '以下为 2023 年度复旦版中国医院专科声誉排行榜相关方向摘录，仅用于理解医院和专科分布，不代表华医畅承诺可安排对应医院、专家、号源或床位。',
            en: 'The following excerpts from the 2023 Fudan specialty reputation rankings help explain hospital and specialty distribution only; they do not imply HuaMed can arrange a listed hospital, doctor, appointment, or bed.'
          }}
        />
        <div className="grid gap-4 md:grid-cols-3">
          {rankItems.map((item, index) => (
            <div key={item} className="rounded-3xl bg-marble-50 p-5 ring-1 hairline">
              <div className="mb-3 font-mono-display text-[12px] text-gold-700">{String(index + 1).padStart(2, '0')}</div>
              <p className="text-sm leading-relaxed text-sea-500">{item}</p>
            </div>
          ))}
        </div>
        <div className="mt-6 flex flex-wrap gap-2">
          {Object.entries(rankingGroups).map(([id, group]) => (
            <button
              key={id}
              type="button"
              className={`condition-carousel-tab ${activeRank === id ? 'is-active' : ''}`}
              onClick={() => setActiveRank(id)}
            >
              {textOf(group.label, lang)}
            </button>
          ))}
        </div>
        <div className="mt-5 overflow-hidden rounded-3xl bg-white ring-1 hairline">
          <div className="flex flex-wrap items-center justify-between gap-3 border-b hairline px-5 py-4">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.18em] text-gold-600">{textOf(activeRankGroup.source, lang)}</div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{textOf(activeRankGroup.label, lang)}</h3>
            </div>
            <a href="https://rank.cn-healthcare.com/fudan/national-general" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1.5 text-[12px] font-semibold text-gold-700">
              {lang === 'zh' ? '查看公开来源' : 'Open public source'}
              <Icon name="external-link" size={13} />
            </a>
          </div>
          <div className="grid gap-0 md:grid-cols-2">
            {activeRankGroup.rows.map(([name, city, note], index) => (
              <div key={`${activeRank}-${name}`} className="flex gap-3 border-b border-r border-sea-400/8 p-4">
                <div className="font-mono-display text-[12px] text-gold-700">{String(index + 1).padStart(2, '0')}</div>
                <div className="min-w-0">
                  <div className="text-sm font-semibold text-sea-500">{name}</div>
                  <div className="mt-1 text-xs text-marble-500">{city} · {note}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </Card>
      <KnowledgeCenterCta lang={lang} go={go} />
    </>
  );
};

const KNOWLEDGE_CENTER_SECTIONS = [
  {
    icon: 'landmark',
    title: { zh: '中国医疗体系如何运作', en: 'How China’s medical system works' },
    text: {
      zh: '中国优质医疗资源高度集中在北京、上海、广州等城市的知名公立三甲医院，尤其是疑难重症、复杂手术、专科会诊和高难度检查，往往集中在头部综合医院和国家级专科医院。与欧美常见的家庭医生、社区医生、保险网络和逐级转诊体系不同，中国患者在很多情况下可以更直接地进入三甲医院专科门诊或专家门诊，但这也意味着医院选择、科室选择、专家方向、资料准备和就诊流程会更复杂。',
      en: 'High-quality medical resources in China are concentrated in leading public tertiary hospitals in Beijing, Shanghai, Guangzhou, and other major cities. Complex diseases, major surgery, specialist consultation, and advanced tests often concentrate in top comprehensive or national specialty hospitals. Unlike family-doctor, community-care, insurance-network, and stepwise referral systems common in Europe and the United States, patients in China can often reach tertiary specialty or expert clinics more directly, which also makes hospital choice, department choice, specialist direction, record preparation, and visit flow more complex.'
    }
  },
  {
    icon: 'building-2',
    title: { zh: '如何理解三甲医院、特需门诊和国际医疗部', en: 'Understanding tertiary hospitals, VIP clinics, and international departments' },
    text: {
      zh: '三甲医院代表中国医院等级评审中的较高等级，但不同医院在专科方向、专家资源、国际患者服务能力和就诊流程上存在差异。特需门诊和国际医疗部通常在预约、环境、沟通和支付方式上更适合部分海外患者，但具体可预约科室、医生和费用标准，需要以医院实际安排为准。',
      en: 'Tertiary Grade A hospitals represent a high level in China’s hospital grading system, but hospitals differ by specialty strength, specialist resources, international-patient service capability, and visit flow. VIP clinics and international departments are often more suitable for some overseas patients in appointment flow, environment, communication, and payment options, but available departments, doctors, and fees depend on each hospital’s actual arrangement.'
    }
  },
  {
    icon: 'book-open-check',
    title: { zh: '如何使用复旦版医院排行榜', en: 'How to use Fudan hospital rankings' },
    text: {
      zh: '复旦版中国医院排行榜可帮助海外用户初步理解中国医院综合实力和专科声誉分布，但排行榜不是个人就医路径的唯一依据。某位患者适合哪家医院、哪个科室、哪类专家，需要结合病种、病情阶段、检查资料、来华时间、医院流程和医疗指征综合判断。',
      en: 'The Fudan China hospital rankings help overseas users understand overall hospital strength and specialty reputation distribution, but rankings are not the only basis for an individual pathway. Which hospital, department, and specialist direction fits a patient depends on condition, disease stage, records, travel timing, hospital process, and medical indications.'
    }
  },
  {
    icon: 'file-stack',
    title: { zh: '来华前通常需要准备哪些资料', en: 'Records usually needed before China travel' },
    text: {
      zh: '通常建议准备既往病历、检查报告、影像资料、病理报告、用药记录、手术记录、当地医生建议、过敏史、保险信息和预计来华时间。复杂病种可能还需要补充原始影像文件、病理切片、基因检测报告或英文/中文医学摘要。',
      en: 'Usually prepare prior records, test reports, imaging, pathology reports, medication history, surgery records, local doctor advice, allergy history, insurance information, and expected China travel timing. Complex conditions may also need original imaging files, pathology slides, genomic reports, or English/Chinese medical summaries.'
    }
  },
  {
    icon: 'shield-check',
    title: { zh: '国际保险直付和预授权怎么理解', en: 'Understanding international insurance direct billing and pre-authorization' },
    text: {
      zh: '国际保险是否能在中国医院直付或预授权，取决于用户个人保单、医院政策、诊疗项目和保险公司审核结果。华医畅可以协助准备资料和沟通流程，但不能代表保险公司承诺批准、直付或赔付金额。',
      en: 'Whether international insurance can be used for direct billing or pre-authorization in China depends on the user’s policy, hospital policy, care item, and insurer review. HuaMed can help prepare materials and support communication, but cannot promise approval, direct billing, or reimbursement amount on behalf of insurers.'
    }
  },
  {
    icon: 'clipboard-check',
    title: { zh: '到院当天一般会发生什么', en: 'What usually happens on the hospital visit day' },
    text: {
      zh: '到院当天通常包括签到、挂号或确认预约、医生面诊、检查开具、缴费或保险窗口沟通、检查排期、报告获取和复诊安排。不同医院和科室流程不同，是否需要当天完成检查或多次往返，以医生面诊和医院实际安排为准。',
      en: 'A hospital visit day usually includes check-in, registration or appointment confirmation, doctor consultation, test orders, payment or insurance-window communication, test scheduling, report collection, and follow-up arrangement. Flow differs by hospital and department. Whether tests can be completed that day or require multiple visits depends on doctor consultation and hospital arrangement.'
    }
  },
  {
    icon: 'folder-check',
    title: { zh: '检查、报告和诊后资料如何获取', en: 'How tests, reports, and post-visit records are obtained' },
    text: {
      zh: '医生面诊后可能会根据病情建议 CT、MRI、超声、血液检查、病理会诊或其他检查。检查完成后，报告和影像资料通常需要按医院流程获取。对于需要回国复查或提交保险材料的用户，可在就诊后整理诊后报告、翻译盖章病例和复查资料包。',
      en: 'After consultation, doctors may recommend CT, MRI, ultrasound, blood tests, pathology consultation, or other tests. Reports and imaging files are usually obtained through hospital-specific processes after completion. Users who need return-home follow-up or insurance materials can organize post-visit reports, translated/stamped records, and follow-up packages after the visit.'
    }
  }
];

const KnowledgeCenterCta = ({ lang, go }) => (
  <Card padding="p-6" className="knowledge-center-cta">
    <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
      <div>
        <div className="font-mono-display text-[11px] uppercase tracking-[0.2em] text-gold-700">Knowledge Center</div>
        <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-2 text-3xl text-sea-500`}>{lang === 'zh' ? '来华就医知识中心' : 'China Care Knowledge Center'}</h3>
        <p className="mt-2 max-w-3xl text-sm leading-7 text-sea-400/78">{lang === 'zh' ? '系统了解中国医疗体系、三甲医院资源、专家二诊、国际保险和来华流程。' : 'Understand China’s medical system, tertiary-hospital resources, second opinion, international insurance, and China care flow.'}</p>
      </div>
      <Button icon="book-open-check" onClick={() => go('knowledge.html')}>{lang === 'zh' ? '打开知识中心' : 'Open knowledge center'}</Button>
    </div>
  </Card>
);

const KnowledgeCenterPage = ({ lang, go }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Knowledge Center"
      icon="book-open-check"
      title={lang === 'zh' ? '来华就医知识中心' : 'China Care Knowledge Center'}
      subtitle={lang === 'zh'
        ? '帮助海外患者理解中国医疗体系、三甲医院资源、专家二诊、国际保险和来华就医流程，减少信息差和跨语言沟通成本。'
        : 'Helping overseas patients understand China’s medical system, tertiary-hospital resources, specialist second opinion, international insurance, and China care flow, reducing information gaps and cross-language communication cost.'}
    />
    <div className="knowledge-center-grid">
      {KNOWLEDGE_CENTER_SECTIONS.map((section, index) => (
        <Card key={section.title.en} padding="p-6" className="knowledge-center-card">
          <div className="mb-4 flex items-start justify-between gap-4">
            <span className="flex h-12 w-12 items-center justify-center rounded-2xl gold-gradient text-sea-600">
              <Icon name={section.icon} size={20} />
            </span>
            <span className="font-mono-display text-[12px] text-gold-700">{String(index + 1).padStart(2, '0')}</span>
          </div>
          <h2 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl leading-tight text-sea-500`}>{textOf(section.title, lang)}</h2>
          <p className="mt-3 text-sm leading-8 text-sea-400/82">{textOf(section.text, lang)}</p>
        </Card>
      ))}
    </div>
    <Card padding="p-7" className="knowledge-final-cta">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <p className="max-w-3xl text-sm leading-8 text-sea-500">
          {lang === 'zh'
            ? '不确定自己是否适合来中国就医？提交病例资料，先获得中国专家二诊评估。'
            : 'Not sure whether China care fits? Submit medical records first and obtain a China specialist second opinion.'}
        </p>
        <Button icon="file-pen-line" onClick={() => go('intake.html?form=1')}>{lang === 'zh' ? '提交病例资料' : 'Submit records'}</Button>
      </div>
    </Card>
  </>
);

const PLAN_PACKAGES = [
  {
    id: 'second-opinion',
    icon: 'stethoscope',
    title: { zh: '中国专家二诊评估服务', en: 'China specialist second opinion service' },
    price: { zh: '550 USD 起', en: 'From 550 USD' },
    tagline: { zh: '适合希望先获得中国三甲专家二次诊疗意见，并判断是否需要来中国进一步就医的用户。', en: 'For users who want a China tertiary-hospital specialist second opinion first, then decide whether further China care is needed.' },
    bestFor: { zh: '已有检查报告、影像或诊断线索，但不确定是否需要来华面诊、检查、住院或手术评估。', en: 'For users with reports, imaging, or diagnostic clues who are unsure whether in-person consultation, testing, admission, or surgery assessment in China is needed.' },
    includes: {
      zh: ['病例资料初步整理：1 位患者 / 1 个主要病种方向', '中文病例摘要 1 份', '关键问题清单 1 份', '中国专家二诊评估 1 次', '专家意见整理 1 份', '华医畅私人医生咨询服务 2 次，每次约 30 分钟', '来华可行性判断 1 次', '资料补充建议 1 份', '中英文基础沟通支持', '保险报销资料需求初步判断', '1 个服务周期内基础沟通'],
      en: ['Initial case-record organization for 1 patient / 1 main condition direction', 'One Chinese medical case summary', 'One key-question list', 'One China specialist second-opinion review', 'One specialist-opinion summary', 'Two HuaMed private-doctor consultations, about 30 minutes each', 'One China-travel feasibility review', 'One record-supplement recommendation list', 'Basic Chinese/English communication support', 'Initial review of insurance reimbursement documentation needs', 'Basic communication within one service cycle']
    },
    excludes: {
      zh: ['医院门诊、检查、影像、药品、住院、手术等医疗费用', '到院陪同', '医院预约落地执行', '国际保险直付或预授权沟通', '正式认证医学翻译'],
      en: ['Hospital outpatient, testing, imaging, medication, admission, surgery, and other medical fees', 'On-site accompaniment', 'Hospital appointment execution', 'International insurance direct billing or pre-authorization communication', 'Certified medical translation']
    },
    limits: { zh: '本服务用于专家二诊评估和来华可行性判断，不替代医院或医生正式诊断；不包含医院预约落地执行和保险预授权沟通，不承诺医院预约、床位、手术安排、保险批准或治疗效果。', en: 'This service supports second opinion and China-travel feasibility review only. It does not replace formal hospital or physician diagnosis; it does not include hospital appointment execution or insurance pre-authorization communication, and does not promise appointments, beds, surgery arrangements, insurance approval, or outcomes.' },
    cta: { zh: '提交资料，获取专家二诊评估', en: 'Submit records for specialist second opinion' }
  },
  {
    id: 'full-service',
    icon: 'hospital',
    title: { zh: '中国就医全流程服务', en: 'End-to-end China care service' },
    price: { zh: '面议', en: 'By consultation' },
    tagline: { zh: '适合已明确来华就医需求，需要医院预约、专家协调、到院陪同、检查住院衔接、保险沟通和诊后资料整理的用户。', en: 'For users with a clear China care need who require hospital appointment coordination, specialist communication, on-site accompaniment, testing/admission linkage, insurance communication, and post-visit record organization.' },
    bestFor: { zh: '已明确希望来中国进一步就医，或已经完成专家二诊评估，需要华医畅协助推进从预约到到院执行的完整服务。', en: 'For users who clearly want further care in China, or have completed second opinion and need HuaMed to support the full path from appointment to on-site execution.' },
    includes: {
      zh: ['专属服务建档：1 位患者 / 1 个主要病种方向', '病例整理与医学翻译：1 套病例资料包', '华医畅私人医生咨询服务最多 6 次，每次约 30 分钟', '1 个就医周期内私人医生连续文字支持', '中英文医学沟通支持', '中国专家二诊评估最多 2 次', '医院与科室匹配：最多 3 个医院 / 科室方向', '专家门诊预约协调：最多 3 次预约协调尝试', '来华就医路径规划 1 份', '国际保险直付 / 预授权沟通协助：1 个就医周期内', '诊断证明 / 保险报销资料协助', '到院双语陪同最多 3 个就医日', '检查流程、住院或手术评估协调', '接送与出行基础协调最多 2 次', '家属同步沟通和诊后资料整理', '1 套核心诊后翻译资料'],
      en: ['Dedicated service file for 1 patient / 1 main condition direction', 'Case organization and medical translation: one complete case package', 'Up to six HuaMed private-doctor consultations, about 30 minutes each', 'Private-doctor text support during one care cycle', 'Chinese/English medical communication support', 'Up to two China specialist second-opinion reviews', 'Hospital and department matching: up to three hospital / department directions', 'Specialist outpatient appointment coordination: up to three coordination attempts', 'One China care pathway plan', 'International insurance direct-billing / pre-authorization communication support within one care cycle', 'Diagnosis certificate / insurance reimbursement documentation assistance', 'Up to three bilingual on-site accompaniment days', 'Testing flow and admission or surgery-assessment coordination', 'Up to two basic transfer and travel coordination requests', 'Family update communication and post-visit record organization', 'One core post-visit translation package']
    },
    excludes: {
      zh: ['医院收取的门诊、检查、影像、药品、住院、手术等医疗费用', '酒店、机票、签证、第三方交通、餐饮、住宿等外部费用', '保险公司最终批准、直付或赔付结果', '指定专家一定接诊、床位、手术排期或治疗效果', '多病种、多城市、多次来华行程的额外服务', '超过 3 个就医日的陪同服务'],
      en: ['Hospital outpatient, testing, imaging, medication, admission, surgery, and other medical fees', 'Hotel, flights, visa, third-party transportation, meals, accommodation, and other external costs', 'Final insurer approval, direct billing, or reimbursement outcome', 'Guaranteed designated-specialist acceptance, beds, surgery scheduling, or treatment outcomes', 'Additional services for multiple conditions, cities, or China trips', 'On-site accompaniment beyond three care days']
    },
    limits: { zh: '本服务提供来华就医执行支持，可协助推进预约、保险沟通和证明材料准备，但不替代医院或医生作出诊断和治疗决策，不承诺具体医院最终接诊、专家号源、床位安排、手术排期、保险批准结果、医院最终出具格式或治疗效果。默认服务周期为 30 个自然日或 1 次主要来华就医行程，以先到者为准。', en: 'This service provides China care execution support and can assist with appointments, insurance communication, and documentation preparation, but does not replace hospital or physician diagnosis and treatment decisions. It does not promise final hospital acceptance, specialist appointment slots, bed arrangements, surgery scheduling, insurance approval, final hospital-issued document format, or treatment outcomes. The default service cycle is 30 calendar days or one main China care trip, whichever comes first.' },
    cta: { zh: '咨询全流程服务方案', en: 'Consult full-service plan' },
    featured: true
  }
];

const ServicePlanPage = ({ lang, go }) => (
  <>
    <PageIntro
      lang={lang}
      eyebrow="Custom Care Journey"
      icon="route"
      variant="journey"
      heroImage="assets/page-heroes/care-journey.png"
      title={lang === 'zh' ? '定制你的中国就医旅程' : 'Customize your China care journey'}
      subtitle={lang === 'zh' ? '如果你还不确定是否需要来华，先选择专家二诊评估；如果你已经明确希望来中国就医，可选择全流程服务。服务费不包含医院医疗费用。' : 'If you are unsure whether China care is needed, start with specialist second opinion. If you already clearly want care in China, choose end-to-end service. Service fees do not include hospital medical fees.'}
    />
    <ServicePlanGuide lang={lang} />
    <ProcessTimeline lang={lang} go={go} />
    <PricingPlansSection lang={lang} go={go} />
  </>
);

const PricingPlansSection = ({ lang, go, onOpenIntake }) => (
  <section id="packages" className="service-plan-pricing scroll-mt-24">
    <SectionHeader
      eyebrow="Packages"
      lang={lang}
      title={{ zh: '选择适合你的中国就医服务', en: 'Choose your China care service package' }}
      subtitle={{
        zh: '如果你还不确定是否需要来华，先选择专家二诊评估；如果你已经明确希望来中国就医，可选择全流程服务，由华医畅协助推进资料整理、医院协调、到院陪同、保险沟通和诊后资料整理。',
        en: 'If you are unsure whether China care is needed, start with specialist second opinion. If you already clearly want care in China, choose end-to-end service for record organization, hospital coordination, on-site accompaniment, insurance communication, and post-visit record organization.'
      }}
      right={<Pill tone="gold" icon="receipt-text">{lang === 'zh' ? '医院费用另付' : 'Hospital fees excluded'}</Pill>}
    />
    <Card padding="p-5" className="mb-5 bg-gold-50/60 ring-1 ring-gold-100">
      <p className="text-sm leading-8 text-sea-500">
        {lang === 'zh'
          ? '如果你不确定是否适合来华，建议先选择专家二诊评估；如果你已经明确希望来中国就医，可直接咨询全流程服务方案。'
          : 'If you are unsure whether China travel is right, start with specialist second opinion. If you already clearly want care in China, consult the end-to-end service plan directly.'}
      </p>
    </Card>
    <div className="pricing-grid">
      {PLAN_PACKAGES.map((plan) => (
        <Card key={plan.id} padding="p-0" className={`pricing-plan-card ${plan.featured ? 'is-featured' : ''}`}>
          <div className="pricing-plan-head">
            <div className="flex items-center justify-between gap-3">
              <span className={`flex h-12 w-12 items-center justify-center rounded-2xl ${plan.featured ? 'gold-gradient text-sea-600' : 'sea-gradient text-gold-300'}`}>
                <Icon name={plan.icon} size={20} />
              </span>
              {plan.featured && <Pill tone="gold">{lang === 'zh' ? '推荐' : 'Recommended'}</Pill>}
            </div>
            <h2 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-5 text-[34px] leading-tight text-sea-500`}>{textOf(plan.title, lang)}</h2>
            <div className="mt-2 font-mono-display text-lg text-gold-700">{textOf(plan.price, lang)}</div>
            <p className="mt-3 text-sm leading-relaxed text-sea-400/78">{textOf(plan.tagline, lang)}</p>
          </div>
          <div className="pricing-plan-body">
            <div className="rounded-2xl bg-marble-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 hairline">{textOf(plan.bestFor, lang)}</div>
            <div className="mt-5 space-y-2">
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-gold-700">{lang === 'zh' ? '包含服务' : 'Included'}</div>
              {plan.includes[lang].map((item) => (
                <div key={item} className="flex gap-2 text-sm leading-relaxed text-sea-500">
                  <Icon name="check" size={15} className="mt-0.5 shrink-0 text-gold-600" />
                  <span>{item}</span>
                </div>
              ))}
            </div>
            {plan.excludes && (
              <div className="mt-5 space-y-2">
                <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-marble-500">{lang === 'zh' ? '不包含' : 'Not included'}</div>
                {plan.excludes[lang].map((item) => (
                  <div key={item} className="flex gap-2 text-sm leading-relaxed text-sea-400/84">
                    <Icon name="minus" size={15} className="mt-0.5 shrink-0 text-marble-500" />
                    <span>{item}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
          <div className="pricing-plan-foot">
            <div className="pricing-plan-boundary rounded-2xl bg-gold-50/70 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-100">
              <div className="mb-1 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-gold-700">
                <Icon name="shield-alert" size={13} />
                {lang === 'zh' ? '服务边界' : 'Boundary'}
              </div>
              {textOf(plan.limits, lang)}
            </div>
            <Button icon="file-pen-line" onClick={() => onOpenIntake ? onOpenIntake() : go('intake.html?form=1')} className="mt-5 w-full">
              {textOf(plan.cta, lang)}
            </Button>
          </div>
        </Card>
      ))}
    </div>
    <PackageComparisonSection lang={lang} />
    <ResearchFeedbackCoverageSection lang={lang} />
  </section>
);

const PackageComparisonSection = ({ lang }) => {
  const rows = [
    {
      label: { zh: '服务定位', en: 'Service position' },
      second: { zh: '先判断是否需要来华', en: 'First assess whether China care is needed' },
      full: { zh: '推进来华就医执行服务', en: 'Move into China care execution support' }
    },
    {
      label: { zh: '专家二诊评估', en: 'Specialist second opinion' },
      second: { zh: '1 次中国专家二诊评估', en: 'One China specialist second-opinion review' },
      full: { zh: '最多 2 次中国专家二诊评估', en: 'Up to two China specialist second-opinion reviews' }
    },
    {
      label: { zh: '语言沟通支持', en: 'Language communication support' },
      second: { zh: '中英文基础沟通支持', en: 'Basic Chinese/English communication support' },
      full: { zh: '中英文医学沟通支持，含到院双语陪同上限', en: 'Chinese/English medical communication support, with on-site bilingual accompaniment limit' }
    },
    {
      label: { zh: '预约协调', en: 'Appointment coordination' },
      second: { zh: '不含医院预约落地执行', en: 'Hospital appointment execution not included' },
      full: { zh: '最多 3 次专家门诊预约协调尝试', en: 'Up to three specialist outpatient appointment coordination attempts' }
    },
    {
      label: { zh: '保险沟通', en: 'Insurance communication' },
      second: { zh: '保险报销资料需求初步判断，不含保险预授权', en: 'Initial reimbursement-documentation review; pre-authorization not included' },
      full: { zh: '协助保险直付 / 预授权沟通，不承诺批准结果', en: 'Support direct-billing / pre-authorization communication; approval not promised' }
    },
    {
      label: { zh: '诊断证明 / 保险报销资料', en: 'Diagnosis certificate / reimbursement documents' },
      second: { zh: '初步判断可能需要哪些资料', en: 'Initial view of potentially required documents' },
      full: { zh: '协助准备诊断证明和保险报销相关资料，不承诺医院最终出具格式', en: 'Assist with diagnosis certificate and reimbursement documents; final hospital format not promised' }
    }
  ];
  return (
    <Card padding="p-0" className="mt-6 overflow-hidden">
      <div className="border-b border-marble-200/70 p-5">
        <div className="font-mono-display text-[11px] uppercase tracking-[0.2em] text-gold-700">{lang === 'zh' ? '套餐对比' : 'Package comparison'}</div>
        <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-2 text-2xl text-sea-500`}>{lang === 'zh' ? '二诊评估与全流程服务怎么选' : 'How to choose between the two packages'}</h3>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[760px] text-left text-sm">
          <thead className="bg-marble-50 text-[11px] uppercase tracking-[0.16em] text-marble-500">
            <tr>
              <th className="px-5 py-3 font-medium">{lang === 'zh' ? '项目' : 'Item'}</th>
              <th className="px-5 py-3 font-medium">{textOf(PLAN_PACKAGES[0].title, lang)}</th>
              <th className="px-5 py-3 font-medium">{textOf(PLAN_PACKAGES[1].title, lang)}</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => (
              <tr key={row.label.zh} className="border-t border-marble-200/60 align-top">
                <td className="px-5 py-4 font-medium text-sea-500">{textOf(row.label, lang)}</td>
                <td className="px-5 py-4 leading-relaxed text-sea-400/86">{textOf(row.second, lang)}</td>
                <td className="px-5 py-4 leading-relaxed text-sea-400/86">{textOf(row.full, lang)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
};

const ResearchFeedbackCoverageSection = ({ lang }) => {
  const items = [
    ['languages', lang === 'zh' ? '语言困难' : 'Language difficulty', lang === 'zh' ? '套餐一覆盖中英文基础沟通支持；套餐二升级为中英文医学沟通支持，并可结合到院双语陪同。' : 'Package 1 covers basic Chinese/English communication; Package 2 upgrades to Chinese/English medical communication and can include on-site bilingual accompaniment.'],
    ['search-check', lang === 'zh' ? '高效确诊' : 'Efficient diagnostic clarity', lang === 'zh' ? '套餐一通过资料整理、关键问题清单和中国专家二诊评估，先帮助判断下一步；套餐二在此基础上推进医院、科室和门诊协调。' : 'Package 1 uses record organization, key-question list, and China specialist second opinion to clarify next steps; Package 2 adds hospital, department, and outpatient coordination.'],
    ['file-check-2', lang === 'zh' ? '保险报销证明' : 'Insurance reimbursement proof', lang === 'zh' ? '套餐一初步判断报销资料需求；套餐二协助准备诊断证明和保险报销相关材料，但不承诺保险批准或医院最终出具格式。' : 'Package 1 gives an initial view of reimbursement-document needs; Package 2 assists with diagnosis certificate and reimbursement materials, without promising insurer approval or final hospital format.'],
    ['calendar-check', lang === 'zh' ? '专家预约时间' : 'Specialist appointment timing', lang === 'zh' ? '套餐一不含预约落地；套餐二可做最多 3 次专家门诊预约协调尝试，但不承诺专家号源或接诊时间。' : 'Package 1 does not include appointment execution; Package 2 supports up to three specialist outpatient coordination attempts, without promising appointment slots or timing.']
  ];
  return (
    <Card padding="p-6" className="mt-6 bg-marble-50/70">
      <SectionHeader
        eyebrow="Feedback Check"
        lang={lang}
        title={{ zh: '调研反馈需求覆盖核对', en: 'Research feedback coverage check' }}
        subtitle={{
          zh: '以下逐项对应用户调研中反复出现的服务需求，并保留清晰服务边界，便于产品经理落地到表单、报价单和客服话术。',
          en: 'The following maps recurring user research needs to service coverage while keeping clear boundaries for product, quotation, and support-script implementation.'
        }}
      />
      <div className="grid gap-4 md:grid-cols-2">
        {items.map(([icon, title, text]) => (
          <div key={title} className="rounded-2xl bg-white p-4 ring-1 hairline">
            <Icon name={icon} size={18} className="mb-3 text-gold-700" />
            <h4 className="text-sm font-semibold text-sea-500">{title}</h4>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/82">{text}</p>
          </div>
        ))}
      </div>
      <ComplianceNotice
        lang={lang}
        text={{
          zh: '产品经理落地提示：询价表单需增加语言偏好、保险类型、是否需要报销材料、是否已有目标专家/时间窗口；客服与报价单需同步展示边界：套餐一不含预约落地和保险预授权，套餐二协助预约、保险和证明材料，但不承诺专家号源、保险批准或医院最终出具格式。',
          en: 'Product implementation note: add language preference, insurance type, reimbursement-document need, and target specialist/time-window fields to quotation intake. Support scripts and quotations should show the same boundaries: Package 1 excludes appointment execution and insurance pre-authorization; Package 2 assists with appointments, insurance, and proof documents, but does not promise specialist slots, insurance approval, or final hospital-issued formats.'
        }}
      />
    </Card>
  );
};

const InsuranceSupportSection = ({ lang }) => {
  const items = [
    ['shield-check', lang === 'zh' ? '协助梳理用户保险信息和就医需求' : 'Review insurance information and care needs'],
    ['building-2', lang === 'zh' ? '协助确认目标医院是否有国际保险直付或预授权沟通窗口' : 'Check whether the target hospital has direct-billing or pre-authorization communication channels'],
    ['file-check-2', lang === 'zh' ? '协助准备保险预授权所需的病例、检查、预约和费用相关材料' : 'Prepare records, tests, appointment, and cost-related materials for pre-authorization'],
    ['list-plus', lang === 'zh' ? '协助用户理解保险公司可能要求的补充材料' : 'Help users understand supplementary materials insurers may request'],
    ['users-round', lang === 'zh' ? '协助家属理解自费、直付、预授权和报销之间的区别' : 'Help families understand self-pay, direct billing, pre-authorization, and reimbursement differences']
  ];
  return (
    <Card padding="p-7" className="insurance-support-card">
      <SectionHeader
        eyebrow="International Insurance"
        lang={lang}
        title={{ zh: '国际保险直付与预授权沟通协助', en: 'International insurance direct billing and pre-authorization support' }}
        subtitle={{
          zh: '如果你持有 Cigna、Bupa、Aetna 或其他国际保险，华医畅可以协助你理解中国医院就医场景下的直付、预授权和报销资料要求。',
          en: 'If you hold Cigna, Bupa, Aetna, or other international insurance, HuaMed can help you understand direct billing, pre-authorization, and reimbursement documentation requirements in China hospital settings.'
        }}
      />
      <p className="max-w-4xl text-sm leading-8 text-sea-500">
        {lang === 'zh'
          ? '海外患者在中国医院就医时，是否可以使用国际保险直付或预授权，取决于用户个人保单、就诊医院、具体诊疗项目和保险公司的审核结果。华医畅可以协助用户整理资料、了解医院国际部或保险窗口要求，并协助推进直付或预授权沟通流程，但不承诺保险公司一定批准、直付或覆盖全部费用。'
          : 'Whether international insurance can be used for direct billing or pre-authorization in China depends on the user’s policy, hospital, care item, and insurer review. HuaMed can help organize materials, understand international department or insurance-window requirements, and support communication, but does not promise approval, direct billing, or full coverage.'}
      </p>
      <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-5">
        {items.map(([icon, text]) => (
          <div key={text} className="rounded-3xl bg-white/78 p-4 ring-1 hairline">
            <Icon name={icon} size={18} className="mb-3 text-gold-700" />
            <p className="text-sm leading-relaxed text-sea-500">{text}</p>
          </div>
        ))}
      </div>
      <ComplianceNotice
        lang={lang}
        text={{
          zh: '华医畅不代表保险公司审核保单，不承诺保险覆盖范围，不承诺直付或预授权一定通过。医院医疗费用不包含在华医畅服务费中。',
          en: 'HuaMed does not review policies on behalf of insurers, promise coverage scope, or guarantee direct billing or pre-authorization approval. Hospital medical fees are not included in HuaMed service fees.'
        }}
      />
    </Card>
  );
};

const OptionalServicesSection = ({ lang }) => {
  const rows = [
    [lang === 'zh' ? '到院当天双语陪同' : 'Bilingual on-site accompaniment', lang === 'zh' ? '协助签到、挂号、诊室沟通、检查流程、缴费或保险窗口沟通、取报告和复诊安排。' : 'Support check-in, registration, clinic communication, testing flow, payment or insurance-window communication, report pickup, and follow-up scheduling.', lang === 'zh' ? '按天报价' : 'Quoted per day'],
    [lang === 'zh' ? '接送机与市内医疗出行' : 'Airport and medical-trip transfers', lang === 'zh' ? '协助安排机场、酒店、医院之间的接送和就医日交通。' : 'Coordinate transfers among airport, hotel, hospital, and care-day transportation.', lang === 'zh' ? '按实际需求报价' : 'Quoted by actual needs'],
    [lang === 'zh' ? '正式医学翻译或认证译文' : 'Formal or certified medical translation', lang === 'zh' ? '病历、检查报告、诊断证明、出院小结、手术记录等正式翻译。' : 'Formal translations for records, reports, diagnosis certificates, discharge summaries, surgery records, and related documents.', lang === 'zh' ? '按文件量报价' : 'Quoted by document volume'],
    [lang === 'zh' ? '保险材料整理' : 'Insurance material organization', lang === 'zh' ? '协助整理预授权、直付或报销所需资料。' : 'Organize materials needed for pre-authorization, direct billing, or reimbursement.', lang === 'zh' ? '按复杂度报价' : 'Quoted by complexity'],
    [lang === 'zh' ? '家属远程同步' : 'Remote family updates', lang === 'zh' ? '向海外家属同步就医流程、检查进展、医生反馈和下一步安排。' : 'Update overseas family members on care flow, testing progress, doctor feedback, and next arrangements.', lang === 'zh' ? '按服务周期报价' : 'Quoted by service period'],
    [lang === 'zh' ? '诊后资料包' : 'Post-visit record package', lang === 'zh' ? '整理诊后报告、翻译盖章病例、回国复查资料。' : 'Organize post-visit reports, translated/stamped case records, and return-home follow-up materials.', lang === 'zh' ? '按文件量和医院要求报价' : 'Quoted by document volume and hospital requirements']
  ];
  return (
    <section className="optional-services-section">
      <SectionHeader
        eyebrow="Optional Services"
        lang={lang}
        title={{ zh: '可选服务', en: 'Optional services' }}
        subtitle={{
          zh: '根据用户来华时间、医院安排、语言需求和资料用途，以下服务可在主套餐之外单独确认。',
          en: 'Depending on China travel timing, hospital arrangement, language needs, and document use, these services can be confirmed separately beyond the main package.'
        }}
      />
      <div className="optional-services-grid">
        {rows.map(([title, text, pricing]) => (
          <Card key={title} padding="p-5">
            <div className="mb-3 flex items-start justify-between gap-3">
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
              <Pill tone="marble">{pricing}</Pill>
            </div>
            <p className="text-sm leading-relaxed text-sea-400/78">{text}</p>
          </Card>
        ))}
      </div>
    </section>
  );
};

const JourneyFAQSection = ({ lang }) => {
  const faqs = [
    [lang === 'zh' ? '华医畅是否提供医疗诊断？' : 'Does HuaMed provide medical diagnosis?', lang === 'zh' ? '华医畅提供病例整理、专家二诊协调、来华就医路径规划和就医服务支持，不替代医院或医生的正式诊断。所有诊断、检查、治疗方案和手术决策，以医院和执业医生的正式意见为准。' : 'HuaMed provides case organization, specialist second-opinion coordination, China care pathway planning, and care-service support. It does not replace formal diagnosis by hospitals or physicians. All diagnoses, tests, treatment plans, and surgery decisions depend on formal hospital and licensed-physician opinions.'],
    [lang === 'zh' ? '服务费是否包含医院费用？' : 'Do service fees include hospital fees?', lang === 'zh' ? '不包含。医生门诊费、检查费、影像费、化验费、药费、住院费、手术费等由医院单独收取。华医畅服务费仅对应病例整理、专家沟通协调、来华就医路径规划、陪同、翻译、保险沟通协助等服务内容。' : 'No. Doctor consultation fees, testing, imaging, labs, medication, admission, and surgery fees are charged separately by hospitals. HuaMed service fees cover record organization, specialist communication coordination, China care pathway planning, accompaniment, translation, and insurance communication support.'],
    [lang === 'zh' ? '能否保证预约到某位专家？' : 'Can HuaMed guarantee a named specialist?', lang === 'zh' ? '不能承诺。华医畅会在资料完整、符合医疗指征并通过医院正式流程的前提下，协助匹配合适的医院、科室和专家方向，但不承诺某一位专家、某一个号源、床位、手术排期或治疗结果。' : 'No. When records are complete, medical indications fit, and formal hospital processes allow, HuaMed helps match suitable hospitals, departments, and specialist directions. It does not promise a named specialist, appointment slot, bed, surgery timing, or outcome.'],
    [lang === 'zh' ? '国际保险是否一定可以直付？' : 'Is international insurance direct billing guaranteed?', lang === 'zh' ? '不一定。是否可以直付、预授权或报销，取决于用户个人保单、医院政策、诊疗项目和保险公司审核结果。华医畅可以协助准备资料和沟通流程，但不代表保险公司作出承诺。' : 'No. Direct billing, pre-authorization, or reimbursement depends on the user’s policy, hospital policy, care item, and insurer review. HuaMed can help prepare materials and support communication, but cannot commit on behalf of insurers.'],
    [lang === 'zh' ? '来华前需要准备哪些资料？' : 'What records are usually needed before China travel?', lang === 'zh' ? '通常包括既往病历、检查报告、影像资料、病理报告、用药记录、手术记录、当地医生建议、保险信息和预计来华时间。不同病种需要的资料不同，华医畅会根据用户情况提供资料清单。' : 'Usually prior medical records, test reports, imaging, pathology reports, medication history, surgery records, local doctor advice, insurance information, and expected China travel timing. Required records vary by condition, and HuaMed provides a case-specific checklist.'],
    [lang === 'zh' ? '如果专家判断暂不适合来华怎么办？' : 'What if the specialist says China travel is not suitable now?', lang === 'zh' ? '如果专家二诊评估认为暂不适合来华，华医畅会根据已有资料帮助用户理解原因，并建议后续需要补充的检查、复诊方向或可继续在当地处理的事项。是否继续升级后续服务，由用户自行决定。' : 'If second opinion suggests China travel is not suitable for now, HuaMed helps the user understand the reason based on available records and suggests further tests, follow-up directions, or local-care items. Users decide whether to continue to later service stages.'],
    [lang === 'zh' ? '付款和退款规则是什么？' : 'What are payment and refund rules?', lang === 'zh' ? '服务启动前需根据所选服务支付相应服务费或定金。病例整理、专家协调、医院沟通、保险沟通等服务一旦启动，已发生的服务成本不予退还。如因医院、专家时间、保险审核或用户行程变化导致原方案需要调整，华医畅会与用户沟通替代方案。具体付款节点和退款规则以双方确认的服务方案为准。' : 'Before service starts, the corresponding service fee or deposit is paid based on the selected plan. Once record organization, specialist coordination, hospital communication, or insurance communication begins, incurred service costs are non-refundable. If hospital timing, specialist availability, insurance review, or travel changes require plan adjustment, HuaMed will discuss alternatives. Exact payment and refund terms follow the confirmed service plan.'],
    [lang === 'zh' ? '华医畅是否可以安排住院或手术？' : 'Can HuaMed arrange admission or surgery?', lang === 'zh' ? '华医畅可以在资料完整、符合医疗指征并通过医院正式流程评估的前提下，协助推进住院评估、手术评估或相关就医流程。但最终是否接诊、是否住院、是否手术以及具体时间安排，由医院和医生根据患者病情及医院资源决定。' : 'When records are complete, indications fit, and formal hospital review allows, HuaMed can help move forward admission assessment, surgery assessment, or related care processes. Final acceptance, admission, surgery, and timing are determined by hospitals and doctors based on the patient’s condition and hospital resources.'],
    [lang === 'zh' ? '如果我只想先了解是否值得来中国，应该选择哪档服务？' : 'Which service should I choose if I only want to know whether China travel is worth it?', lang === 'zh' ? '建议先选择中国专家二诊评估服务。该服务会先帮助你整理病例资料，并通过中国专家意见判断是否需要进一步来华面诊、检查、住院或手术评估。' : 'Start with the China specialist second opinion service. It helps organize records first, then uses China specialist input to assess whether in-person consultation, testing, admission, or surgery assessment in China is needed.'],
    [lang === 'zh' ? '华医畅是否适合所有病种？' : 'Is HuaMed suitable for every condition?', lang === 'zh' ? '华医畅更适合已有明确检查结果、复杂诊疗需求或希望获得中国专家二诊意见的用户。重点方向包括肿瘤、胸外、心血管、神经外科、妇产、消化、耳鼻喉、肾脏病、骨科/脊柱等。普通小病、急诊抢救或不适合长途旅行的情况，不一定适合通过华医畅安排来华就医。' : 'HuaMed is better suited to users with clear findings, complex care needs, or a need for China specialist second opinion. Key directions include oncology, thoracic surgery, cardiovascular, neurosurgery, gynecology/obstetrics, gastroenterology, ENT, nephrology, orthopedics/spine, and related fields. Minor illnesses, emergency rescue, or cases unsuitable for long-distance travel may not fit HuaMed’s China care service.']
  ];
  return (
    <section className="journey-faq-section">
      <SectionHeader
        eyebrow="FAQ"
        lang={lang}
        title={{ zh: '常见问题', en: 'Frequently asked questions' }}
        subtitle={{ zh: '以下回答用于帮助用户理解服务边界、费用、保险和来华路径。', en: 'These answers help users understand service boundaries, fees, insurance, and China care pathways.' }}
      />
      <div className="journey-faq-list">
        {faqs.map(([q, a], index) => (
          <details key={q} className="journey-faq-item" open={index < 2}>
            <summary>
              <span>{q}</span>
              <Icon name="chevron-down" size={17} />
            </summary>
            <p>{a}</p>
          </details>
        ))}
      </div>
    </section>
  );
};

const JourneyFinalCta = ({ lang, go, onOpenIntake }) => (
  <Card padding="p-7" className="journey-final-cta">
    <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
      <div>
        <div className="font-mono-display text-[11px] uppercase tracking-[0.2em] text-gold-700">{lang === 'zh' ? 'Start with records' : 'Start with records'}</div>
        <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-2 text-3xl text-sea-500`}>{lang === 'zh' ? '不确定自己是否适合来中国就医？' : 'Not sure whether China care fits?'}</h3>
        <p className="mt-2 max-w-3xl text-sm leading-7 text-sea-400/78">{lang === 'zh' ? '提交病例资料，先获得中国专家二诊评估，再判断是否需要继续规划来华路径。' : 'Submit records first, obtain a China specialist second opinion, then decide whether to continue planning a China pathway.'}</p>
      </div>
      <Button icon="file-pen-line" onClick={() => onOpenIntake ? onOpenIntake() : go('intake.html?form=1')}>{lang === 'zh' ? '提交病例资料' : 'Submit records'}</Button>
    </div>
  </Card>
);

const ServicePlanGuide = ({ lang }) => {
  const items = [
    ['search-check', lang === 'zh' ? '先判断适配' : 'Fit first', lang === 'zh' ? '不是每个病例都适合二诊或来华，急症、资料不足和不在范围内的情况会先说明。' : 'Not every case fits second opinion or China visit; urgent, incomplete, or out-of-scope cases are clarified first.'],
    ['file-stack', lang === 'zh' ? '按资料推进' : 'Record-led service', lang === 'zh' ? '价格和服务深度取决于资料完整度、病种复杂度和是否进入来华协调。' : 'Price and service depth depend on record readiness, case complexity, and whether China coordination is needed.'],
    ['receipt-text', lang === 'zh' ? '医院费用不打包' : 'No bundled hospital fees', lang === 'zh' ? '检查、治疗、住院和手术费用由客户直接向医院支付，华医畅不代收。' : 'Testing, treatment, admission, and surgery fees are paid directly to hospitals, not collected by HuaMed.']
  ];
  return (
    <div className="grid gap-5 lg:grid-cols-3">
      {items.map(([icon, title, text]) => (
        <Card key={title} padding="p-5">
          <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl gold-gradient text-sea-600">
            <Icon name={icon} size={19} />
          </div>
          <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
          <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
        </Card>
      ))}
    </div>
  );
};

const HospitalsSection = ({ lang, go }) => {
  const [activeHospitalId, setActiveHospitalId] = React.useState(HOSPITALS[0].id);
  const activeHospital = HOSPITALS.find((hospital) => hospital.id === activeHospitalId) || HOSPITALS[0];
  return (
    <>
      <SectionHeader
        eyebrow="Medical System"
        lang={lang}
        title={{ zh: '为什么海外患者需要先理解中国医疗体系？', en: 'Why overseas patients should understand China’s medical system first' }}
        subtitle={{
          zh: '中国优质医疗资源高度集中在北京、上海、广州等城市的知名三甲医院和重点专科。难点不只是找到医院，而是判断医院、科室、亚专科、资料完整度和正式流程是否匹配当前问题。',
          en: 'High-quality medical resources in China are concentrated in top tertiary hospitals and specialty centers in major cities. The challenge is matching hospital, department, subspecialty, record readiness, and formal process to the case.'
        }}
      />
      <Card padding="p-6 md:p-8" className="hospital-system-card">
        <div className="grid gap-5 md:grid-cols-3">
          {[
            ['map', lang === 'zh' ? '先定位城市与医院方向' : 'Locate city and hospital direction', lang === 'zh' ? '综合医院、专科医院、国际医疗部或特需门诊适合的场景不同。' : 'General hospitals, specialty hospitals, international departments, and VIP clinics fit different cases.'],
            ['list-checks', lang === 'zh' ? '再确认科室和亚专科' : 'Confirm department and subspecialty', lang === 'zh' ? '同一个病种可能涉及外科、内科、影像、病理或多学科协作。' : 'The same condition may involve surgery, medicine, imaging, pathology, or multidisciplinary care.'],
            ['file-search', lang === 'zh' ? '最后看资料是否足够' : 'Check whether records are enough', lang === 'zh' ? '报告、影像、病理和本地医生建议越完整，越能减少无效就诊和重复检查。' : 'More complete reports, imaging, pathology, and local advice reduce wasted visits and repeated tests.']
          ].map(([icon, title, text]) => (
            <div key={title} className="rounded-3xl bg-white/72 p-5 ring-1 hairline">
              <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl gold-gradient text-sea-600">
                <Icon name={icon} size={19} />
              </div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
              <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{text}</p>
            </div>
          ))}
        </div>
        <div className="mt-6 flex flex-wrap items-center justify-between gap-4 rounded-3xl bg-white/72 p-5 ring-1 hairline">
          <p className="max-w-2xl text-sm leading-relaxed text-sea-500">
            {lang === 'zh'
              ? '想进一步了解中国三甲医院、重点专科、复旦榜单和来华就医资料路径，可以先看完整说明页。'
              : 'For more on Chinese tertiary hospitals, specialty directions, Fudan rankings, and record pathways, open the full guide.'}
          </p>
          <Button icon="arrow-up-right" onClick={() => window.location.href = 'system.html'}>
            {lang === 'zh' ? '了解中国医疗服务体系' : 'Open system guide'}
          </Button>
        </div>
      </Card>
      <SectionHeader
        eyebrow="Representative Hospitals"
        lang={lang}
        title={{ zh: '重点医院参考', en: 'Representative Hospital References' }}
        subtitle={{
          zh: '中国多家代表性高水平医院资源，为海外家庭理解复杂疾病评估、专科二诊和来华就医路径提供参考。',
          en: 'Representative high-level hospital resources in China help overseas families understand complex case review, specialty second opinion, and China care pathways.'
        }}
      />
      <ComplianceNotice
        lang={lang}
        icon="shield-alert"
        text={{
          zh: '以下医院内容用于帮助海外用户理解中国优质医疗资源的分布和重点专科方向，不代表华医畅承诺与相关医院存在合作关系，也不代表可以直接安排指定专家、号源、床位或手术。',
          en: 'The hospital information below helps overseas users understand the distribution of high-quality medical resources and specialty directions in China. It does not mean HuaMed promises a partnership with these hospitals or can directly arrange a named specialist, appointment slot, bed, or surgery.'
        }}
      />
      <div className="hospital-card-grid">
        {HOSPITALS.map((hospital) => (
          <button
            key={hospital.id}
            type="button"
            className={`hospital-card ${hospital.id === activeHospital.id ? 'is-active' : ''}`}
            onClick={() => setActiveHospitalId(hospital.id)}
          >
            <img src={hospital.image} alt={textOf(hospital.name, lang)} />
            <span className="hospital-card-body">
              <span className="font-mono-display text-[10px] uppercase tracking-[0.2em] text-gold-700">{textOf(hospital.city, lang)}</span>
              <span className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 block text-[22px] leading-tight text-sea-500`}>{textOf(hospital.name, lang)}</span>
              <span className="mt-2 block text-xs leading-relaxed text-sea-400/76">{textOf(hospital.tag, lang)}</span>
            </span>
          </button>
        ))}
      </div>
      <Card padding="p-0" className="hospital-detail-card">
        <div className="grid gap-0 lg:grid-cols-12">
          <div className="lg:col-span-5">
            <img src={activeHospital.image} alt={textOf(activeHospital.name, lang)} className="hospital-detail-image" />
          </div>
          <div className="p-6 lg:col-span-7 lg:p-8">
            <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
              <div>
                <div className="font-mono-display text-[11px] uppercase tracking-[0.2em] text-gold-700">{textOf(activeHospital.city, lang)}</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-[32px] leading-tight text-sea-500`}>{textOf(activeHospital.name, lang)}</h3>
                <a href={activeHospital.website} target="_blank" rel="noreferrer" className="mt-2 inline-flex items-center gap-1.5 text-xs font-semibold text-gold-700">
                  {lang === 'zh' ? '医院官网' : 'Official website'}
                  <Icon name="external-link" size={12} />
                </a>
              </div>
              <Pill tone="gold" icon="building-2">{textOf(activeHospital.tag, lang)}</Pill>
            </div>
            <p className="text-sm leading-8 text-sea-400/82">{textOf(activeHospital.note, lang)}</p>
            <div className="mt-5 grid gap-5 lg:grid-cols-2">
              <div>
                <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{lang === 'zh' ? '优势方向' : 'Specialty directions'}</div>
                <div className="space-y-2">
                  {activeHospital.focus[lang].map((item) => (
                    <div key={item} className="flex gap-2 rounded-2xl bg-white p-3 text-sm text-sea-500 ring-1 hairline">
                      <Icon name="check" size={14} className="mt-0.5 shrink-0 text-gold-600" />
                      <span>{item}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div>
                <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{lang === 'zh' ? '数字支撑' : 'Signals'}</div>
                <div className="space-y-2">
                  {activeHospital.metrics[lang].map((item) => (
                    <div key={`${item.value}-${item.label}`} className="rounded-2xl bg-white p-4 ring-1 hairline">
                      <div className="flex items-baseline gap-2">
                        <span className="font-mono-display text-2xl font-semibold text-gold-700">{item.value}</span>
                        <span className="text-[12px] font-medium text-sea-500">{item.label}</span>
                      </div>
                      <p className="mt-2 text-sm leading-relaxed text-sea-400/78">{item.text}</p>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <div className="mt-5">
                <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{lang === 'zh' ? '建议先准备' : 'Prepare first'}</div>
                <div className="flex flex-wrap gap-2">
                  {activeHospital.records[lang].map((item) => <Pill key={item} tone="marble">{item}</Pill>)}
                </div>
            </div>
          </div>
        </div>
      </Card>
      <Card padding="p-6" className="hospital-direction-cta">
        <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
          <p className="max-w-3xl text-sm leading-8 text-sea-500">
            {lang === 'zh'
              ? '不确定自己适合哪家医院或科室？提交资料后，华医畅可根据病种、检查资料和来华时间，协助判断适合的医院和专家方向。'
              : 'Not sure which hospital or department fits? After you submit records, HuaMed can help judge suitable hospital and specialist directions based on condition, available records, and expected China travel timing.'}
          </p>
          <Button icon="file-pen-line" onClick={() => go?.('intake.html?form=1')}>{lang === 'zh' ? '提交资料，获取医院方向建议' : 'Submit records for hospital direction'}</Button>
        </div>
      </Card>
    </>
  );
};

const ServicesSection = ({ lang, tr, serviceId, setServiceId, selectedService, copy }) => (
  <>
    <SectionHeader
      eyebrow="Services"
      lang={lang}
      title={{ zh: copy.sectionServices, en: copy.sectionServices }}
      subtitle={{
        zh: '费用区间只代表华医畅服务费。医院检查、治疗、住院和手术等医疗费用由客户直接向医院支付。',
        en: 'Fee ranges refer to HuaMed service fees only. Hospital tests, treatment, admission, and surgery fees are paid directly to hospitals.'
      }}
      right={<Pill tone="green" icon="shield-check">{lang === 'zh' ? '合规边界内展示' : 'Compliance-first copy'}</Pill>}
    />
    <div className="grid gap-6 lg:grid-cols-12">
      <div className="grid gap-4 md:grid-cols-2 lg:col-span-7">
        {SERVICES.map((service) => {
          const active = service.id === serviceId;
          return (
            <Card key={service.id} onClick={() => setServiceId(service.id)} padding="p-5" className={`cursor-pointer transition hover:-translate-y-0.5 hover:shadow-lift ${active ? 'ring-gold-400 shadow-lift' : ''}`}>
              <div className="flex items-start gap-4">
                <div className={`${active ? 'gold-gradient text-sea-600' : 'bg-marble-100 text-sea-400'} flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl`}>
                  <Icon name={service.icon} size={19} />
                </div>
                <div className="min-w-0">
                  <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-lg font-semibold text-sea-500`}>{tr(service.name)}</h3>
                  <div className="mt-1 font-mono-display text-[12px] text-gold-700">{tr(service.price)}</div>
                  <p className="mt-2 text-[13px] leading-relaxed text-sea-400/76">{tr(service.description)}</p>
                </div>
              </div>
            </Card>
          );
        })}
      </div>
      <Card className="lg:col-span-5" padding="p-7">
        <div className="mb-5 flex items-start justify-between gap-3">
          <div>
            <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{copy.serviceFee}</div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-[28px] leading-tight text-sea-500`}>{tr(selectedService.name)}</h3>
            <div className="font-mono-display mt-2 text-lg text-gold-700">{tr(selectedService.price)}</div>
          </div>
          <div className="flex h-12 w-12 items-center justify-center rounded-2xl sea-gradient text-gold-300">
            <Icon name={selectedService.icon} size={21} />
          </div>
        </div>
        <div className="space-y-4">
          <div>
            <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{copy.deliverables}</div>
            <div className="space-y-2">
              {selectedService.deliverables[lang].map((item) => (
                <div key={item} className="flex gap-2 rounded-2xl bg-marble-50 p-3 text-sm text-sea-500 ring-1 hairline">
                  <Icon name="check" size={14} className="mt-0.5 text-gold-600" />
                  <span>{item}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="rounded-2xl bg-gold-50/70 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-100">
            <div className="mb-1 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-gold-700">
              <Icon name="shield-alert" size={13} />
              {copy.boundary}
            </div>
            {tr(selectedService.boundary)}
          </div>
        </div>
      </Card>
    </div>
  </>
);

const ChecklistSection = ({ lang, tr, selected, selectedCondition, setSelectedCondition, copy }) => {
  const conditionList = [...getFocusConditions(), ...getSupportConditions()];
  return (
    <>
      <SectionHeader
        eyebrow="Conditions"
        lang={lang}
        title={{ zh: '服务病症', en: 'Conditions' }}
        subtitle={{
          zh: '按病种查看适合初步评估的情况、常见关注点和通常需要准备的报告、影像、病理资料。',
          en: 'Review supported conditions, common care questions, and the records usually needed for an initial pathway assessment.'
        }}
      />
      <div className="grid gap-6 lg:grid-cols-12">
        <Card className="lg:col-span-4" padding="p-6">
          <div className="mb-4 text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{copy.chooseCondition}</div>
          <div className="space-y-2">
            {conditionList.map((condition) => (
              <button key={condition.id} onClick={() => setSelectedCondition(condition.id)} className={`flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left transition ${selectedCondition === condition.id ? 'bg-sea-400/10 ring-1 ring-gold-300' : 'hover:bg-marble-100'}`}>
                <Icon name={condition.icon} size={15} className="text-gold-600" />
                <span className="flex-1 text-sm text-sea-500">{tr(condition.name)}</span>
                {selectedCondition === condition.id && <Icon name="check-circle-2" size={15} className="text-gold-600" />}
              </button>
            ))}
          </div>
        </Card>
        <Card className="lg:col-span-8" padding="p-7">
          <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{lang === 'zh' ? '当前问题' : 'Selected concern'}</div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-[28px] text-sea-500`}>{tr(selected.name)}</h3>
              <p className="mt-1 max-w-xl text-sm leading-relaxed text-sea-400/75">{tr(selected.short)}</p>
            </div>
          </div>
          <div className="grid gap-3 md:grid-cols-2">
            {selected.docs.map((doc, index) => (
              <div
                key={doc.en}
                className="flex items-center gap-3 rounded-2xl bg-white p-4 text-left ring-1 hairline"
              >
                <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-marble-100 text-gold-700">
                  <Icon name="file-text" size={15} />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="text-sm font-medium text-sea-500">{tr(doc)}</div>
                  <div className="font-mono-display mt-0.5 text-[10px] text-marble-500">{lang === 'zh' ? '通常需要资料' : 'Commonly requested'} · {String(index + 1).padStart(2, '0')}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="mt-5 rounded-2xl bg-marble-50 p-4 ring-1 hairline">
            <div className="mb-1 text-[10px] font-medium uppercase tracking-[0.2em] text-marble-500">{copy.nextStep}</div>
            <div className="text-sm leading-relaxed text-sea-500">{tr(selected.next)}</div>
          </div>
        </Card>
      </div>
    </>
  );
};

const resultTitleOf = (lang, nextAction) => {
  const titles = {
    'Local emergency first': { zh: '请先在当地急诊处理', en: 'Seek local emergency care first' },
    'Collect records': { zh: '建议先补齐关键资料', en: 'Collect key records first' },
    'Pathway consult': { zh: '适合先做路径咨询', en: 'Start with pathway consultation' },
    'Specialist review': { zh: '适合进入中国专家二诊预评估', en: 'Proceed to China specialist pre-assessment' },
    'Free triage': { zh: '适合先做免费初步判断', en: 'Start with free initial review' }
  };
  return (titles[nextAction] || titles['Free triage'])[lang];
};

const formatFileSize = (bytes = 0) => {
  if (!bytes) return '';
  if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
};

const AttachmentField = ({ lang, files = [], onChange }) => {
  const [warning, setWarning] = React.useState('');
  const removeFile = (indexToRemove) => onChange(files.filter((_, index) => index !== indexToRemove));
  const addFiles = (fileList) => {
    const selected = Array.from(fileList || []).map((file) => ({
      name: file.name,
      size: file.size,
      type: file.type || 'unknown',
      lastModified: file.lastModified || 0
    }));
    const accepted = selected.filter((file) => file.size <= MAX_ATTACHMENT_BYTES);
    const rejectedBySize = selected.length - accepted.length;
    const merged = [...files];
    accepted.forEach((file) => {
      const signature = `${file.name}-${file.size}-${file.lastModified}`;
      if (!merged.some((item) => `${item.name}-${item.size}-${item.lastModified || 0}` === signature)) merged.push(file);
    });
    const limited = merged.slice(0, MAX_ATTACHMENT_COUNT);
    const rejectedByCount = Math.max(0, merged.length - MAX_ATTACHMENT_COUNT);
    onChange(limited);
    if (rejectedBySize || rejectedByCount) {
      setWarning(lang === 'zh'
        ? `已保留前 ${MAX_ATTACHMENT_COUNT} 个附件；单个文件不能超过 ${formatFileSize(MAX_ATTACHMENT_BYTES)}。`
        : `Kept up to ${MAX_ATTACHMENT_COUNT} attachments; each file must be under ${formatFileSize(MAX_ATTACHMENT_BYTES)}.`);
    } else {
      setWarning('');
    }
  };
  return (
    <div className="rounded-3xl bg-marble-50 p-4 ring-1 hairline">
      <div className="mb-3 flex items-start justify-between gap-3">
        <div>
          <div className="mb-1.5 flex items-center gap-1 text-[11px] font-medium uppercase tracking-[0.16em] text-marble-500">
            {lang === 'zh' ? '上传报告 / 附件' : 'Reports / attachments'}
          </div>
          <p className="text-sm leading-relaxed text-sea-400/78">
            {lang === 'zh'
              ? `这个阶段可以上传任意文件，最多 ${MAX_ATTACHMENT_COUNT} 个，每个不超过 ${formatFileSize(MAX_ATTACHMENT_BYTES)}。建议放入当地医院诊断报告、检查报告、CT/MRI/超声/内镜影像资料、病理报告、用药清单和本地医生建议。`
              : `Any file type is accepted for now, up to ${MAX_ATTACHMENT_COUNT} files, each under ${formatFileSize(MAX_ATTACHMENT_BYTES)}. Suggested files: local diagnosis notes, lab reports, CT/MRI/ultrasound/endoscopy imaging, pathology reports, medication list, and local doctor advice.`}
          </p>
        </div>
        <Icon name="paperclip" size={20} className="mt-1 shrink-0 text-gold-600" />
      </div>
      <label className="flex cursor-pointer flex-col items-center justify-center rounded-2xl border border-dashed border-gold-300 bg-white px-4 py-5 text-center transition hover:bg-gold-50/60">
        <Icon name="upload-cloud" size={22} className="mb-2 text-gold-600" />
        <span className="text-sm font-medium text-sea-500">{lang === 'zh' ? '继续添加文件' : 'Add files'}</span>
        <span className="mt-1 text-[11px] text-marble-500">
          {lang === 'zh' ? `${files.length}/${MAX_ATTACHMENT_COUNT} 已选，重复选择不会覆盖` : `${files.length}/${MAX_ATTACHMENT_COUNT} selected, adding will not replace`}
        </span>
        <input
          type="file"
          multiple
          className="sr-only"
          onChange={(event) => {
            addFiles(event.target.files);
            event.target.value = '';
          }}
        />
      </label>
      {warning && <div className="mt-3 rounded-2xl bg-gold-50 p-3 text-sm text-sea-500 ring-1 ring-gold-200">{warning}</div>}
      {files.length ? (
        <div className="mt-3 space-y-2">
          {files.map((file, index) => (
            <div key={`${file.name}-${index}`} className="flex items-center justify-between gap-3 rounded-2xl bg-white p-3 text-sm ring-1 hairline">
              <span className="min-w-0 truncate text-sea-500">{file.name}</span>
              <div className="flex shrink-0 items-center gap-2">
                <span className="font-mono-display text-[11px] text-marble-500">{formatFileSize(file.size)}</span>
                <button type="button" onClick={() => removeFile(index)} className="flex h-7 w-7 items-center justify-center rounded-xl bg-marble-100 text-sea-400 transition hover:bg-rose-50 hover:text-rose-700" title={lang === 'zh' ? '移除附件' : 'Remove attachment'}>
                  <Icon name="x" size={14} />
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
};

const IntakeSection = ({ lang, tr, form, updateForm, errors, submitForm, resetForm, lastResult, submitError, authSession, config, whatsappUrl, copy }) => {
  const serviceSceneOptions = SERVICE_SCENES.map((scene) => ({ value: scene.id, label: textOf(scene.name, lang) }));
  const conditionOptions = [
    ...getFocusConditions().map((item) => ({ value: item.id, label: `${getConditionGroupLabel(item, lang)} · ${tr(item.name)}` })),
    ...getSupportConditions().map((item) => ({ value: item.id, label: `${getConditionGroupLabel(item, lang)} · ${tr(item.name)}` })),
    { value: 'other', label: lang === 'zh' ? '其他问题 / 需要人工判断' : 'Other concern / needs manual review' }
  ];
  const countryOptions = COUNTRIES.map((country) => ({ value: country, label: country }));
  const selectedScene = getServiceScene(form.serviceScene);

  return (
    <div className="intake-modal-body space-y-5">
      <div className="rounded-3xl bg-gold-50/80 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-100">
        <div className="mb-1 flex items-center gap-2 font-semibold text-gold-700">
          <Icon name="lock-keyhole" size={15} />
          {lang === 'zh' ? '隐私保护声明' : 'Privacy note'}
        </div>
        {lang === 'zh'
          ? '你提交的信息仅用于华医畅服务团队进行资料初筛、联系沟通和后续路径判断。未进入正式服务前，平台不会公开展示你的医疗资料。'
          : 'Your information is used only for HuaMed team triage, contact, and pathway review. Medical records are not publicly displayed before a formal service stage begins.'}
      </div>
      <form onSubmit={submitForm} className="space-y-4">
        <div className="grid gap-4 md:grid-cols-2">
          <Field label={lang === 'zh' ? '姓名 / 称呼' : 'Name'} value={form.name} onChange={(v) => updateForm('name', v)} required error={errors.name} placeholder="Ms. Lim" />
          <SelectField label={lang === 'zh' ? '国家 / 地区' : 'Country'} value={form.country} onChange={(v) => updateForm('country', v)} options={countryOptions} required error={errors.country} />
          <Field label={lang === 'zh' ? '城市' : 'City'} value={form.city} onChange={(v) => updateForm('city', v)} required error={errors.city} placeholder="Kuala Lumpur" />
          <Field label={lang === 'zh' ? 'WhatsApp 手机号' : 'WhatsApp number'} value={form.contact} onChange={(v) => updateForm('contact', v)} required error={errors.contact} placeholder={contactHintForCountry(form.country, lang)} />
          <SelectField label={lang === 'zh' ? '服务场景' : 'Service scenario'} value={form.serviceScene} onChange={(v) => {
            updateForm('serviceScene', v);
            if (v !== 'medical') updateForm('conditionId', v);
          }} options={serviceSceneOptions} required error={errors.serviceScene} />
          {form.serviceScene === 'medical' ? (
            <SelectField label={lang === 'zh' ? '病种 / 诊疗场景' : 'Condition / care scenario'} value={form.conditionId} onChange={(v) => updateForm('conditionId', v)} options={conditionOptions} required error={errors.conditionId} />
          ) : (
            <div className="rounded-2xl bg-marble-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 hairline">
              <div className="mb-1 font-semibold">{textOf(selectedScene.name, lang)}</div>
              {textOf(selectedScene.short, lang)}
            </div>
          )}
        </div>
        <AttachmentField
          lang={lang}
          files={form.attachmentSummary || []}
          onChange={(files) => updateForm('attachmentSummary', files)}
        />
        <TextareaField label={lang === 'zh' ? '主诉 / 当前最想解决的问题' : 'Chief concern / main question'} value={form.notes} onChange={(v) => updateForm('notes', v)} placeholder={lang === 'zh' ? '请简单描述最关心的问题、已有检查和家庭决策困惑。' : 'Briefly describe the key concern, existing reports, and family decision questions.'} />
        <TextareaField label={lang === 'zh' ? '本地医生建议' : 'Local doctor recommendation'} value={form.doctorAdvice} onChange={(v) => updateForm('doctorAdvice', v)} placeholder={lang === 'zh' ? '如暂时没有，可以留空。' : 'Leave blank if not available.'} />
        {Object.values(errors).some(Boolean) && (
          <div className="rounded-2xl bg-rose-50 p-3 text-sm text-rose-700 ring-1 ring-rose-100">{copy.formRequired}</div>
        )}
        {submitError && (
          <div className={`rounded-2xl p-3 text-sm ring-1 ${submitError.includes('已提交') || submitError.includes('submitted') ? 'bg-emerald-50 text-emerald-700 ring-emerald-100' : 'bg-rose-50 text-rose-700 ring-rose-100'}`}>
            {submitError}
          </div>
        )}
        <div className="flex flex-wrap gap-3">
          <Button type="submit" icon={authSession?.role === 'client' ? 'send-horizontal' : 'lock-keyhole'}>
            {authSession?.role === 'client' ? (lang === 'zh' ? '提交信息' : 'Submit information') : (lang === 'zh' ? '登录后提交' : 'Sign in to submit')}
          </Button>
          <Button variant="ghost" icon="rotate-ccw" onClick={resetForm}>{copy.reset}</Button>
        </div>
      </form>
      {lastResult && (
        <div className="space-y-3 rounded-3xl bg-emerald-50 p-4 text-sm leading-relaxed text-emerald-800 ring-1 ring-emerald-100">
          <div className="font-semibold">{lang === 'zh' ? '提交成功，我们将在 24 小时内初步查看。' : 'Submitted. We will review within 24 hours.'}</div>
          <ResultCopy lang={lang} lead={lastResult} />
          <div className="flex flex-wrap gap-2">
            <Button variant="ghost" icon="home" onClick={() => window.location.href = 'index.html'}>{lang === 'zh' ? '返回首页' : 'Home'}</Button>
            <Button
              icon="message-circle"
              disabled={!whatsappUrl && !config?.whatsappConfigured}
              onClick={() => {
                const url = whatsappUrl || whatsappUrlFromConfig(config, lastResult);
                if (url) window.location.href = url;
              }}
            >
              {lang === 'zh' ? 'WhatsApp 联系我们' : 'Contact on WhatsApp'}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

const ResultCopy = ({ lang, lead }) => {
  const lines = {
    'Local emergency first': {
      zh: '当前选择了急性/紧急情况。建议先在当地急诊处理，华医畅暂不适合作为第一响应。',
      en: 'The case is marked as acute or urgent. Local emergency care should be the first response; HuaMed is not suitable as first-line emergency support.'
    },
    'Collect records': {
      zh: '目前资料不足。建议先补充报告、影像原片和本地医生建议，再进入免费初步判断。',
      en: 'Records are insufficient. Please collect reports, imaging files, and local recommendations before the initial review.'
    },
    'Pathway consult': {
      zh: '适合先进入路径咨询，明确是否需要中国专家二诊，以及是否值得来华面诊。',
      en: 'A pathway consultation is recommended before deciding on specialist review or China visit.'
    },
    'Specialist review': {
      zh: '资料和意向度较好，建议进入中国专家二诊预评估。',
      en: 'Record readiness and intent are strong. China specialist second opinion is recommended.'
    },
    'Free triage': {
      zh: '建议先完成免费初步判断，确认需求、资料完整度和服务适配性。',
      en: 'Start with a free initial review to confirm need, record readiness, and service fit.'
    }
  };
  const item = lines[lead.nextAction] || lines['Free triage'];
  return (
    <div className="rounded-2xl bg-white p-4 text-sm leading-relaxed text-sea-500 ring-1 hairline">
      {item[lang]}
    </div>
  );
};

const LeadsSection = ({ lang, tr, leads, changeLeadStatus, updateLeadField, addDemoLead, webhookUrl, setWebhookUrl, mockWebhook, webhookStatus, copy }) => {
  const [statusFilter, setStatusFilter] = React.useState('All');
  const [sourceFilter, setSourceFilter] = React.useState('All');
  const insights = getOpsInsights(leads);
  const sourceFilters = ['All', ...Array.from(new Set(leads.map((lead) => lead.source || 'Website intake')))];
  const filtered = leads.filter((lead) => {
    const statusMatch = statusFilter === 'All' || lead.status === statusFilter;
    const sourceMatch = sourceFilter === 'All' || (lead.source || 'Website intake') === sourceFilter;
    return statusMatch && sourceMatch;
  });
  const statusOptions = ['All', ...OPS_STATUSES];
  const adminCopy = {
    zh: {
      subtitle: '仅在运营端页面显示。客户前台不展示评分、Webhook、内部状态或线索表。',
      sourceQuality: '渠道质量',
      conditionMix: '病种线索',
      sixtyDays: '60 天复盘',
      webhookBody: '第一版先本地保存。这里预留飞书、Notion、Airtable 或自建后端 webhook 地址。',
      testSend: '测试发送',
      empty: '暂无符合筛选条件的线索。'
    },
    en: {
      subtitle: 'Visible only in the ops portal. The client frontstage does not show scores, webhooks, internal statuses, or lead tables.',
      sourceQuality: 'Channel quality',
      conditionMix: 'Condition leads',
      sixtyDays: '60-day review',
      webhookBody: 'v0.1 saves locally. This field reserves a webhook for Feishu, Notion, Airtable, or a custom backend.',
      testSend: 'Test Send',
      empty: 'No leads match the current filters.'
    }
  }[lang];

  return (
    <>
      <SectionHeader
        eyebrow="Operations"
        lang={lang}
        title={{ zh: copy.sectionLeads, en: copy.sectionLeads }}
        subtitle={{ zh: adminCopy.subtitle, en: adminCopy.subtitle }}
        right={
          <div className="flex flex-wrap gap-2">
            <Button variant="ghost" icon="plus" onClick={addDemoLead}>{copy.addDemo}</Button>
            <Button icon="file-down" onClick={() => downloadCsv(leads)}>{copy.exportCsv}</Button>
          </div>
        }
      />
      <div className="mb-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MiniMetric label={lang === 'zh' ? '60 天线索' : '60-day leads'} value={insights.total} />
        <MiniMetric label={lang === 'zh' ? '付费转化' : 'Paid conversion'} value={insights.paidConversion} />
        <MiniMetric label={lang === 'zh' ? '来华意向' : 'China intent'} value={insights.chinaIntent} />
        <MiniMetric label={lang === 'zh' ? '资料完整' : 'Record readiness'} value={insights.recordsReady} />
      </div>
      <div className="grid gap-6 xl:grid-cols-12">
        <Card className="min-w-0 overflow-hidden xl:col-span-9" padding="p-0">
          <div className="grid gap-3 border-b hairline p-4 lg:grid-cols-[1fr_auto] lg:items-center">
            <div className="flex flex-wrap items-center gap-2">
              {statusOptions.map((status) => (
                <button key={status} onClick={() => setStatusFilter(status)} className={`h-9 rounded-full px-3 text-[12px] font-medium transition ${statusFilter === status ? 'gold-gradient text-sea-600 shadow-soft' : 'bg-white text-sea-400 ring-1 hairline hover:ring-gold-300'}`}>
                  {status === 'All' ? (lang === 'zh' ? '全部' : 'All') : labelOf(STATUS_LABELS, status, lang)}
                </button>
              ))}
            </div>
            <select value={sourceFilter} onChange={(event) => setSourceFilter(event.target.value)} className="h-9 rounded-xl bg-white px-3 text-[12px] text-sea-500 ring-1 hairline">
              {sourceFilters.map((source) => (
                <option key={source} value={source}>{source === 'All' ? (lang === 'zh' ? '全部来源' : 'All sources') : source}</option>
              ))}
            </select>
          </div>
          {filtered.length === 0 ? (
            <div className="p-8 text-sm text-sea-400">{adminCopy.empty}</div>
          ) : (
            <div className="max-w-full overflow-auto scroll-soft">
              <table className="w-full min-w-[1360px] text-left text-sm">
                <thead className="bg-marble-50 text-[10px] uppercase tracking-[0.18em] text-marble-500">
                  <tr>
                    <th className="px-5 py-3">Lead</th>
                    <th className="px-5 py-3">Source</th>
                    <th className="px-5 py-3">Condition</th>
                    <th className="px-5 py-3">Records</th>
                    <th className="px-5 py-3">Intent</th>
                    <th className="px-5 py-3">Score</th>
                    <th className="px-5 py-3">Next</th>
                    <th className="px-5 py-3">Status</th>
                    <th className="px-5 py-3">Reason</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((lead) => (
                    <tr key={lead.id} className="border-t hairline align-top">
                      <td className="px-5 py-4">
                        <div className="font-medium text-sea-500">{lead.name}</div>
                        <div className="font-mono-display mt-0.5 text-[10px] text-marble-500">{lead.id} · {lead.createdAt}</div>
                        <div className="mt-1 max-w-[180px] truncate text-[11px] text-marble-500">{lead.contact}</div>
                      </td>
                      <td className="px-5 py-4">
                        <select value={lead.source || 'Website intake'} onChange={(event) => updateLeadField(lead.id, 'source', event.target.value)} className="h-9 w-[150px] rounded-xl bg-white px-3 text-[12px] text-sea-500 ring-1 hairline">
                          {SOURCE_OPTIONS.includes(lead.source || 'Website intake') ? null : <option value={lead.source}>{lead.source}</option>}
                          {SOURCE_OPTIONS.map((source) => <option key={source} value={source}>{source}</option>)}
                        </select>
                      </td>
                      <td className="max-w-[220px] px-5 py-4">
                        <div className="truncate text-sea-500">{tr(getCondition(lead.conditionId).name)}</div>
                        <div className="text-[11px] text-marble-500">{lead.city} · {lead.country}</div>
                        <div className="text-[11px] text-marble-500">{lead.timeframe}</div>
                      </td>
                      <td className="px-5 py-4">
                        <Pill tone={lead.hasRecords === 'complete' ? 'green' : lead.hasRecords === 'partial' ? 'gold' : 'rose'}>{labelOf(RECORD_LABELS, lead.hasRecords, lang)}</Pill>
                      </td>
                      <td className="px-5 py-4">
                        <div className="flex flex-col gap-1.5">
                          <Pill tone={lead.acceptsPaid === 'yes' ? 'green' : lead.acceptsPaid === 'maybe' ? 'gold' : 'marble'}>{lang === 'zh' ? '付费 ' : 'Paid '}{labelOf(INTENT_LABELS, lead.acceptsPaid, lang)}</Pill>
                          <Pill tone={lead.considersChina === 'yes' ? 'green' : lead.considersChina === 'maybe' ? 'gold' : 'marble'}>{lang === 'zh' ? '来华 ' : 'China '}{labelOf(INTENT_LABELS, lead.considersChina, lang)}</Pill>
                        </div>
                      </td>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-2">
                          <div className="h-2 w-20 overflow-hidden rounded-full bg-marble-200">
                            <div className="h-full gold-gradient" style={{ width: `${lead.score || 0}%` }} />
                          </div>
                          <span className="font-mono-display text-[12px] text-sea-500">{lead.score || 0}</span>
                        </div>
                        <div className="mt-1 text-[11px] text-marble-500">{lead.tier}</div>
                      </td>
                      <td className="px-5 py-4 text-sea-500">{labelOf(NEXT_ACTION_LABELS, lead.nextAction, lang)}</td>
                      <td className="px-5 py-4">
                        <select value={lead.status} onChange={(event) => changeLeadStatus(lead.id, event.target.value)} className="h-9 w-[150px] rounded-xl bg-white px-3 text-[12px] text-sea-500 ring-1 hairline">
                          {OPS_STATUSES.map((status) => <option key={status} value={status}>{labelOf(STATUS_LABELS, status, lang)}</option>)}
                        </select>
                      </td>
                      <td className="px-5 py-4">
                        <select value={lead.rejectionReason || ''} onChange={(event) => updateLeadField(lead.id, 'rejectionReason', event.target.value)} className="h-9 w-[160px] rounded-xl bg-white px-3 text-[12px] text-sea-500 ring-1 hairline">
                          {REJECTION_REASONS.map((reason) => <option key={reason || 'empty'} value={reason}>{reason || (lang === 'zh' ? '未填写' : 'None')}</option>)}
                        </select>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card>
        <div className="space-y-6 xl:col-span-3">
          <Card padding="p-6">
            <div className="mb-4 flex items-center justify-between">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{adminCopy.sixtyDays}</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{adminCopy.conditionMix}</h3>
              </div>
              <Icon name="bar-chart-3" size={22} className="text-gold-600" />
            </div>
            <div className="space-y-3">
              {insights.conditionRows.map(([conditionId, count]) => (
                <div key={conditionId} className="flex items-center justify-between gap-3 rounded-2xl bg-marble-50 p-3 ring-1 hairline">
                  <span className="truncate text-sm text-sea-500">{tr(getCondition(conditionId).name)}</span>
                  <span className="font-mono-display text-sm text-gold-700">{count}</span>
                </div>
              ))}
            </div>
            <div className="mt-5 border-t hairline pt-4">
              <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.18em] text-marble-500">{adminCopy.sourceQuality}</div>
              <div className="space-y-2">
                {insights.sourceRows.map(([source, item]) => (
                  <div key={source} className="flex items-center justify-between gap-3 text-sm">
                    <span className="truncate text-sea-400">{source}</span>
                    <span className="font-mono-display text-sea-500">{pct(item.quality, item.total)}</span>
                  </div>
                ))}
              </div>
            </div>
          </Card>
          <Card padding="p-6">
            <div className="mb-4 flex items-center justify-between">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Webhook</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '集成预留' : 'Integration stub'}</h3>
              </div>
              <Icon name="plug-zap" size={22} className="text-gold-600" />
            </div>
            <p className="mb-4 text-sm leading-relaxed text-sea-400/75">{adminCopy.webhookBody}</p>
            <Field label="Webhook URL" value={webhookUrl} onChange={setWebhookUrl} placeholder="https://..." />
            <Button variant="sea" icon="send" onClick={mockWebhook} className="mt-3 w-full">{adminCopy.testSend}</Button>
            {webhookStatus && <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-sm text-emerald-700 ring-1 ring-emerald-100">{webhookStatus}</div>}
            <div className="mt-5 grid grid-cols-2 gap-3">
              <MiniMetric label={lang === 'zh' ? '总线索' : 'Leads'} value={leads.length} />
              <MiniMetric label={lang === 'zh' ? '高意向' : 'High'} value={leads.filter((lead) => lead.tier === 'High').length} />
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const CaseFlowSection = ({ lang, tr, leads, doctorProfiles, focusLeadId, changeLeadStatus, updateLeadField, toggleLeadRecord }) => {
  const flowLeads = leads.filter((lead) => !['Rejected', 'Closed'].includes(lead.status));
  const [activeLeadId, setActiveLeadId] = React.useState(() => flowLeads[0]?.id || leads[0]?.id || '');
  const selectedLead = leads.find((lead) => lead.id === activeLeadId) || flowLeads[0] || leads[0];
  const publishedDoctors = doctorProfiles.filter((profile) => profile.isPublished);

  React.useEffect(() => {
    if (!selectedLead && leads[0]) setActiveLeadId(leads[0].id);
  }, [selectedLead, leads]);

  React.useEffect(() => {
    if (focusLeadId && leads.some((lead) => lead.id === focusLeadId)) setActiveLeadId(focusLeadId);
  }, [focusLeadId, leads]);

  if (!selectedLead) {
    return (
      <>
        <SectionHeader
          eyebrow="Case Flow"
          lang={lang}
          title={{ zh: '病历流转', en: 'Case package flow' }}
          subtitle={{ zh: '暂无线索。客户提交或运营添加测试线索后，这里会显示病历流转。', en: 'No leads yet. Case flow appears after client submissions or demo leads.' }}
        />
        <Card padding="p-8">
          <div className="text-sm text-sea-400">{lang === 'zh' ? '暂无可流转病例。' : 'No case available.'}</div>
        </Card>
      </>
    );
  }

  const recordItems = getRecordItems(selectedLead, lang);
  const readiness = getRecordReadiness(selectedLead);
  const matchedDoctor = publishedDoctors.find((profile) => profile.id === selectedLead.matchedDoctorId);
  const doctorFeedback = normalizeDoctorFeedback(selectedLead.doctorFeedback);
  const clientSummary = selectedLead.clientPathwaySummary || buildClientPathwaySummary(selectedLead, lang);
  const flowStage = getCaseFlowStage(selectedLead);
  const packageId = `PKG-${selectedLead.id.replace('HMD-', '')}`;
  const doctorOptions = [
    { value: '', label: lang === 'zh' ? '暂不匹配医生' : 'No doctor matched' },
    ...publishedDoctors.map((profile) => ({
      value: profile.id,
      label: `${textOf(profile.displayName, lang)} · ${textOf(profile.department, lang)}`
    }))
  ];
  const stageRows = [
    { id: 'Records Pending', icon: 'files', title: lang === 'zh' ? '资料补齐' : 'Records', text: lang === 'zh' ? '确认报告、影像、病理和本地建议是否齐全。' : 'Confirm reports, imaging, pathology, and local advice.' },
    { id: 'Case Packaging', icon: 'folder-heart', title: lang === 'zh' ? '病例包' : 'Case package', text: lang === 'zh' ? '整理摘要、问题清单和资料缺口。' : 'Prepare summary, questions, and record gaps.' },
    { id: 'Doctor Review', icon: 'stethoscope', title: lang === 'zh' ? '医生预评估' : 'Doctor review', text: lang === 'zh' ? '匹配已上架医生，只提交适合的择期病例。' : 'Match a published doctor for suitable elective cases.' },
    { id: 'Pathway Consult', icon: 'route', title: lang === 'zh' ? '路径反馈' : 'Pathway feedback', text: lang === 'zh' ? '运营反馈客户，并判断是否进入来华协调。' : 'Ops reports back and decides China pathway fit.' }
  ];
  const stageIndex = stageRows.findIndex((item) => item.id === flowStage);

  const setStatusAndNote = (status, note) => {
    changeLeadStatus(selectedLead.id, status);
    if (note) updateLeadField(selectedLead.id, 'casePackageNote', note);
  };

  const submitDoctorReview = () => {
    if (!selectedLead.matchedDoctorId || readiness.pct < 100) return;
    changeLeadStatus(selectedLead.id, 'Doctor Review');
    updateLeadField(selectedLead.id, 'nextAction', 'Specialist review');
  };

  return (
    <>
      <SectionHeader
        eyebrow="Case Flow"
        lang={lang}
        title={{ zh: '病历流转：从线索到医生预评估', en: 'Case flow: from lead to doctor review' }}
        subtitle={{
          zh: '运营先补齐资料、整理病例包，再匹配已上架医生。这里是内部工作区，不会展示给客户。',
          en: 'Ops completes records, prepares the case package, then matches a published doctor. This workspace is internal only.'
        }}
        right={<Pill tone="sea" icon="folder-kanban">{lang === 'zh' ? '内部病例流转' : 'Internal case flow'}</Pill>}
      />

      <div className="mb-5 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        {stageRows.map((stage, index) => {
          const done = stageIndex > index || selectedLead.status === 'Pathway Consult';
          const active = stage.id === flowStage;
          return (
            <Card key={stage.id} padding="p-5" className={active ? 'ring-gold-300' : ''}>
              <div className="mb-3 flex items-center justify-between">
                <div className={`flex h-11 w-11 items-center justify-center rounded-2xl ${done || active ? 'sea-gradient text-gold-300' : 'bg-marble-100 text-sea-400'}`}>
                  <Icon name={done ? 'check' : stage.icon} size={18} />
                </div>
                <span className="font-mono-display text-[11px] text-marble-500">{String(index + 1).padStart(2, '0')}</span>
              </div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-lg text-sea-500`}>{stage.title}</h3>
              <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{stage.text}</p>
            </Card>
          );
        })}
      </div>

      <div className="grid gap-6 xl:grid-cols-12">
        <Card className="xl:col-span-3" padding="p-0">
          <div className="border-b hairline p-5">
            <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Case Queue</div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '待流转病例' : 'Case queue'}</h3>
          </div>
          <div className="max-h-[620px] overflow-auto p-3 scroll-soft">
            {flowLeads.map((lead) => {
              const itemReadiness = getRecordReadiness(lead);
              const active = lead.id === selectedLead.id;
              return (
                <button
                  key={lead.id}
                  onClick={() => setActiveLeadId(lead.id)}
                  className={`mb-2 block w-full rounded-2xl p-3 text-left transition ring-1 ${active ? 'bg-gold-50 ring-gold-200' : 'bg-white hairline hover:ring-gold-200'}`}
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="truncate text-sm font-medium text-sea-500">{lead.name}</span>
                    <Pill tone={itemReadiness.pct === 100 ? 'green' : 'gold'}>{itemReadiness.pct}%</Pill>
                  </div>
                  <div className="mt-1 truncate text-[11px] text-marble-500">{lead.id} · {labelOf(STATUS_LABELS, lead.status, lang)}</div>
                  <div className="mt-1 truncate text-[12px] text-sea-400">{tr(getCondition(lead.conditionId).name)}</div>
                </button>
              );
            })}
          </div>
        </Card>

        <div className="space-y-6 xl:col-span-5">
          <Card padding="p-6">
            <div className="mb-5 flex flex-wrap items-start justify-between gap-3">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{packageId}</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '病例包工作台' : 'Case package workspace'}</h3>
                <p className="mt-1 text-sm leading-relaxed text-sea-400/75">{selectedLead.name} · {tr(getCondition(selectedLead.conditionId).name)}</p>
              </div>
              <Pill tone={readiness.pct === 100 ? 'green' : 'gold'} icon="clipboard-check">
                {lang === 'zh' ? `资料 ${readiness.ready}/${readiness.total}` : `Records ${readiness.ready}/${readiness.total}`}
              </Pill>
            </div>

            <div className="mb-5 overflow-hidden rounded-full bg-marble-200">
              <div className="h-2 gold-gradient transition-all" style={{ width: `${readiness.pct}%` }} />
            </div>

            <div className="space-y-2">
              {recordItems.map((item) => (
                <button
                  key={item.key}
                  onClick={() => toggleLeadRecord(selectedLead.id, item.key)}
                  className={`flex w-full items-center justify-between gap-3 rounded-2xl p-3 text-left ring-1 transition ${item.ready ? 'bg-emerald-50 text-emerald-800 ring-emerald-100' : 'bg-marble-50 text-sea-500 hairline hover:ring-gold-200'}`}
                >
                  <span className="flex items-center gap-2 text-sm">
                    <Icon name={item.ready ? 'check-circle-2' : 'circle'} size={16} />
                    {item.label}
                  </span>
                  <span className="text-[11px] uppercase tracking-[0.14em]">{item.ready ? (lang === 'zh' ? '已收' : 'Ready') : (lang === 'zh' ? '缺口' : 'Gap')}</span>
                </button>
              ))}
            </div>

            <div className="mt-5 rounded-3xl bg-marble-50 p-4 ring-1 hairline">
              <div className="mb-3 flex items-center justify-between gap-3">
                <div>
                  <div className="text-[10px] font-medium uppercase tracking-[0.18em] text-gold-600">{lang === 'zh' ? '客户资料' : 'Client records'}</div>
                  <div className="mt-1 text-sm text-sea-500">{selectedLead.contact || '-'}</div>
                </div>
                <Icon name="paperclip" size={18} className="text-gold-600" />
              </div>
              {selectedLead.attachmentSummary?.length ? (
                <div className="space-y-2">
                  {selectedLead.attachmentSummary.map((file, index) => (
                    <div key={`${file.name}-${index}`} className="flex items-center justify-between gap-3 rounded-2xl bg-white p-3 text-sm ring-1 hairline">
                      <span className="min-w-0 truncate text-sea-500">{file.name}</span>
                      <span className="shrink-0 font-mono-display text-[11px] text-marble-500">{formatFileSize(file.size)}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="rounded-2xl bg-white p-3 text-sm leading-relaxed text-sea-400 ring-1 hairline">
                  {lang === 'zh' ? '客户尚未选择附件，运营可在 WhatsApp 跟进当地医院诊断报告、影像资料、病理报告和用药清单。' : 'No attachments selected yet. Ops can follow up on WhatsApp for local diagnosis reports, imaging, pathology, and medication list.'}
                </div>
              )}
            </div>

            <div className="mt-5 grid gap-3 md:grid-cols-3">
              <Button variant="ghost" icon="file-warning" onClick={() => setStatusAndNote('Records Pending', lang === 'zh' ? '已标记资料缺口，等待客户补充。' : 'Marked record gaps; waiting for client supplement.')}>
                {lang === 'zh' ? '标记待补' : 'Mark pending'}
              </Button>
              <Button variant="sea" icon="folder-check" onClick={() => setStatusAndNote('Case Packaging', lang === 'zh' ? '病例包已进入整理。' : 'Case package is being prepared.')}>
                {lang === 'zh' ? '整理病例包' : 'Package case'}
              </Button>
              <Button icon="send" disabled={!selectedLead.matchedDoctorId || readiness.pct < 100} onClick={submitDoctorReview}>
                {lang === 'zh' ? '提交医生' : 'Send to doctor'}
              </Button>
            </div>
          </Card>

          <Card padding="p-6">
            <TextareaField
              label={lang === 'zh' ? '病例摘要' : 'Case summary'}
              value={selectedLead.caseSummary || ''}
              onChange={(value) => updateLeadField(selectedLead.id, 'caseSummary', value)}
              placeholder={lang === 'zh' ? '整理客户基础情况、时间线、本地医生建议和家庭问题。' : 'Summarize profile, timeline, local recommendation, and family questions.'}
            />
            <TextareaField
              label={lang === 'zh' ? '运营备注' : 'Ops note'}
              value={selectedLead.casePackageNote || ''}
              onChange={(value) => updateLeadField(selectedLead.id, 'casePackageNote', value)}
              placeholder={lang === 'zh' ? '例如：等待 CT DICOM；已确认愿意付费二诊。' : 'Example: waiting for CT DICOM; paid review intent confirmed.'}
            />
          </Card>
        </div>

        <div className="space-y-6 xl:col-span-4">
          <Card padding="p-6">
            <div className="mb-5 flex items-center justify-between">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Doctor Match</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '匹配医生' : 'Match doctor'}</h3>
              </div>
              <Icon name="stethoscope" size={24} className="text-gold-600" />
            </div>
            <SelectField
              label={lang === 'zh' ? '已上架医生' : 'Published doctor'}
              value={selectedLead.matchedDoctorId || ''}
              onChange={(value) => updateLeadField(selectedLead.id, 'matchedDoctorId', value)}
              options={doctorOptions}
            />
            {matchedDoctor ? (
              <div className="mt-5 rounded-3xl bg-marble-50 p-4 ring-1 hairline">
                <div className="flex flex-wrap items-center gap-2">
                  <h4 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{textOf(matchedDoctor.displayName, lang)}</h4>
                  <Pill tone="green" icon="eye">{lang === 'zh' ? '已上架' : 'Published'}</Pill>
                </div>
                <div className="mt-1 text-sm text-sea-400">{textOf(matchedDoctor.hospital, lang)} · {textOf(matchedDoctor.department, lang)}</div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {(matchedDoctor.focus?.[lang] || []).slice(0, 4).map((item) => <Pill key={item} tone="gold">{item}</Pill>)}
                </div>
              </div>
            ) : (
              <div className="mt-5 rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
                {publishedDoctors.length
                  ? (lang === 'zh' ? '请选择一个已上架医生。资料未齐时不建议提交医生预评估。' : 'Choose a published doctor. Do not submit to doctor review before records are complete.')
                  : (lang === 'zh' ? '暂无已上架医生。请先在“医生档案”模块上架医生。' : 'No published doctors yet. Publish a doctor in the Doctors module first.')}
              </div>
            )}
          </Card>

          <Card padding="p-6">
            <div className="mb-4 flex items-center justify-between">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Preview</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '医生端病例包预览' : 'Doctor case preview'}</h3>
              </div>
              <Icon name="file-text" size={24} className="text-gold-600" />
            </div>
            <div className="space-y-3">
              {[
                [lang === 'zh' ? '病例包编号' : 'Package ID', packageId],
                [lang === 'zh' ? '患者展示' : 'Patient display', lang === 'zh' ? '匿名客户，不显示联系方式' : 'Anonymized client, no contact shown'],
                [lang === 'zh' ? '病种方向' : 'Condition', tr(getCondition(selectedLead.conditionId).name)],
                [lang === 'zh' ? '资料完整度' : 'Record readiness', `${readiness.pct}%`],
                [lang === 'zh' ? '下一步' : 'Next action', labelOf(NEXT_ACTION_LABELS, selectedLead.nextAction, lang)]
              ].map(([label, value]) => (
                <div key={label} className="rounded-2xl bg-marble-50 p-3 ring-1 hairline">
                  <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{label}</div>
                  <div className="mt-1 text-sm leading-relaxed text-sea-500">{value}</div>
                </div>
              ))}
            </div>
            <div className="mt-4 rounded-2xl bg-emerald-50 p-3 text-sm leading-relaxed text-emerald-800 ring-1 ring-emerald-100">
              {lang === 'zh'
                ? '医生账号后续只看此类匿名病例包、关键资料缺口和运营整理问题，不直接获取客户联系方式。'
                : 'Doctor accounts will only see anonymized case packages, key record gaps, and ops-prepared questions, not client contact details.'}
            </div>
          </Card>

          <Card padding="p-6">
            <div className="mb-4 flex items-center justify-between gap-3">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Doctor Feedback</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '医生反馈回收' : 'Feedback received'}</h3>
              </div>
              <Pill tone={doctorFeedback.status === 'Submitted' ? 'green' : doctorFeedback.status === 'Draft' ? 'gold' : 'marble'} icon={doctorFeedback.status === 'Submitted' ? 'check-circle-2' : 'clock'}>
                {labelOf(DOCTOR_FEEDBACK_STATUS_LABELS, doctorFeedback.status, lang)}
              </Pill>
            </div>
            {doctorFeedback.status === 'Submitted' ? (
              <div className="space-y-3">
                {[
                  [lang === 'zh' ? '反馈医生' : 'Reviewer', doctorFeedback.reviewerName || (matchedDoctor ? textOf(matchedDoctor.displayName, lang) : '-')],
                  [lang === 'zh' ? '评估时间' : 'Reviewed at', doctorFeedback.reviewedAt || '-'],
                  [lang === 'zh' ? '路径适配' : 'Pathway fit', feedbackLabel(doctorFeedback.pathwayFit, lang)],
                  [lang === 'zh' ? '来华适配' : 'China visit fit', feedbackLabel(doctorFeedback.chinaVisitFit, lang)]
                ].map(([label, value]) => (
                  <div key={label} className="rounded-2xl bg-marble-50 p-3 ring-1 hairline">
                    <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{label}</div>
                    <div className="mt-1 text-sm leading-relaxed text-sea-500">{value}</div>
                  </div>
                ))}
                <div className="rounded-2xl bg-emerald-50 p-3 text-sm leading-relaxed text-emerald-800 ring-1 ring-emerald-100">
                  {doctorFeedback.assessment || (lang === 'zh' ? '医生已提交预评估，但尚未填写核心判断。' : 'The doctor submitted feedback without a detailed assessment.')}
                </div>
                <TextareaField
                  label={lang === 'zh' ? '客户可读摘要' : 'Client-readable summary'}
                  value={clientSummary}
                  onChange={(value) => updateLeadField(selectedLead.id, 'clientPathwaySummary', value)}
                  placeholder={lang === 'zh' ? '运营整理为客户可读版本，不直接暴露内部字段。' : 'Ops rewrites this into client-readable language without internal fields.'}
                />
                <Button
                  icon="route"
                  onClick={() => {
                    updateLeadField(selectedLead.id, 'clientPathwaySummary', clientSummary || buildClientPathwaySummary(selectedLead, lang));
                    changeLeadStatus(selectedLead.id, 'Pathway Consult');
                  }}
                  className="w-full"
                >
                  {lang === 'zh' ? '进入路径反馈' : 'Move to pathway feedback'}
                </Button>
              </div>
            ) : (
              <div className="rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
                {lang === 'zh'
                  ? '医生端提交预评估后，这里会显示反馈状态、路径适配和运营可整理给客户的摘要。'
                  : 'After the doctor submits pre-assessment feedback, ops will see the review status, pathway fit, and a client-readable summary here.'}
              </div>
            )}
          </Card>
        </div>
      </div>
    </>
  );
};

const OpsOverviewSection = ({ lang, leads, doctorProfiles = [] }) => {
  const insights = getOpsInsights(leads);
  const publishedDoctors = doctorProfiles.filter((profile) => profile.isPublished).length;
  const steps = [
    {
      icon: 'inbox',
      title: lang === 'zh' ? '线索进入' : 'Lead capture',
      text: lang === 'zh' ? '客户提交情况后进入本地线索池，保留来源、病种、资料和联系信息。' : 'Client submissions enter the local lead pool with source, condition, records, and contact details.'
    },
    {
      icon: 'clipboard-check',
      title: lang === 'zh' ? '运营判断' : 'Ops triage',
      text: lang === 'zh' ? '运营先看资料完整度、付费意向、来华意向和是否适合首期承接。' : 'Ops reviews record readiness, paid intent, China visit intent, and service fit.'
    },
    {
      icon: 'stethoscope',
      title: lang === 'zh' ? '医生匹配' : 'Doctor matching',
      text: lang === 'zh' ? '只把资料较完整、问题清楚的择期病例整理给合作医生做预评估。' : 'Only complete, focused, elective cases are packaged for partner doctor pre-assessment.'
    },
    {
      icon: 'route',
      title: lang === 'zh' ? '路径推进' : 'Pathway follow-up',
      text: lang === 'zh' ? '根据二诊和适配度进入路径咨询、来华门诊协调或关闭。' : 'Cases move into pathway consultation, China visit coordination, or closure based on fit.'
    }
  ];

  return (
    <>
      <SectionHeader
        eyebrow="Ops Console"
        lang={lang}
        title={{ zh: '运营端：从线索到病例路径', en: 'Ops Portal: from lead to case pathway' }}
        subtitle={{
          zh: '运营端不承担客户教育，也不做营销展示；核心是筛选、补资料、状态流转、医生匹配和 60 天复盘。',
          en: 'The ops portal is not for client education or marketing. It focuses on screening, record gaps, status flow, doctor matching, and 60-day review.'
        }}
        right={<Pill tone="sea" icon="lock-keyhole">{lang === 'zh' ? '内部使用' : 'Internal use'}</Pill>}
      />
      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
        <MiniMetric label={lang === 'zh' ? '当前线索' : 'Current leads'} value={leads.length} />
        <MiniMetric label={lang === 'zh' ? '60 天线索' : '60-day leads'} value={insights.total} />
        <MiniMetric label={lang === 'zh' ? '付费转化' : 'Paid conversion'} value={insights.paidConversion} />
        <MiniMetric label={lang === 'zh' ? '资料完整' : 'Record readiness'} value={insights.recordsReady} />
        <MiniMetric label={lang === 'zh' ? '上架医生' : 'Published doctors'} value={publishedDoctors} />
      </div>
      <div className="mt-6 grid gap-5 lg:grid-cols-4">
        {steps.map((step, index) => (
          <Card key={step.title} padding="p-5">
            <div className="mb-4 flex items-center justify-between">
              <div className="flex h-11 w-11 items-center justify-center rounded-2xl sea-gradient text-gold-300">
                <Icon name={step.icon} size={19} />
              </div>
              <span className="font-mono-display text-[11px] text-marble-500">{String(index + 1).padStart(2, '0')}</span>
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-lg font-semibold text-sea-500`}>{step.title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{step.text}</p>
          </Card>
        ))}
      </div>
    </>
  );
};

const DoctorOpsSection = ({ lang, doctorProfiles, addDoctorProfile, toggleDoctorPublished }) => {
  const emptyDoctorForm = {
    nameZh: '',
    nameEn: '',
    hospitalZh: '',
    hospitalEn: '',
    departmentZh: '胸外科',
    departmentEn: 'Thoracic Surgery',
    titleZh: '主任医师',
    titleEn: 'Chief physician',
    locationZh: '中国 · 北京',
    locationEn: 'Beijing, China',
    focusZh: '肺结节、早期肺癌、胸腔镜微创手术评估',
    focusEn: 'Lung nodules, early lung cancer, VATS pathway review',
    suitableCasesZh: '已有薄层 CT 报告和 DICOM 原片的肺结节客户\n本地医生建议随访、穿刺或手术，但家庭仍需二诊判断',
    suitableCasesEn: 'Lung nodule cases with thin-slice CT report and DICOM images\nFamilies needing second-opinion clarity after local follow-up, biopsy, or surgery advice',
    caseRequirementsZh: '胸部 CT 报告\nDICOM 原片\n既往 CT 对比\n本地医生建议',
    caseRequirementsEn: 'Chest CT report\nDICOM images\nPrior CT comparison\nLocal doctor recommendation',
    reviewScopeZh: '二诊预评估\n资料缺口提示\n来华门诊必要性判断\n手术路径可行性初步意见',
    reviewScopeEn: 'Second-opinion pre-assessment\nRecord-gap notes\nChina outpatient necessity review\nInitial surgery-pathway feasibility opinion',
    notAcceptedZh: '急诊或危重症\n无关键报告或影像的空泛咨询\n要求保证专家、床位、手术日期或疗效的需求',
    notAcceptedEn: 'Emergency or critical cases\nUnstructured consultation without key reports or imaging\nRequests for guaranteed doctor, bed, surgery date, or outcome',
    availabilityZh: '待运营确认',
    availabilityEn: 'Pending ops confirmation',
    publishState: 'draft'
  };
  const [form, setForm] = React.useState(emptyDoctorForm);
  const [error, setError] = React.useState('');
  const [saved, setSaved] = React.useState('');
  const publishedCount = doctorProfiles.filter((profile) => profile.isPublished).length;
  const draftCount = doctorProfiles.length - publishedCount;
  const updateForm = (key, value) => {
    setForm((prev) => ({ ...prev, [key]: value }));
    if (error) setError('');
    if (saved) setSaved('');
  };
  const localize = (zh, en) => ({ zh: zh.trim(), en: (en || zh).trim() });
  const localizeList = (zh, en) => ({ zh: toLocalArray(zh), en: toLocalArray(en || zh) });

  const submitDoctor = () => {
    if (!form.nameZh.trim() || !form.hospitalZh.trim()) {
      setError(lang === 'zh' ? '请至少填写医生姓名和医院。' : 'Please enter at least doctor name and hospital.');
      return;
    }
    const isPublished = form.publishState === 'published';
    const profile = normalizeDoctorProfile({
      id: `doc-${Date.now()}-${Math.floor(100 + Math.random() * 900)}`,
      isPublished,
      accountStatus: 'Ops managed',
      createdAt: localNow(),
      status: {
        zh: isPublished ? '上架展示' : '内部草稿',
        en: isPublished ? 'Published' : 'Draft'
      },
      source: { zh: '运营录入', en: 'Entered by ops' },
      name: localize(form.nameZh, form.nameEn),
      displayName: localize(`${form.nameZh} ${form.titleZh}`.trim(), `${form.nameEn || form.nameZh} ${form.titleEn || form.titleZh}`.trim()),
      hospital: localize(form.hospitalZh, form.hospitalEn),
      department: localize(form.departmentZh, form.departmentEn),
      title: localize(form.titleZh, form.titleEn),
      location: localize(form.locationZh, form.locationEn),
      languages: { zh: ['中文', '英文资料可读'], en: ['Chinese', 'English records readable'] },
      focus: localizeList(form.focusZh, form.focusEn),
      suitableCases: localizeList(form.suitableCasesZh, form.suitableCasesEn),
      caseRequirements: localizeList(form.caseRequirementsZh, form.caseRequirementsEn),
      reviewScope: localizeList(form.reviewScopeZh, form.reviewScopeEn),
      notAccepted: localizeList(form.notAcceptedZh, form.notAcceptedEn),
      accountAccess: {
        zh: ['查看运营整理后的匿名病例包', '查看关键影像和资料缺口', '填写二诊预评估反馈', '不直接获取客户联系方式'],
        en: ['View ops-prepared anonymized case packages', 'Review key imaging and record gaps', 'Submit pre-assessment feedback', 'No direct access to client contact details']
      },
      availability: localize(form.availabilityZh, form.availabilityEn),
      note: {
        zh: isPublished
          ? '此档案由运营录入并标记上架。真实展示前需确认医生授权、展示范围和合作边界。'
          : '此档案为内部草稿，仅运营端可见；上架后才会进入医生端展示。',
        en: isPublished
          ? 'This profile is entered and published by ops. Authorization, display scope, and partnership boundaries must be confirmed before real publication.'
          : 'This is an internal draft visible only in ops; it appears on the doctor portal only after publication.'
      }
    });
    addDoctorProfile(profile);
    setForm(emptyDoctorForm);
    setSaved(lang === 'zh' ? '医生档案已保存。' : 'Doctor profile saved.');
  };

  return (
    <>
      <SectionHeader
        eyebrow="Doctor Resources"
        lang={lang}
        title={{ zh: '医生档案管理', en: 'Doctor profile management' }}
        subtitle={{
          zh: '现阶段由运营统一录入医生资料；只有标记为“上架展示”的档案，才会出现在医生端页面。后续账号系统可沿用这套资料和权限边界。',
          en: 'Ops enters doctor profiles for now. Only profiles marked as published appear in the doctor portal; the later account system can reuse this profile and access boundary.'
        }}
        right={
          <div className="flex flex-wrap gap-2">
            <Pill tone="green" icon="eye">{lang === 'zh' ? `上架 ${publishedCount}` : `Published ${publishedCount}`}</Pill>
            <Pill tone="marble" icon="file-pen-line">{lang === 'zh' ? `草稿 ${draftCount}` : `Draft ${draftCount}`}</Pill>
          </div>
        }
      />
      <div className="grid gap-6 xl:grid-cols-12">
        <Card className="xl:col-span-5" padding="p-6">
          <div className="mb-5 flex items-center justify-between gap-3">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Ops Entry</div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '新增医生档案' : 'Add doctor profile'}</h3>
            </div>
            <Icon name="user-round-plus" size={24} className="text-gold-600" />
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            <Field label={lang === 'zh' ? '医生姓名' : 'Doctor name'} value={form.nameZh} onChange={(value) => updateForm('nameZh', value)} placeholder={lang === 'zh' ? '例如：陈谨川' : 'Example: Jinchuan Chen'} required error={!!error && !form.nameZh.trim()} />
            <Field label={lang === 'zh' ? '英文姓名' : 'English name'} value={form.nameEn} onChange={(value) => updateForm('nameEn', value)} placeholder="Optional" />
            <Field label={lang === 'zh' ? '医院' : 'Hospital'} value={form.hospitalZh} onChange={(value) => updateForm('hospitalZh', value)} placeholder={lang === 'zh' ? '例如：北京协和医院' : 'Hospital'} required error={!!error && !form.hospitalZh.trim()} />
            <Field label={lang === 'zh' ? '医院英文' : 'Hospital EN'} value={form.hospitalEn} onChange={(value) => updateForm('hospitalEn', value)} placeholder="Optional" />
            <Field label={lang === 'zh' ? '科室' : 'Department'} value={form.departmentZh} onChange={(value) => updateForm('departmentZh', value)} />
            <Field label={lang === 'zh' ? '职称' : 'Title'} value={form.titleZh} onChange={(value) => updateForm('titleZh', value)} />
            <SelectField
              label={lang === 'zh' ? '展示状态' : 'Display status'}
              value={form.publishState}
              onChange={(value) => updateForm('publishState', value)}
              options={[
                { value: 'draft', label: lang === 'zh' ? '内部草稿' : 'Internal draft' },
                { value: 'published', label: lang === 'zh' ? '上架展示' : 'Published' }
              ]}
            />
            <Field label={lang === 'zh' ? '可接收名额' : 'Availability'} value={form.availabilityZh} onChange={(value) => updateForm('availabilityZh', value)} />
          </div>
          <div className="mt-4 space-y-4">
            <TextareaField label={lang === 'zh' ? '重点方向' : 'Focus areas'} value={form.focusZh} onChange={(value) => updateForm('focusZh', value)} />
            <TextareaField label={lang === 'zh' ? '适合病例' : 'Suitable cases'} value={form.suitableCasesZh} onChange={(value) => updateForm('suitableCasesZh', value)} />
            <TextareaField label={lang === 'zh' ? '病例包最低资料' : 'Minimum records'} value={form.caseRequirementsZh} onChange={(value) => updateForm('caseRequirementsZh', value)} />
            <TextareaField label={lang === 'zh' ? '医生可反馈范围' : 'Review scope'} value={form.reviewScopeZh} onChange={(value) => updateForm('reviewScopeZh', value)} />
            <TextareaField label={lang === 'zh' ? '暂不接收范围' : 'Not accepted'} value={form.notAcceptedZh} onChange={(value) => updateForm('notAcceptedZh', value)} />
          </div>
          {error && <div className="mt-4 rounded-2xl bg-rose-50 p-3 text-sm text-rose-700 ring-1 ring-rose-100">{error}</div>}
          {saved && <div className="mt-4 rounded-2xl bg-emerald-50 p-3 text-sm text-emerald-700 ring-1 ring-emerald-100">{saved}</div>}
          <Button icon="save" onClick={submitDoctor} className="mt-5 w-full">{lang === 'zh' ? '保存医生档案' : 'Save doctor profile'}</Button>
        </Card>

        <Card className="xl:col-span-7" padding="p-0">
          <div className="border-b hairline p-5">
            <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Profile Shelf</div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '医生资源列表' : 'Doctor resources'}</h3>
          </div>
          <div className="divide-y hairline">
            {doctorProfiles.map((profile) => {
              const focusItems = profile.focus?.[lang] || [];
              return (
                <div key={profile.id} className="grid gap-4 p-5 lg:grid-cols-[1fr_auto] lg:items-center">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <h4 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{textOf(profile.displayName, lang)}</h4>
                      <Pill tone={profile.isPublished ? 'green' : 'marble'} icon={profile.isPublished ? 'eye' : 'eye-off'}>
                        {profile.isPublished ? (lang === 'zh' ? '上架展示' : 'Published') : (lang === 'zh' ? '内部草稿' : 'Draft')}
                      </Pill>
                    </div>
                    <div className="mt-1 text-sm leading-relaxed text-sea-400/76">
                      {textOf(profile.hospital, lang)} · {textOf(profile.department, lang)} · {textOf(profile.location, lang)}
                    </div>
                    <div className="mt-3 flex flex-wrap gap-2">
                      {focusItems.slice(0, 4).map((item) => <Pill key={item} tone="gold">{item}</Pill>)}
                    </div>
                    <div className="mt-3 text-[11px] text-marble-500">
                      {lang === 'zh' ? '录入时间' : 'Entered'}: {profile.createdAt} · {textOf(profile.source, lang)}
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-2 lg:justify-end">
                    <Button
                      variant={profile.isPublished ? 'quiet' : 'sea'}
                      icon={profile.isPublished ? 'eye-off' : 'eye'}
                      onClick={() => toggleDoctorPublished(profile.id)}
                    >
                      {profile.isPublished ? (lang === 'zh' ? '下架' : 'Unpublish') : (lang === 'zh' ? '上架' : 'Publish')}
                    </Button>
                    <Button variant="ghost" icon="external-link" onClick={() => window.open('doctor.html', '_blank')}>
                      {lang === 'zh' ? '看医生端' : 'View portal'}
                    </Button>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </>
  );
};

const OpsRulesSection = ({ lang }) => {
  const rules = [
    {
      title: lang === 'zh' ? '客户前台不显示内部判断' : 'Keep internal scoring off client pages',
      text: lang === 'zh' ? 'Score、状态、Webhook、拒绝原因只在运营端出现。客户只看到建议下一步。' : 'Scores, statuses, webhooks, and rejection reasons stay in ops. Clients only see suggested next steps.'
    },
    {
      title: lang === 'zh' ? '先补资料，再谈医生匹配' : 'Complete records before doctor matching',
      text: lang === 'zh' ? '没有关键报告、影像或病理时，运营端优先标记待补资料，不直接推进二诊。' : 'If key reports, imaging, or pathology are missing, ops marks records pending before second-opinion matching.'
    },
    {
      title: lang === 'zh' ? '不承诺医生、床位、日期或疗效' : 'No promise of doctor, bed, date, or outcome',
      text: lang === 'zh' ? '运营端可以记录意向和协调动作，但不得把协调能力写成保证。' : 'Ops can record intent and coordination work, but coordination must not be represented as a guarantee.'
    }
  ];
  return (
    <>
      <SectionHeader
        eyebrow="Operating Rules"
        lang={lang}
        title={{ zh: '运营边界和状态规则', en: 'Ops boundaries and status rules' }}
        subtitle={{
          zh: '这块用于提醒内部团队：华医畅是路径协调服务，不替代医院或医生。',
          en: 'This keeps the team aligned: HuaMed coordinates care pathways and does not replace hospitals or physicians.'
        }}
      />
      <div className="grid gap-5 lg:grid-cols-3">
        {rules.map((rule) => (
          <Card key={rule.title} padding="p-6">
            <Icon name="shield-check" size={22} className="mb-4 text-gold-600" />
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{rule.title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{rule.text}</p>
          </Card>
        ))}
      </div>
    </>
  );
};

const OpsLoginScreen = ({ lang, setLang, copy, onLoggedIn }) => {
  const [username, setUsername] = React.useState('ops@huamed.local');
  const [password, setPassword] = React.useState('huamed-ops-2026');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (event) => {
    event.preventDefault();
    setLoading(true);
    setError('');
    try {
      const session = await apiJson('/api/auth/ops/login', {
        method: 'POST',
        body: JSON.stringify({ username, password })
      });
      onLoggedIn(session);
    } catch {
      setError(lang === 'zh' ? '运营账号或密码不正确。' : 'Invalid ops username or password.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="app-shell portal-ops min-h-screen">
      <TopBar lang={lang} setLang={setLang} copy={copy} onNotice={() => {}} portal="ops" />
      <main className="mx-auto flex min-h-[calc(100vh-72px)] max-w-4xl items-center px-5 py-10">
        <Card padding="p-8" className="w-full">
          <div className="mb-6 flex items-start justify-between gap-4">
            <div>
              <div className="mb-2 flex items-center gap-2">
                <span className="h-px w-7 bg-gold-400" />
                <span className="text-[11px] font-medium uppercase tracking-[0.22em] text-gold-600">Ops Login</span>
              </div>
              <h1 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-3xl text-sea-500`}>{lang === 'zh' ? '运营端登录' : 'Ops portal login'}</h1>
              <p className="mt-2 max-w-xl text-sm leading-relaxed text-sea-400/75">
                {lang === 'zh' ? '客户 Google 注册并提交初筛资料后，运营端可在这里查看用户和线索。' : 'After clients sign in with Google and submit intake, ops can review users and leads here.'}
              </p>
            </div>
            <Pill tone="sea" icon="lock-keyhole">{lang === 'zh' ? '内部使用' : 'Internal'}</Pill>
          </div>
          <form onSubmit={submit} className="grid gap-4 md:grid-cols-[1fr_1fr_auto] md:items-end">
            <Field label={lang === 'zh' ? '运营账号' : 'Username'} value={username} onChange={setUsername} />
            <Field label={lang === 'zh' ? '密码' : 'Password'} type="password" value={password} onChange={setPassword} />
            <Button type="submit" icon="log-in" disabled={loading}>{loading ? (lang === 'zh' ? '登录中' : 'Signing in') : (lang === 'zh' ? '登录' : 'Sign in')}</Button>
          </form>
          {error && <div className="mt-4 rounded-2xl bg-rose-50 p-3 text-sm text-rose-700 ring-1 ring-rose-100">{error}</div>}
        </Card>
      </main>
    </div>
  );
};

const OpsUsersSection = ({ lang, users, leads, onOpenUserLeads }) => {
  const leadCountByUser = leads.reduce((acc, lead) => {
    acc[lead.userId] = (acc[lead.userId] || 0) + 1;
    return acc;
  }, {});
  return (
    <>
      <SectionHeader
        eyebrow="Registered Clients"
        lang={lang}
        title={{ zh: '注册用户与 WhatsApp 线索', en: 'Registered users and WhatsApp leads' }}
        subtitle={{
          zh: '这里显示通过 Google 登录并提交完整初筛表的客户。运营可用这些资料进入 WhatsApp 人工跟进。',
          en: 'These clients signed in with Google and submitted the full intake form. Ops can use this context for WhatsApp follow-up.'
        }}
        right={<Pill tone="green" icon="users">{lang === 'zh' ? `用户 ${users.length}` : `Users ${users.length}`}</Pill>}
      />
      <Card padding="p-0">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[860px] text-left text-sm">
            <thead className="bg-marble-50 text-[11px] uppercase tracking-[0.16em] text-marble-500">
              <tr>
                <th className="px-5 py-3">{lang === 'zh' ? '客户' : 'Client'}</th>
                <th className="px-5 py-3">{lang === 'zh' ? '地区' : 'Location'}</th>
                <th className="px-5 py-3">WhatsApp</th>
                <th className="px-5 py-3">{lang === 'zh' ? '线索数' : 'Leads'}</th>
                <th className="px-5 py-3">{lang === 'zh' ? '注册时间' : 'Registered'}</th>
              </tr>
            </thead>
            <tbody>
              {users.length === 0 ? (
                <tr><td className="px-5 py-8 text-center text-sea-400" colSpan="5">{lang === 'zh' ? '暂无注册用户。' : 'No registered users yet.'}</td></tr>
              ) : users.map((user) => (
                <tr key={user.id} className="border-t hairline">
                  <td className="px-5 py-4">
                    <div className="font-medium text-sea-500">{user.name || '-'}</div>
                    <div className="text-[11px] text-marble-500">{user.email || '-'}</div>
                  </td>
                  <td className="px-5 py-4 text-sea-500">{[user.city, user.country].filter(Boolean).join(' · ') || '-'}</td>
                  <td className="px-5 py-4 text-sea-500">{user.whatsapp || user.phone || '-'}</td>
                  <td className="px-5 py-4">
                    <button
                      type="button"
                      disabled={!leadCountByUser[user.id]}
                      onClick={() => onOpenUserLeads(user.id)}
                      className={`inline-flex rounded-full ${leadCountByUser[user.id] ? 'cursor-pointer hover:ring-gold-300' : 'cursor-not-allowed opacity-60'}`}
                    >
                      <Pill tone="gold" icon={leadCountByUser[user.id] ? 'external-link' : undefined}>
                        {leadCountByUser[user.id] || 0}
                      </Pill>
                    </button>
                  </td>
                  <td className="px-5 py-4 text-marble-500">{user.createdAt?.slice(0, 10) || '-'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
};

const OpsApp = () => {
  const [lang, setLang] = React.useState(() => localStorage.getItem('huamed-lang') || 'zh');
  const [active, setActive] = React.useState('ops-overview');
  const [noticeOpen, setNoticeOpen] = React.useState(false);
  const [webhookUrl, setWebhookUrl] = React.useState(() => localStorage.getItem(WEBHOOK_KEY) || '');
  const [webhookStatus, setWebhookStatus] = React.useState('');
  const [leads, setLeads] = React.useState(loadStoredLeads);
  const [users, setUsers] = React.useState([]);
  const [doctorProfiles, setDoctorProfiles] = React.useState(loadStoredDoctors);
  const [opsSession, setOpsSession] = React.useState({ role: 'loading', user: null });
  const [opsError, setOpsError] = React.useState('');
  const [focusedLeadId, setFocusedLeadId] = React.useState('');
  const copy = UI[lang];
  const tr = (value) => textOf(value, lang);

  React.useEffect(() => {
    localStorage.setItem('huamed-lang', lang);
  }, [lang]);

  React.useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(leads));
  }, [leads]);

  React.useEffect(() => {
    localStorage.setItem(WEBHOOK_KEY, webhookUrl);
  }, [webhookUrl]);

  React.useEffect(() => {
    localStorage.setItem(DOCTOR_STORAGE_KEY, JSON.stringify(doctorProfiles));
  }, [doctorProfiles]);

  const loadOpsData = async () => {
    const [leadData, userData] = await Promise.all([
      apiJson('/api/ops/leads'),
      apiJson('/api/ops/users')
    ]);
    setLeads(leadData.leads.map(normalizeLead));
    setUsers(userData.users || []);
  };

  React.useEffect(() => {
    apiJson('/api/me')
      .then((session) => {
        setOpsSession(session);
        if (session.role === 'ops') return loadOpsData();
      })
      .catch(() => setOpsSession({ role: 'guest', user: null }));
  }, []);

  React.useEffect(() => {
    const syncFromStorage = (event) => {
      if (event.key === STORAGE_KEY) setLeads(loadStoredLeads());
      if (event.key === DOCTOR_STORAGE_KEY) setDoctorProfiles(loadStoredDoctors());
    };
    window.addEventListener('storage', syncFromStorage);
    return () => window.removeEventListener('storage', syncFromStorage);
  }, []);

  const go = (id) => {
    setActive(id);
    requestAnimationFrame(() => {
      document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  };

  const openUserLeads = (userId) => {
    const firstLead = leads.find((lead) => lead.userId === userId);
    if (!firstLead) return;
    setFocusedLeadId(firstLead.id);
    go('case-flow');
  };

  const addDemoLead = () => {
    const demos = [
      { ...emptyForm, source: 'WhatsApp referral', name: 'Mr. Wong', country: 'Thailand', city: 'Bangkok', language: '中文', contact: 'WhatsApp +66 test', conditionId: 'thyroid', hasRecords: 'complete', acceptsPaid: 'yes', considersChina: 'maybe', notes: 'TI-RADS 4, wants China review.' },
      { ...emptyForm, source: 'Partner clinic', name: 'Ms. Chua', country: 'Vietnam', city: 'Ho Chi Minh City', language: 'English', contact: 'email test@huamed.local', conditionId: 'sports', hasRecords: 'partial', acceptsPaid: 'maybe', considersChina: 'yes', notes: 'ACL tear, comparing surgery options.' }
    ];
    const base = demos[Math.floor(Math.random() * demos.length)];
    const scored = scoreLead(base);
    setLeads((prev) => [normalizeLead({ ...base, ...scored, id: makeLeadId(), createdAt: localNow(), status: 'New' }), ...prev]);
  };

  const changeLeadStatus = (id, status) => {
    setLeads((prev) => prev.map((lead) => lead.id === id ? { ...lead, status } : lead));
    apiJson(`/api/ops/leads/${id}`, { method: 'PATCH', body: JSON.stringify({ status }) }).catch(() => {});
  };

  const updateLeadField = (id, key, value) => {
    setLeads((prev) => prev.map((lead) => lead.id === id ? { ...lead, [key]: value } : lead));
    apiJson(`/api/ops/leads/${id}`, { method: 'PATCH', body: JSON.stringify({ [key]: value }) }).catch(() => {});
  };

  const toggleLeadRecord = (id, recordItemKey) => {
    setLeads((prev) => prev.map((lead) => {
      if (lead.id !== id) return lead;
      const currentItem = getRecordItems(lead, 'zh').find((item) => item.key === recordItemKey);
      const currentValue = currentItem?.ready || false;
      return {
        ...lead,
        recordChecklist: {
          ...(lead.recordChecklist || {}),
          [recordItemKey]: !currentValue
        }
      };
    }));
  };

  const addDoctorProfile = (profile) => {
    setDoctorProfiles((prev) => [normalizeDoctorProfile(profile), ...prev]);
  };

  const toggleDoctorPublished = (id) => {
    setDoctorProfiles((prev) => prev.map((profile) => {
      if (profile.id !== id) return profile;
      const isPublished = !profile.isPublished;
      return {
        ...profile,
        isPublished,
        status: {
          zh: isPublished ? '上架展示' : '内部草稿',
          en: isPublished ? 'Published' : 'Draft'
        },
        note: isPublished ? {
          zh: '此档案由运营标记上架。真实展示前需确认医生授权、展示范围和合作边界。',
          en: 'This profile is marked as published by ops. Authorization, display scope, and partnership boundaries must be confirmed before real publication.'
        } : profile.note
      };
    }));
  };

  const mockWebhook = () => {
    setWebhookStatus(lang === 'zh' ? '测试发送成功：下一版可接飞书/Notion/Airtable。' : 'Test ping sent: ready for Feishu/Notion/Airtable in the next version.');
    setTimeout(() => setWebhookStatus(''), 3600);
  };

  const navItems = [
    { id: 'ops-overview', icon: 'layout-dashboard', label: lang === 'zh' ? '运营概览' : 'Ops Overview' },
    { id: 'ops-users', icon: 'users', label: lang === 'zh' ? '注册用户' : 'Users' },
    { id: 'ops-doctors', icon: 'user-round-cog', label: lang === 'zh' ? '医生档案' : 'Doctors' },
    { id: 'case-flow', icon: 'folder-kanban', label: lang === 'zh' ? '病历流转' : 'Case Flow' },
    { id: 'ops', icon: 'table-2', label: lang === 'zh' ? '线索工作台' : 'Lead Desk' },
    { id: 'ops-rules', icon: 'list-checks', label: lang === 'zh' ? '流转规则' : 'Rules' }
  ];

  if (opsSession.role === 'loading') {
    return (
      <div className="app-shell portal-ops flex min-h-screen items-center justify-center">
        <Card padding="p-8"><div className="text-sm text-sea-500">{lang === 'zh' ? '正在检查运营登录状态...' : 'Checking ops session...'}</div></Card>
      </div>
    );
  }

  if (opsSession.role !== 'ops') {
    return <OpsLoginScreen lang={lang} setLang={setLang} copy={copy} onLoggedIn={(session) => {
      setOpsSession(session);
      loadOpsData().catch(() => setOpsError(lang === 'zh' ? '已登录，但读取运营数据失败。' : 'Signed in, but failed to load ops data.'));
    }} />;
  }

  return (
    <div className="app-shell portal-ops flex min-h-screen">
      <SideNav active={active} go={go} lang={lang} setLang={setLang} copy={copy} portal="ops" navItems={navItems} />
      <main className="min-w-0 flex-1">
        <TopBar lang={lang} setLang={setLang} copy={copy} onNotice={() => setNoticeOpen(true)} portal="ops" />
        <div className="space-y-8 px-5 py-6 md:px-10 md:py-8">
          <section id="ops-overview" className="scroll-mt-24">
            <OpsOverviewSection lang={lang} leads={leads} doctorProfiles={doctorProfiles} />
          </section>
          {opsError && <div className="rounded-2xl bg-rose-50 p-3 text-sm text-rose-700 ring-1 ring-rose-100">{opsError}</div>}
          <section id="ops-users" className="scroll-mt-24">
            <OpsUsersSection lang={lang} users={users} leads={leads} onOpenUserLeads={openUserLeads} />
          </section>
          <section id="ops-doctors" className="scroll-mt-24">
            <DoctorOpsSection
              lang={lang}
              doctorProfiles={doctorProfiles}
              addDoctorProfile={addDoctorProfile}
              toggleDoctorPublished={toggleDoctorPublished}
            />
          </section>
          <section id="case-flow" className="scroll-mt-24">
            <CaseFlowSection
              lang={lang}
              tr={tr}
              leads={leads}
              doctorProfiles={doctorProfiles}
              focusLeadId={focusedLeadId}
              changeLeadStatus={changeLeadStatus}
              updateLeadField={updateLeadField}
              toggleLeadRecord={toggleLeadRecord}
            />
          </section>
          <section id="ops" className="scroll-mt-24">
            <LeadsSection
              lang={lang}
              tr={tr}
              leads={leads}
              changeLeadStatus={changeLeadStatus}
              updateLeadField={updateLeadField}
              addDemoLead={addDemoLead}
              webhookUrl={webhookUrl}
              setWebhookUrl={setWebhookUrl}
              mockWebhook={mockWebhook}
              webhookStatus={webhookStatus}
              copy={copy}
            />
          </section>
          <section id="ops-rules" className="scroll-mt-24">
            <OpsRulesSection lang={lang} />
          </section>
          <Footer lang={lang} portal="ops" />
        </div>
      </main>
      <Modal open={noticeOpen} onClose={() => setNoticeOpen(false)} title={copy.riskNotice} lang={lang}>
        <div className="space-y-3">
          {RISK_COPY[lang].map((line, index) => (
            <div key={index} className="flex gap-3 rounded-2xl bg-marble-50 p-3.5 text-sm leading-relaxed text-sea-500 ring-1 hairline">
              <span className="mt-1 h-1.5 w-1.5 shrink-0 rounded-full bg-gold-400" />
              <span>{line}</span>
            </div>
          ))}
        </div>
        <div className="mt-5 flex justify-end">
          <Button variant="sea" icon="check" onClick={() => setNoticeOpen(false)}>{copy.close}</Button>
        </div>
      </Modal>
    </div>
  );
};

const DoctorHeroSection = ({ lang, go }) => (
  <section id="doctor-overview" className="doctor-hero relative overflow-hidden rounded-4xl p-7 shadow-deep md:p-10">
    <div className="relative z-[1] grid gap-8 lg:grid-cols-12 lg:items-end">
      <div className="lg:col-span-7">
        <div className="mb-5 flex items-center gap-2">
          <span className="h-px w-8 bg-gold-400" />
          <span className="text-[11px] font-medium uppercase tracking-[0.25em] text-gold-700">{lang === 'zh' ? '中国合作医生 / 医院资源方' : 'China doctors and hospital partners'}</span>
        </div>
        <h1 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} max-w-[700px] text-[38px] font-semibold leading-tight text-sea-600 md:text-[50px]`}>
          {lang === 'zh' ? '让海外病例先被整理、筛选，再进入专家预评估。' : 'Organized overseas cases before specialist pre-assessment.'}
        </h1>
        <p className="mt-5 max-w-[640px] text-[15px] leading-8 text-sea-500/78">
          {lang === 'zh'
            ? '华医畅为东南亚华人家庭整理报告、影像、病理和核心问题，把适合中国专家二诊或来华择期评估的病例打包给合作医生和医院资源方。'
            : 'HuaMed organizes reports, imaging, pathology, and family questions for Southeast Asian Chinese-speaking families, then packages suitable elective cases for partner doctors and hospital resources.'}
        </p>
        <div className="mt-7 flex flex-wrap gap-3">
          <Button icon="id-card" onClick={() => go('doctor-profiles')}>{lang === 'zh' ? '查看医生档案' : 'Doctor Profile'}</Button>
          <Button variant="ghost" icon="folder-heart" onClick={() => go('case-package')}>{lang === 'zh' ? '病例包' : 'Case Package'}</Button>
          <Button variant="ghost" icon="route" onClick={() => go('doctor-flow')}>{lang === 'zh' ? '协作流程' : 'Workflow'}</Button>
        </div>
      </div>
      <Card className="lg:col-span-5" padding="p-6">
        <div className="grid gap-3">
          {[
            [lang === 'zh' ? '病例来源' : 'Case source', lang === 'zh' ? '东南亚华人家庭，马来西亚先行' : 'Southeast Asian Chinese-speaking families, Malaysia pilot'],
            [lang === 'zh' ? '资料状态' : 'Record status', lang === 'zh' ? '运营先筛选、补资料、整理摘要' : 'Ops screens, closes gaps, and prepares case briefs'],
            [lang === 'zh' ? '医生动作' : 'Doctor action', lang === 'zh' ? '二诊预评估和路径建议，不承诺结果' : 'Second-opinion pre-assessment and pathway suggestions, no outcome guarantees']
          ].map(([label, value]) => (
            <div key={label} className="rounded-2xl bg-marble-50 p-4 ring-1 hairline">
              <div className="text-[10px] font-medium uppercase tracking-[0.18em] text-gold-600">{label}</div>
              <div className="mt-1 text-sm leading-relaxed text-sea-500">{value}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  </section>
);

const DetailList = ({ items, icon = 'check-circle-2' }) => (
  <div className="space-y-2">
    {items.map((item) => (
      <div key={item} className="flex gap-2 text-sm leading-relaxed text-sea-500">
        <Icon name={icon} size={15} className="mt-0.5 shrink-0 text-gold-600" />
        <span>{item}</span>
      </div>
    ))}
  </div>
);

const DoctorProfileCard = ({ lang, profile }) => {
  const tr = (value) => textOf(value, lang);
  const list = (value) => value?.[lang] || [];
  const profileFacts = [
    [lang === 'zh' ? '医院' : 'Hospital', tr(profile.hospital)],
    [lang === 'zh' ? '科室' : 'Department', tr(profile.department)],
    [lang === 'zh' ? '职称' : 'Title', tr(profile.title)],
    [lang === 'zh' ? '地点' : 'Location', tr(profile.location)]
  ];

  return (
    <>
      <div className="grid gap-5 xl:grid-cols-12">
        <Card className="xl:col-span-7" padding="p-6 md:p-7">
          <div className="flex flex-col gap-5 md:flex-row md:items-start md:justify-between">
            <div className="flex gap-4">
              <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-3xl bg-sea-400 text-marble-50 shadow-soft">
                <Icon name="stethoscope" size={28} />
              </div>
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl leading-tight text-sea-500`}>
                    {tr(profile.displayName)}
                  </h3>
                  <Pill tone="green" icon="badge-check">{lang === 'zh' ? '已上架' : 'Published'}</Pill>
                </div>
                <p className="mt-2 text-sm leading-relaxed text-sea-400/78">
                  {lang === 'zh'
                    ? '该医生档案由运营端录入并标记上架，用于说明医生资源方向、病例接收边界和后续账号权限。'
                    : 'This profile is entered and published by ops to show doctor resource direction, case intake boundaries, and future account access.'}
                </p>
              </div>
            </div>
            <Pill tone="sea" icon="calendar-clock">{tr(profile.availability)}</Pill>
          </div>

          <div className="mt-6 grid gap-3 md:grid-cols-2">
            {profileFacts.map(([label, value]) => (
              <div key={label} className="rounded-2xl bg-marble-50 p-4 ring-1 hairline">
                <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{label}</div>
                <div className="mt-1 text-sm leading-relaxed text-sea-500">{value}</div>
              </div>
            ))}
          </div>

          <div className="mt-6 grid gap-5 md:grid-cols-2">
            <div>
              <h4 className="mb-3 text-[11px] font-medium uppercase tracking-[0.18em] text-marble-500">{lang === 'zh' ? '重点方向' : 'Focus Areas'}</h4>
              <div className="flex flex-wrap gap-2">
                {list(profile.focus).map((item) => (
                  <Pill key={item} tone="gold">{item}</Pill>
                ))}
              </div>
            </div>
            <div>
              <h4 className="mb-3 text-[11px] font-medium uppercase tracking-[0.18em] text-marble-500">{lang === 'zh' ? '语言和资料' : 'Language'}</h4>
              <div className="flex flex-wrap gap-2">
                {list(profile.languages).map((item) => (
                  <Pill key={item} tone="marble" icon="languages">{item}</Pill>
                ))}
              </div>
            </div>
          </div>

          <div className="mt-6 rounded-3xl bg-gold-50 p-5 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
            <div className="mb-2 flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.18em] text-gold-700">
              <Icon name="triangle-alert" size={14} />
              {lang === 'zh' ? '演示声明' : 'Demo Notice'}
            </div>
            {tr(profile.note)}
          </div>
        </Card>

        <div className="grid gap-5 xl:col-span-5">
          <Card padding="p-6">
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mb-4 text-xl text-sea-500`}>
              {lang === 'zh' ? '适合提交给该医生的病例' : 'Cases suitable for this doctor'}
            </h3>
            <DetailList items={list(profile.suitableCases)} />
          </Card>
          <Card padding="p-6">
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mb-4 text-xl text-sea-500`}>
              {lang === 'zh' ? '病例包最低资料' : 'Minimum case-package records'}
            </h3>
            <DetailList items={list(profile.caseRequirements)} icon="file-check-2" />
          </Card>
        </div>
      </div>

      <div className="mt-5 grid gap-5 lg:grid-cols-3">
        {[
          [lang === 'zh' ? '医生可反馈什么' : 'Review scope', list(profile.reviewScope), 'clipboard-check'],
          [lang === 'zh' ? '暂不接收' : 'Not accepted', list(profile.notAccepted), 'shield-alert'],
          [lang === 'zh' ? '医生账号权限规划' : 'Doctor account access', list(profile.accountAccess), 'key-round']
        ].map(([title, items, icon]) => (
          <Card key={title} padding="p-6">
            <Icon name={icon} size={22} className="mb-4 text-gold-600" />
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mb-3 text-xl text-sea-500`}>{title}</h3>
            <DetailList items={items} icon={icon === 'shield-alert' ? 'x-circle' : 'check-circle-2'} />
          </Card>
        ))}
      </div>
    </>
  );
};

const DoctorProfileSection = ({ lang, doctorProfiles }) => {
  const publishedProfiles = doctorProfiles.filter((profile) => profile.isPublished);
  return (
    <>
      <SectionHeader
        eyebrow="Doctor Profile"
        lang={lang}
        title={{ zh: '已上架医生档案', en: 'Published doctor profiles' }}
        subtitle={{
          zh: '医生端只展示运营端标记为“上架展示”的医生档案。后续医生登录后，将从这里进入自己的病例包和二诊预评估反馈。',
          en: 'The doctor portal only shows profiles marked as published by ops. Later, doctors will log in from here to view their case packages and submit pre-assessment feedback.'
        }}
        right={<Pill tone="gold" icon="database">{lang === 'zh' ? '运营上架' : 'Ops published'}</Pill>}
      />
      {publishedProfiles.length === 0 ? (
        <Card padding="p-8">
          <div className="flex flex-col items-center justify-center text-center">
            <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-3xl bg-marble-100 text-sea-400 ring-1 hairline">
              <Icon name="eye-off" size={24} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl text-sea-500`}>
              {lang === 'zh' ? '暂无已上架医生档案' : 'No published doctor profiles'}
            </h3>
            <p className="mt-2 max-w-xl text-sm leading-relaxed text-sea-400/75">
              {lang === 'zh'
                ? '运营端可以先录入医生资料，确认授权和展示边界后再上架到医生端。'
                : 'Ops can enter doctor profiles first, then publish them after authorization and display boundaries are confirmed.'}
            </p>
          </div>
        </Card>
      ) : (
        <div className="space-y-6">
          {publishedProfiles.map((profile) => (
            <DoctorProfileCard key={profile.id} lang={lang} profile={profile} />
          ))}
        </div>
      )}
    </>
  );
};

const DoctorCasePackageSection = ({ lang }) => {
  const items = [
    ['file-text', lang === 'zh' ? '病例摘要' : 'Case brief', lang === 'zh' ? '基础情况、时间线、既往治疗和本地医生建议。' : 'Basic profile, timeline, prior treatment, and local doctor recommendation.'],
    ['images', lang === 'zh' ? '关键资料' : 'Key records', lang === 'zh' ? '报告、影像、内镜图片、病理和缺口说明。' : 'Reports, imaging, endoscopy images, pathology, and missing-record notes.'],
    ['message-square-text', lang === 'zh' ? '问题清单' : 'Question list', lang === 'zh' ? '家庭最关心的问题被转成医生可直接回应的二诊问题。' : 'Family concerns are translated into direct second-opinion questions.'],
    ['languages', lang === 'zh' ? '沟通背景' : 'Communication context', lang === 'zh' ? '中文/英文沟通偏好、来华意向、付费服务意向。' : 'Chinese/English preference, China visit intent, and paid-service intent.']
  ];
  return (
    <>
      <SectionHeader
        eyebrow="Case Package"
        lang={lang}
        title={{ zh: '合作医生会收到什么？', en: 'What partner doctors receive' }}
        subtitle={{
          zh: '医生端不面向患者收集零散信息，重点是展示华医畅如何把海外病例整理成可评估材料。',
          en: 'The doctor portal does not collect scattered patient input; it shows how HuaMed turns overseas cases into reviewable packages.'
        }}
      />
      <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-4">
        {items.map(([icon, title, text]) => (
          <Card key={title} padding="p-6">
            <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-50 text-emerald-700 ring-1 ring-emerald-100">
              <Icon name={icon} size={20} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{text}</p>
          </Card>
        ))}
      </div>
    </>
  );
};

const DoctorFlowSection = ({ lang }) => {
  const steps = [
    lang === 'zh' ? '运营筛选客户和资料完整度' : 'Ops screens client fit and record readiness',
    lang === 'zh' ? '整理病例摘要和专家问题清单' : 'Prepare case brief and specialist questions',
    lang === 'zh' ? '匹配合适专科医生做二诊预评估' : 'Match suitable specialist for pre-assessment',
    lang === 'zh' ? '由运营反馈客户，并判断是否进入来华协调' : 'Ops reports back to client and decides China pathway fit'
  ];
  return (
    <>
      <SectionHeader
        eyebrow="Collaboration Flow"
        lang={lang}
        title={{ zh: '医生协作流程', en: 'Doctor collaboration workflow' }}
        subtitle={{
          zh: '医生端的核心不是公开承诺专家资源，而是说明病例如何被筛选、整理、提交和反馈。',
          en: 'The goal is not to publicly promise expert resources, but to explain screening, packaging, review, and feedback.'
        }}
      />
      <div className="grid gap-4 lg:grid-cols-4">
        {steps.map((step, index) => (
          <div key={step} className="rounded-3xl bg-white/84 p-5 shadow-soft ring-1 hairline">
            <div className="font-serif-display text-3xl text-gold-600">{String(index + 1).padStart(2, '0')}</div>
            <div className="mt-3 text-sm leading-relaxed text-sea-500">{step}</div>
          </div>
        ))}
      </div>
    </>
  );
};

const DoctorFitSection = ({ lang, tr }) => (
  <>
    <SectionHeader
      eyebrow="Specialty Fit"
      lang={lang}
      title={{ zh: '首期更适合哪些医生资源？', en: 'Which doctor resources fit v1 best?' }}
      subtitle={{
        zh: '首期优先围绕已有报告、影像、病理的择期二诊和来华路径评估。',
        en: 'v1 prioritizes elective second opinions and China pathway review for cases with existing records.'
      }}
      right={<Pill tone="green" icon="stethoscope">{lang === 'zh' ? '择期二诊' : 'Elective second opinion'}</Pill>}
    />
    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
      {getFocusConditions().map((condition) => (
        <Card key={condition.id} padding="p-5">
          <Icon name={condition.icon} size={22} className="mb-4 text-gold-600" />
          <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-lg leading-tight text-sea-500`}>{tr(condition.name)}</h3>
          <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{tr(condition.next)}</p>
        </Card>
      ))}
    </div>
  </>
);

const DoctorBoundarySection = ({ lang }) => (
  <>
    <SectionHeader
      eyebrow="Boundaries"
      lang={lang}
      title={{ zh: '合作边界', en: 'Collaboration boundaries' }}
      subtitle={{
        zh: '医生端需要清楚说明：华医畅提供病例整理和路径协调，不替代医生诊疗，不向客户承诺具体结果。',
        en: 'The doctor portal clarifies that HuaMed organizes cases and coordinates pathways; it does not replace care decisions or promise outcomes.'
      }}
    />
    <div className="grid gap-5 lg:grid-cols-3">
      {[
        [lang === 'zh' ? '不接急危重症' : 'No emergency intake', lang === 'zh' ? '急性胸痛、脑卒中、创伤、高热等应先在当地急诊处理。' : 'Acute chest pain, stroke signs, trauma, and high fever require local emergency care first.'],
        [lang === 'zh' ? '不保证床位或手术日期' : 'No bed or surgery-date guarantee', lang === 'zh' ? '是否面诊、检查、住院或手术以医院和医生评估为准。' : 'Consultation, tests, admission, and surgery depend on hospital and physician assessment.'],
        [lang === 'zh' ? '医疗费直接向医院支付' : 'Medical fees paid to hospitals', lang === 'zh' ? '华医畅只收服务费，不打包或代收医院诊疗费用。' : 'HuaMed charges service fees only and does not bundle hospital medical fees.']
      ].map(([title, text]) => (
        <Card key={title} padding="p-6">
          <Icon name="shield-alert" size={22} className="mb-4 text-gold-600" />
          <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-xl text-sea-500`}>{title}</h3>
          <p className="mt-2 text-sm leading-relaxed text-sea-400/76">{text}</p>
        </Card>
      ))}
    </div>
  </>
);

const DoctorAssignedCasesSection = ({ lang, leads, doctorProfiles, updateDoctorFeedback }) => {
  const reviewCases = leads.filter((lead) => lead.status === 'Doctor Review' && lead.matchedDoctorId);
  const [activeLeadId, setActiveLeadId] = React.useState(() => reviewCases[0]?.id || '');
  const selectedLead = reviewCases.find((lead) => lead.id === activeLeadId) || reviewCases[0];

  React.useEffect(() => {
    if (!selectedLead && reviewCases[0]) setActiveLeadId(reviewCases[0].id);
  }, [selectedLead, reviewCases]);

  if (!selectedLead) {
    return (
      <>
        <SectionHeader
          eyebrow="Assigned Cases"
          lang={lang}
          title={{ zh: '待评估病例包', en: 'Assigned case packages' }}
          subtitle={{
            zh: '运营端把资料齐全且已匹配医生的病例提交后，会在这里形成医生可评估的匿名病例包。',
            en: 'After ops submits complete, doctor-matched cases, anonymized review packages appear here.'
          }}
          right={<Pill tone="marble" icon="inbox">{lang === 'zh' ? '暂无病例' : 'No cases'}</Pill>}
        />
        <Card padding="p-8">
          <div className="flex flex-col items-center justify-center text-center">
            <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-3xl bg-marble-100 text-sea-400 ring-1 hairline">
              <Icon name="folder-open" size={24} />
            </div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl text-sea-500`}>
              {lang === 'zh' ? '暂无待评估病例包' : 'No assigned case packages yet'}
            </h3>
            <p className="mt-2 max-w-xl text-sm leading-relaxed text-sea-400/75">
              {lang === 'zh'
                ? '请先在运营端把病例资料补齐、匹配已上架医生，并提交医生预评估。'
                : 'In ops, complete records, match a published doctor, and submit the case for doctor review first.'}
            </p>
          </div>
        </Card>
      </>
    );
  }

  const condition = getCondition(selectedLead.conditionId);
  const readiness = getRecordReadiness(selectedLead);
  const recordItems = getRecordItems(selectedLead, lang);
  const matchedDoctor = doctorProfiles.find((profile) => profile.id === selectedLead.matchedDoctorId);
  const feedback = normalizeDoctorFeedback(selectedLead.doctorFeedback);
  const packageId = `PKG-${selectedLead.id.replace('HMD-', '')}`;
  const updateFeedback = (key, value) => {
    updateDoctorFeedback(selectedLead.id, {
      ...feedback,
      [key]: value,
      status: feedback.status === 'Submitted' ? 'Submitted' : 'Draft'
    });
  };
  const submitFeedback = () => {
    updateDoctorFeedback(selectedLead.id, {
      ...feedback,
      reviewerName: feedback.reviewerName || (matchedDoctor ? textOf(matchedDoctor.displayName, lang) : ''),
      reviewedAt: localNow(),
      status: 'Submitted'
    });
  };

  return (
    <>
      <SectionHeader
        eyebrow="Assigned Cases"
        lang={lang}
        title={{ zh: '医生病例包与预评估反馈', en: 'Doctor case packages and feedback' }}
        subtitle={{
          zh: '这里模拟医生登录后的工作区：只看运营整理后的匿名病例包，并提交路径预评估；不展示客户联系方式。',
          en: 'This simulates the doctor login workspace: only anonymized ops-prepared case packages are visible, with no client contact details.'
        }}
        right={<Pill tone="green" icon="folder-heart">{lang === 'zh' ? `待评估 ${reviewCases.length}` : `Assigned ${reviewCases.length}`}</Pill>}
      />

      <div className="grid gap-6 xl:grid-cols-12">
        <Card className="xl:col-span-3" padding="p-0">
          <div className="border-b hairline p-5">
            <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Queue</div>
            <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '待评估' : 'Assigned'}</h3>
          </div>
          <div className="max-h-[560px] overflow-auto p-3 scroll-soft">
            {reviewCases.map((lead) => {
              const active = lead.id === selectedLead.id;
              const itemFeedback = normalizeDoctorFeedback(lead.doctorFeedback);
              return (
                <button
                  key={lead.id}
                  onClick={() => setActiveLeadId(lead.id)}
                  className={`mb-2 block w-full rounded-2xl p-3 text-left transition ring-1 ${active ? 'bg-gold-50 ring-gold-200' : 'bg-white hairline hover:ring-gold-200'}`}
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="truncate text-sm font-medium text-sea-500">{`PKG-${lead.id.replace('HMD-', '')}`}</span>
                    <Pill tone={itemFeedback.status === 'Submitted' ? 'green' : itemFeedback.status === 'Draft' ? 'gold' : 'marble'}>
                      {labelOf(DOCTOR_FEEDBACK_STATUS_LABELS, itemFeedback.status, lang)}
                    </Pill>
                  </div>
                  <div className="mt-1 truncate text-[12px] text-sea-400">{textOf(getCondition(lead.conditionId).name, lang)}</div>
                  <div className="mt-1 truncate text-[11px] text-marble-500">{lang === 'zh' ? '匿名客户' : 'Anonymized client'} · {getRecordReadiness(lead).pct}%</div>
                </button>
              );
            })}
          </div>
        </Card>

        <div className="space-y-6 xl:col-span-5">
          <Card padding="p-6">
            <div className="mb-5 flex flex-wrap items-start justify-between gap-3">
              <div>
                <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">{packageId}</div>
                <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{textOf(condition.name, lang)}</h3>
                <p className="mt-1 text-sm leading-relaxed text-sea-400/75">
                  {lang === 'zh' ? '匿名客户，不显示联系方式' : 'Anonymized client, contact hidden'}
                </p>
              </div>
              <Pill tone={readiness.pct === 100 ? 'green' : 'gold'} icon="clipboard-check">
                {lang === 'zh' ? `资料 ${readiness.ready}/${readiness.total}` : `Records ${readiness.ready}/${readiness.total}`}
              </Pill>
            </div>

            <div className="grid gap-3 md:grid-cols-2">
              {[
                [lang === 'zh' ? '本地医生建议' : 'Local doctor advice', selectedLead.doctorAdvice || '-'],
                [lang === 'zh' ? '预计时间' : 'Timeframe', selectedLead.timeframe || '-'],
                [lang === 'zh' ? '来华意向' : 'China intent', labelOf(INTENT_LABELS, selectedLead.considersChina, lang)],
                [lang === 'zh' ? '付费意向' : 'Paid intent', labelOf(INTENT_LABELS, selectedLead.acceptsPaid, lang)]
              ].map(([label, value]) => (
                <div key={label} className="rounded-2xl bg-marble-50 p-3 ring-1 hairline">
                  <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{label}</div>
                  <div className="mt-1 text-sm leading-relaxed text-sea-500">{value}</div>
                </div>
              ))}
            </div>

            <div className="mt-5 rounded-3xl bg-marble-50 p-4 ring-1 hairline">
              <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.16em] text-gold-600">{lang === 'zh' ? '运营整理病例摘要' : 'Ops case summary'}</div>
              <div className="whitespace-pre-line text-sm leading-relaxed text-sea-500">{selectedLead.caseSummary || '-'}</div>
            </div>

            <div className="mt-5 grid gap-2">
              {recordItems.map((item) => (
                <div key={item.key} className={`flex items-center justify-between gap-3 rounded-2xl p-3 ring-1 ${item.ready ? 'bg-emerald-50 text-emerald-800 ring-emerald-100' : 'bg-gold-50 text-sea-500 ring-gold-200'}`}>
                  <span className="flex items-center gap-2 text-sm">
                    <Icon name={item.ready ? 'check-circle-2' : 'circle-alert'} size={16} />
                    {item.label}
                  </span>
                  <span className="text-[11px] uppercase tracking-[0.14em]">{item.ready ? (lang === 'zh' ? '已收' : 'Ready') : (lang === 'zh' ? '缺口' : 'Gap')}</span>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <Card className="xl:col-span-4" padding="p-6">
          <div className="mb-5 flex items-center justify-between gap-3">
            <div>
              <div className="text-[10px] font-medium uppercase tracking-[0.22em] text-gold-600">Pre-assessment</div>
              <h3 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} mt-1 text-2xl text-sea-500`}>{lang === 'zh' ? '二诊预评估反馈' : 'Pre-assessment feedback'}</h3>
            </div>
            <Pill tone={feedback.status === 'Submitted' ? 'green' : feedback.status === 'Draft' ? 'gold' : 'marble'} icon="file-pen-line">
              {labelOf(DOCTOR_FEEDBACK_STATUS_LABELS, feedback.status, lang)}
            </Pill>
          </div>

          <div className="grid gap-4">
            <Field
              label={lang === 'zh' ? '反馈医生' : 'Reviewer'}
              value={feedback.reviewerName}
              onChange={(value) => updateFeedback('reviewerName', value)}
              placeholder={matchedDoctor ? textOf(matchedDoctor.displayName, lang) : ''}
            />
            <SelectField
              label={lang === 'zh' ? '路径适配' : 'Pathway fit'}
              value={feedback.pathwayFit}
              onChange={(value) => updateFeedback('pathwayFit', value)}
              options={PATHWAY_FIT_OPTIONS.map((value) => ({ value, label: feedbackLabel(value, lang) }))}
            />
            <SelectField
              label={lang === 'zh' ? '紧急程度' : 'Urgency'}
              value={feedback.urgency}
              onChange={(value) => updateFeedback('urgency', value)}
              options={URGENCY_OPTIONS.map((value) => ({ value, label: feedbackLabel(value, lang) }))}
            />
            <SelectField
              label={lang === 'zh' ? '来华评估适配度' : 'China visit fit'}
              value={feedback.chinaVisitFit}
              onChange={(value) => updateFeedback('chinaVisitFit', value)}
              options={CHINA_VISIT_FIT_OPTIONS.map((value) => ({ value, label: feedbackLabel(value, lang) }))}
            />
            <TextareaField
              label={lang === 'zh' ? '资料缺口' : 'Record gaps'}
              value={feedback.recordGaps}
              onChange={(value) => updateFeedback('recordGaps', value)}
              placeholder={lang === 'zh' ? '例如：需补充 DICOM 原片、病理报告或既往检查对比。' : 'Example: DICOM images, pathology report, or prior comparison needed.'}
            />
            <TextareaField
              label={lang === 'zh' ? '核心判断' : 'Assessment'}
              value={feedback.assessment}
              onChange={(value) => updateFeedback('assessment', value)}
              placeholder={lang === 'zh' ? '基于现有资料的路径预评估，不写成正式诊断。' : 'Pathway pre-assessment based on available records, not a formal diagnosis.'}
            />
            <TextareaField
              label={lang === 'zh' ? '建议下一步' : 'Recommendations'}
              value={feedback.recommendations}
              onChange={(value) => updateFeedback('recommendations', value)}
              placeholder={lang === 'zh' ? '例如：补齐资料后线上二诊、先本地随访、或适合进一步来华门诊评估。' : 'Example: online second opinion after records, local follow-up first, or China outpatient review.'}
            />
            <TextareaField
              label={lang === 'zh' ? '医生备注' : 'Doctor note'}
              value={feedback.doctorNote}
              onChange={(value) => updateFeedback('doctorNote', value)}
              placeholder={lang === 'zh' ? '仅供运营内部理解，不直接发给客户。' : 'For ops context only, not sent directly to the client.'}
            />
          </div>

          <div className="mt-5 rounded-3xl bg-gold-50 p-4 text-sm leading-relaxed text-sea-500 ring-1 ring-gold-200">
            {lang === 'zh'
              ? '提交后会写回运营端。运营需要再整理成客户可读摘要，不直接把内部反馈原文发给客户。'
              : 'Submission writes back to ops. Ops should rewrite it into a client-readable summary instead of sending raw internal feedback.'}
          </div>
          <Button icon="send" onClick={submitFeedback} className="mt-5 w-full">
            {feedback.status === 'Submitted'
              ? (lang === 'zh' ? '更新预评估反馈' : 'Update feedback')
              : (lang === 'zh' ? '提交预评估反馈' : 'Submit feedback')}
          </Button>
        </Card>
      </div>
    </>
  );
};

const DoctorApp = () => {
  const [lang, setLang] = React.useState(() => localStorage.getItem('huamed-lang') || 'zh');
  const [doctorProfiles] = React.useState(loadStoredDoctors);
  const [leads, setLeads] = React.useState(loadStoredLeads);
  const [active, setActive] = React.useState('doctor-overview');
  const [noticeOpen, setNoticeOpen] = React.useState(false);
  const copy = UI[lang];
  const tr = (value) => textOf(value, lang);

  React.useEffect(() => {
    localStorage.setItem('huamed-lang', lang);
  }, [lang]);

  React.useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(leads));
  }, [leads]);

  React.useEffect(() => {
    const syncFromStorage = (event) => {
      if (event.key === STORAGE_KEY) setLeads(loadStoredLeads());
    };
    window.addEventListener('storage', syncFromStorage);
    return () => window.removeEventListener('storage', syncFromStorage);
  }, []);

  const go = (id) => {
    setActive(id);
    requestAnimationFrame(() => {
      document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  };

  const updateDoctorFeedback = (leadId, feedback) => {
    setLeads((prev) => prev.map((lead) => lead.id === leadId ? {
      ...lead,
      doctorFeedback: normalizeDoctorFeedback(feedback)
    } : lead));
  };

  const navItems = [
    { id: 'doctor-overview', icon: 'layout-dashboard', label: lang === 'zh' ? '合作首页' : 'Overview' },
    { id: 'doctor-profiles', icon: 'id-card', label: lang === 'zh' ? '医生档案' : 'Doctor Profile' },
    { id: 'doctor-cases', icon: 'folder-kanban', label: lang === 'zh' ? '待评估病例' : 'Assigned Cases' },
    { id: 'case-package', icon: 'folder-heart', label: lang === 'zh' ? '病例包' : 'Case Package' },
    { id: 'doctor-flow', icon: 'route', label: lang === 'zh' ? '协作流程' : 'Workflow' },
    { id: 'doctor-fit', icon: 'stethoscope', label: lang === 'zh' ? '专科方向' : 'Specialties' },
    { id: 'doctor-boundary', icon: 'shield-alert', label: lang === 'zh' ? '合作边界' : 'Boundaries' }
  ];

  return (
    <div className="app-shell portal-doctor flex min-h-screen">
      <SideNav active={active} go={go} lang={lang} setLang={setLang} copy={copy} portal="doctor" navItems={navItems} />
      <main className="min-w-0 flex-1">
        <TopBar lang={lang} setLang={setLang} copy={copy} onNotice={() => setNoticeOpen(true)} portal="doctor" />
        <div className="space-y-8 px-5 py-6 md:px-10 md:py-8">
          <DoctorHeroSection lang={lang} go={go} />
          <section id="doctor-profiles" className="scroll-mt-24">
            <DoctorProfileSection lang={lang} doctorProfiles={doctorProfiles} />
          </section>
          <section id="doctor-cases" className="scroll-mt-24">
            <DoctorAssignedCasesSection
              lang={lang}
              leads={leads}
              doctorProfiles={doctorProfiles}
              updateDoctorFeedback={updateDoctorFeedback}
            />
          </section>
          <section id="case-package" className="scroll-mt-24">
            <DoctorCasePackageSection lang={lang} />
          </section>
          <section id="doctor-flow" className="scroll-mt-24">
            <DoctorFlowSection lang={lang} />
          </section>
          <section id="doctor-fit" className="scroll-mt-24">
            <DoctorFitSection lang={lang} tr={tr} />
          </section>
          <section id="doctor-boundary" className="scroll-mt-24">
            <DoctorBoundarySection lang={lang} />
          </section>
          <Footer lang={lang} portal="doctor" />
        </div>
      </main>
      <Modal open={noticeOpen} onClose={() => setNoticeOpen(false)} title={copy.riskNotice} lang={lang}>
        <div className="space-y-3">
          {RISK_COPY[lang].map((line, index) => (
            <div key={index} className="flex gap-3 rounded-2xl bg-marble-50 p-3.5 text-sm leading-relaxed text-sea-500 ring-1 hairline">
              <span className="mt-1 h-1.5 w-1.5 shrink-0 rounded-full bg-gold-400" />
              <span>{line}</span>
            </div>
          ))}
        </div>
        <div className="mt-5 flex justify-end">
          <Button variant="sea" icon="check" onClick={() => setNoticeOpen(false)}>{copy.close}</Button>
        </div>
      </Modal>
    </div>
  );
};

const MiniMetric = ({ label, value }) => (
  <div className="rounded-2xl bg-marble-50 p-3 text-center ring-1 hairline">
    <div className="font-serif-display text-3xl text-sea-500">{value}</div>
    <div className="text-[10px] uppercase tracking-[0.18em] text-marble-500">{label}</div>
  </div>
);

const LEGAL_CONTENT = {
  privacy: {
    eyebrow: 'Privacy Policy',
    icon: 'lock-keyhole',
    title: { zh: 'Privacy Policy 隐私政策', en: 'Privacy Policy' },
    updated: { zh: '最后更新：2026 年 5 月 11 日', en: 'Last updated: May 11, 2026' },
    intro: {
      zh: '本隐私政策说明华医畅 HuaMed 在提供来华就医路径协调、资料整理、专家二诊预评估和服务咨询时，如何处理客户和家庭主动提交的信息。',
      en: 'This Privacy Policy explains how HuaMed processes information submitted by clients and families for China care coordination, record organization, specialist pre-assessment, and service consultation.'
    },
    subtitle: { zh: '华医畅按最小必要原则处理资料，用于服务适配判断与路径协调，不用于公开展示或无关营销。', en: 'HuaMed processes only necessary information for service-fit review and pathway coordination, not public display or unrelated marketing.' },
    sections: [
      [{ zh: '1. 我们收集的信息', en: '1. Information we collect' }, [
        { zh: '客户主动填写的基础联系信息，包括姓名、国家/地区、城市、语言和 WhatsApp 联系方式。', en: 'Basic contact information voluntarily submitted by the client, including name, country/region, city, language, and WhatsApp contact.' },
        { zh: '服务判断所需的病种方向、既往检查结果摘要、本地医生建议、家庭关心的问题和希望了解的来华路径。', en: 'Condition direction, record summaries, local doctor advice, family questions, and China care pathway interests needed for service-fit review.' },
        { zh: '客户上传或描述的报告、影像、病理资料、附件文件名、文件大小和提交时间。', en: 'Reports, imaging, pathology materials, attachment names, file sizes, and submission times uploaded or described by the client.' }
      ]],
      [{ zh: '2. 我们如何使用信息', en: '2. How we use information' }, [
        { zh: '判断资料完整度、服务适配性、是否需要补充资料，以及是否适合路径咨询、中国专家二诊预评估或来华协调。', en: 'To assess record completeness, service fit, record gaps, and suitability for pathway consultation, China specialist pre-assessment, or visit coordination.' },
        { zh: '整理病例摘要、问题清单和资料缺口说明，让客户和家庭更清楚下一步需要准备什么。', en: 'To prepare case summaries, question lists, and record-gap notes so clients and families understand next preparation steps.' },
        { zh: '在客户同意的情况下，与服务相关的团队成员、专科方向资源或医院路径资源沟通。', en: 'With client consent, to communicate with relevant HuaMed team members, specialist-direction resources, or hospital pathway resources.' }
      ]],
      [{ zh: '3. 资料分享与授权', en: '3. Sharing and authorization' }, [
        { zh: '华医畅不会出售客户个人信息，也不会把客户病例用于公开展示。', en: 'HuaMed does not sell personal information or use client cases for public display.' },
        { zh: '只有在服务确有需要且客户同意时，我们才会分享整理后的必要资料；分享范围以完成对应服务为限。', en: 'We share organized necessary materials only when required for the service and authorized by the client; the scope is limited to the relevant service.' },
        { zh: '客户首次登录后需要确认是否接受隐私政策和服务条款；接受状态、版本号和时间会被记录，用于证明资料提交前已完成授权确认。', en: 'After first sign-in, clients are asked to accept or decline the Privacy Policy and Terms. Acceptance status, version, and time are recorded to confirm authorization before record submission.' },
        { zh: '客户不应通过网站提交与当前服务无关的第三方隐私资料、身份证件完整照片或支付密码等敏感信息。', en: 'Clients should not submit unrelated third-party private data, full identity document photos, payment passwords, or other sensitive information not needed for the service.' }
      ]],
      [{ zh: '4. 数据安全与保留', en: '4. Security and retention' }, [
        { zh: '我们按最小必要原则保存服务判断所需资料，并限制可接触资料的人员范围。', en: 'We retain only information reasonably necessary for service review and limit access to people who need it for the service.' },
        { zh: '正式生产版本应继续完善账号权限、日志审计、删除请求、备份和数据保留周期。', en: 'A production version should further define account permissions, audit logs, deletion requests, backups, and retention periods.' },
        { zh: '客户可要求更正或删除其提交的信息；如资料仍与正在进行的服务、账务或合规记录相关，我们会说明处理方式。', en: 'Clients may request correction or deletion of submitted information. If information remains needed for an active service, billing, or compliance record, we will explain the handling approach.' }
      ]],
      [{ zh: '5. 联系我们', en: '5. Contact us' }, [
        { zh: '如对资料使用或隐私处理有疑问，请通过网站登录入口或 WhatsApp 服务窗口联系华医畅团队。', en: 'For questions about data use or privacy handling, contact HuaMed through the site sign-in channel or WhatsApp service window.' }
      ]]
    ]
  },
  terms: {
    eyebrow: 'Terms & Conditions',
    icon: 'file-check-2',
    title: { zh: 'Terms & Conditions 服务条款', en: 'Terms & Conditions' },
    updated: { zh: '最后更新：2026 年 5 月 11 日', en: 'Last updated: May 11, 2026' },
    intro: {
      zh: '本服务条款适用于客户使用华医畅 HuaMed 网站、资料提交、免费初步判断、路径咨询、专家二诊预评估和来华就医协调相关服务。',
      en: 'These Terms apply to use of HuaMed websites, record submission, free initial review, pathway consultation, specialist pre-assessment, and China care coordination services.'
    },
    subtitle: { zh: '华医畅提供路径协调与资料整理服务，不替代医院、医生或线下面诊。', en: 'HuaMed provides pathway coordination and record organization services. It does not replace hospitals, doctors, or in-person medical assessment.' },
    sections: [
      [{ zh: '1. 服务范围', en: '1. Scope of services' }, [
        { zh: '华医畅可提供资料完整度初步判断、病例摘要整理、资料缺口清单、路径咨询、专家问题清单、专家二诊预评估协调和来华路径沟通。', en: 'HuaMed may provide initial record-readiness review, case-summary organization, record-gap lists, pathway consultation, specialist question lists, specialist pre-assessment coordination, and China pathway communication.' },
        { zh: '客户提交咨询表单后，华医畅服务团队将在 24 小时内进行初步查看，并通过客户预留联系方式沟通下一步；该初筛不构成医学诊断。', en: 'After a consultation form is submitted, the HuaMed service team will complete an initial review within 24 hours and contact the client through the provided details. This review is not medical diagnosis.' },
        { zh: '具体服务内容以客户选择的套餐、实际资料完整度、病种复杂度和双方确认的服务范围为准。', en: 'Specific deliverables depend on the selected package, record completeness, condition complexity, and confirmed service scope.' }
      ]],
      [{ zh: '2. 医疗责任边界', en: '2. Medical responsibility boundaries' }, [
        { zh: '华医畅不提供最终诊断、治疗方案决定、处方、急救或危重症第一响应。', en: 'HuaMed does not provide final diagnosis, treatment decisions, prescriptions, emergency care, or first-line critical-care response.' },
        { zh: '任何专家意见、路径建议或资料整理结果仅供客户与线下医生进一步沟通参考，最终诊疗以医院和医生线下面诊意见为准。', en: 'Any specialist opinion, pathway note, or organized record output is for further discussion with in-person doctors. Final care depends on hospitals and physicians after assessment.' },
        { zh: '急性胸痛、卒中症状、严重创伤、严重出血、高热寒战等情况，应立即在当地急诊处理。', en: 'Acute chest pain, stroke signs, major trauma, severe bleeding, high fever, or chills should be handled immediately through local emergency care.' }
      ]],
      [{ zh: '3. 费用与支付边界', en: '3. Fees and payment boundaries' }, [
        { zh: '网站展示的价格为华医畅服务费，不包含医院检查、治疗、住院、手术、药品、麻醉、病理、护理、交通、住宿、签证、翻译陪诊或其他第三方费用，除非另有明确说明。', en: 'Displayed prices are HuaMed service fees and exclude hospital testing, treatment, admission, surgery, medication, anesthesia, pathology, nursing, travel, lodging, visa, translation escort, or other third-party fees unless expressly stated.' },
        { zh: '医疗费用由客户直接向医院或医疗机构支付，华医畅不代收医院医疗费用。', en: 'Medical fees are paid directly by the client to hospitals or medical institutions. HuaMed does not collect hospital medical fees on their behalf.' },
        { zh: '套餐价格可能因资料复杂度、病种方向、专家资源和服务深度调整，最终以服务前确认内容为准。', en: 'Package pricing may vary by record complexity, condition direction, specialist resources, and service depth. Final terms are confirmed before service begins.' }
      ]],
      [{ zh: '4. 不作保证', en: '4. No guarantees' }, [
        { zh: '华医畅不承诺疗效、不保证某位专家、不保证床位、手术日期、住院安排、签证结果或治疗结果。', en: 'HuaMed does not guarantee medical outcomes, a specific doctor, hospital bed, surgery date, admission arrangement, visa outcome, or treatment result.' },
        { zh: '客户提交资料不足、病情不适合来华、存在急症风险或不在服务范围内时，华医畅可建议先补资料、当地就医或暂停推进。', en: 'If records are insufficient, the case is unsuitable for China care, emergency risk is present, or the request is outside scope, HuaMed may recommend gathering records, seeking local care, or pausing the process.' }
      ]],
      [{ zh: '5. 客户责任', en: '5. Client responsibilities' }, [
        { zh: '客户应尽量提交真实、完整、清晰的报告、影像、病理和既往治疗资料，并及时说明病情变化。', en: 'Clients should submit accurate, complete, and clear reports, imaging, pathology, and treatment history when available, and promptly disclose changes in condition.' },
        { zh: '客户应自行判断是否接受服务建议，并在重大医疗决定前咨询具备执业资格的医生。', en: 'Clients are responsible for deciding whether to follow service suggestions and should consult licensed physicians before major medical decisions.' }
      ]],
      [{ zh: '6. 变更与联系', en: '6. Updates and contact' }, [
        { zh: '华医畅可能根据产品、法规或运营需要更新本条款。重要变更会在网站页面体现。', en: 'HuaMed may update these Terms based on product, legal, or operational needs. Material changes will be reflected on the website.' },
        { zh: '如对服务范围、费用或条款有疑问，请通过网站登录入口或 WhatsApp 服务窗口联系华医畅团队。', en: 'For questions about service scope, fees, or these Terms, contact HuaMed through the site sign-in channel or WhatsApp service window.' }
      ]]
    ]
  }
};

const LegalPage = ({ lang, type }) => {
  const content = LEGAL_CONTENT[type] || LEGAL_CONTENT.privacy;
  return (
    <>
      <PageIntro lang={lang} eyebrow={content.eyebrow} icon={content.icon} title={textOf(content.title, lang)} subtitle={textOf(content.subtitle, lang)} />
      <Card padding="p-7 md:p-10" className="legal-document">
        <div className="max-w-4xl">
          <div className="font-mono-display text-[11px] uppercase tracking-[0.16em] text-gold-700">{textOf(content.updated, lang)}</div>
          <p className="mt-4 text-[15px] leading-8 text-sea-500">{textOf(content.intro, lang)}</p>
          <div className="mt-8 space-y-8">
            {content.sections.map(([title, items]) => (
              <section key={title.en} className="legal-document-section">
                <h2 className={`${lang === 'zh' ? 'font-zh' : 'font-serif-display'} text-2xl text-sea-500`}>{textOf(title, lang)}</h2>
                <div className="mt-3 space-y-3">
                  {items.map((item) => (
                    <p key={item.en} className="text-sm leading-8 text-sea-400/82">{textOf(item, lang)}</p>
                  ))}
                </div>
              </section>
            ))}
          </div>
        </div>
      </Card>
    </>
  );
};

const Footer = ({ lang, go, portal = 'client' }) => {
  if (portal !== 'client') {
    return (
      <footer className="border-t hairline pb-8 pt-6 text-[11px] text-marble-500">
        <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
          <div className="font-mono-display tracking-[0.14em]">HUAMED · CHINA CARE COORDINATION · 2026</div>
          <div>{lang === 'zh' ? '华医畅提供路径协调与资料整理服务，不构成医疗诊断或治疗建议。' : 'HuaMed provides pathway coordination and record organization, not medical diagnosis or treatment advice.'}</div>
        </div>
      </footer>
    );
  }
  const pageLinks = [
    ['layout-dashboard', lang === 'zh' ? '首页' : 'Home', 'index.html'],
    ['sparkles', lang === 'zh' ? '服务场景' : 'Service Scenarios', 'index.html#conditions'],
    ['users-round', lang === 'zh' ? '团队介绍' : 'Team', 'team.html'],
    ['building-2', lang === 'zh' ? '医院介绍' : 'Hospitals', 'hospitals.html'],
    ['landmark', lang === 'zh' ? '中国医疗体系' : 'China Medical System', 'system.html'],
    ['book-open-check', lang === 'zh' ? '来华就医知识中心' : 'Knowledge Center', 'knowledge.html'],
    ['flask-conical', lang === 'zh' ? '前沿医学咨询' : 'Frontier Medicine', 'frontier-medicine.html'],
    ['route', lang === 'zh' ? '定制就医旅程' : 'Custom Care Journey', 'intake.html']
  ];
  const infoLinks = [
    ['lock-keyhole', 'Privacy Policy', 'privacy.html'],
    ['file-check-2', 'Terms & Conditions', 'terms.html']
  ];
  return (
    <footer className="site-footer">
      <div className="site-footer-grid">
        <div className="site-footer-brand">
          <div className="mb-4 flex items-center gap-3">
            <BrandMark size={42} />
            <div>
              <div className="font-zh text-lg font-semibold text-sea-500">华医畅 HuaMed</div>
              <div className="font-mono-display text-[10px] uppercase tracking-[0.18em] text-gold-700">China Care Coordination</div>
            </div>
          </div>
          <p>{lang === 'zh' ? '华医畅提供路径协调、资料整理、专家意见协调和来华就医支持服务，不构成医疗诊断或治疗建议。' : 'HuaMed provides pathway coordination, record organization, specialist opinion coordination, and China visit support, not medical diagnosis or treatment advice.'}</p>
        </div>
        <div>
          <h3>Pages</h3>
          <div className="site-footer-links">
            {pageLinks.map(([icon, label, href]) => (
              <button key={href} type="button" onClick={() => go?.(href)}><Icon name={icon} size={14} /><span>{label}</span></button>
            ))}
          </div>
        </div>
        <div>
          <h3>Information</h3>
          <div className="site-footer-links">
            {infoLinks.map(([icon, label, href]) => (
              <button key={href} type="button" onClick={() => go?.(href)}><Icon name={icon} size={14} /><span>{label}</span></button>
            ))}
          </div>
        </div>
        <div className="site-footer-risk">
          <h3>{lang === 'zh' ? '风险与边界' : 'Risk Notice'}</h3>
          <div className="space-y-2">
            {RISK_COPY[lang].slice(1).map((line) => (
              <div key={line} className="flex gap-2"><Icon name="shield-alert" size={13} className="mt-0.5 shrink-0 text-gold-600" /><span>{line}</span></div>
            ))}
          </div>
        </div>
      </div>
      <div className="site-footer-bottom">
        <span className="font-mono-display tracking-[0.14em]">HUAMED · 2026</span>
        <span>{lang === 'zh' ? '医疗费用由客户直接向医院或医疗机构支付，华医畅只收取服务费。' : 'Medical fees are paid directly to hospitals or medical institutions. HuaMed charges service fees only.'}</span>
      </div>
    </footer>
  );
};

const AppRouter = () => {
  if (PORTAL === 'ops') return <OpsApp />;
  if (PORTAL === 'doctor') return <DoctorApp />;
  return <ClientApp />;
};

ReactDOM.createRoot(document.getElementById('root')).render(<AppRouter />);
