/* YeYe Expat Centre — Pages (all translated) */
const P = window.YEYE;

function PageHead({ title, sub, actions }) {
  return (
    <div className="phead">
      <div className="pt"><h1 className="h1">{title}</h1>{sub && <div className="muted">{sub}</div>}</div>
      {actions && <div className="flex gap-8 wrap">{actions}</div>}
    </div>
  );
}

/* ===== SERVICES — real catalog grouped by category ===== */
function isFreshUserEmail() {
  try {
    const u = window.YEYE_AUTH && window.YEYE_AUTH.getState && window.YEYE_AUTH.getState().user;
    const e = u && u.email;
    return !!e && ['toptenvideoyou@gmail.com', 'testblue.demo+20260619@yeye-internal.example.com'].includes(e.toLowerCase());
  } catch (_) { return false; }
}
function ServiceCard({ s, openModal, forceUnowned, purchased }) {
  const { t } = useT();
  const price = s.p + (s.u || '');
  const owned = (s.owned || purchased) && !forceUnowned;
  return (
    <Card className="card-pad" style={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="flex ac gap-10">
        <div className="hd-ic" style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: owned ? 'var(--brand-50)' : 'var(--accent-50)', color: owned ? 'var(--brand-600)' : 'var(--accent-600)' }}><Icon name={P.catIcon[s.cat]} size={19} /></div>
        {owned && <Badge tone="ok" dot>{t('c.active')}</Badge>}
      </div>
      <div className="grow"><div className="strong" style={{ fontSize: 14, lineHeight: 1.3 }}>{t('svc.' + s.k)}</div></div>
      <div className="flex jb ac" style={{ paddingTop: 11, borderTop: '1px solid var(--line-2)' }}>
        <span className="strong tnum" style={{ fontSize: 14 }}>{price}</span>
        {owned
          ? (
              <div className="flex ac gap-6">
                {s.payUrl && <Btn variant="ghost" size="sm" icon="refresh-ccw" onClick={() => openModal('service', s)}>Buy Again</Btn>}
                <Btn variant="ghost" size="sm" iconR="arrow-right" onClick={() => openModal('manageService', { service: s })}>{t('c.manage')}</Btn>
              </div>
            )
          : <Btn variant="primary" size="sm" icon="search" onClick={() => openModal('service', s)}>{t('c.review')}</Btn>}
      </div>
    </Card>
  );
}
function ServicesPage({ openModal, purchasedServices, blankProfile }) {
  const { t } = useT();
  const fresh = blankProfile || isFreshUserEmail();
  const purchasedKeys = new Set((purchasedServices || []).map((x) => x.k));
  const owned = P.services.filter((s) => purchasedKeys.has(s.k) || (!fresh && s.owned));
  const ownedKeys = new Set(owned.map((s) => s.k));
  const availableCount = P.services.filter((s) => !ownedKeys.has(s.k)).length;
  return (
    <>
      <PageHead title={t('nav.services')} sub={t('sub.services')} />
      {owned.length > 0 && (
        <>
          <div className="flex ac gap-8 mb-12"><div className="eyebrow">{t('c.myServices')}</div><Badge tone="ok">{owned.length}</Badge></div>
          <div className="grid g-12 mb-24" style={{ gap: 16 }}>
            {owned.map((s) => <div className="col-3" key={s.k}><ServiceCard s={s} openModal={openModal} forceUnowned={fresh} purchased={purchasedKeys.has(s.k)} /></div>)}
          </div>
        </>
      )}
      <div className="flex ac gap-8 mb-16"><div className="eyebrow">{t('c.availableServices')}</div><Badge tone="neut">{availableCount}</Badge></div>
      {P.serviceCats.map((cat) => {
        const list = P.services.filter((s) => s.cat === cat && !ownedKeys.has(s.k));
        if (!list.length) return null;
        return (
          <div key={cat} className="mb-24">
            <div className="flex ac gap-10 mb-12">
              <div className="hd-ic" style={{ width: 30, height: 30, borderRadius: 8 }}><Icon name={P.catIcon[cat]} size={16} /></div>
              <div className="h3" style={{ whiteSpace: 'nowrap', flexShrink: 0 }}>{t('scat.' + cat)}</div>
              <span className="dim" style={{ fontSize: 12.5 }}>{list.length}</span>
            </div>
            <div className="grid g-12" style={{ gap: 16 }}>
              {list.map((s) => <div className="col-3" key={s.k}><ServiceCard s={s} openModal={openModal} forceUnowned={fresh} purchased={purchasedKeys.has(s.k)} /></div>)}
            </div>
          </div>
        );
      })}
    </>
  );
}

function PurchasedServicesPage({ purchasedServices, openModal, go, blankProfile }) {
  const { t } = useT();
  const rows = purchasedServices || [];
  const serviceByKey = {};
  (P.services || []).forEach((s) => { serviceByKey[s.k] = s; });
  const processSeen = new Set();
  const processApplications = (blankProfile ? [] : (P.services || []))
    .filter((s) => s.owned)
    .concat(rows.map((row) => serviceByKey[row.k] || row))
    .map((svc) => {
      const processType = svc.k === 'blue_card' ? 'blue_card' : (svc.k === 'emp_card' ? 'employee_card' : '');
      if (!processType || processSeen.has(processType)) return null;
      processSeen.add(processType);
      return { key: processType, labelKey: svc.k };
    })
    .filter(Boolean);
  return (
    <>
      <PageHead title={t('nav.purchasedServices')} sub={t('sub.purchasedServices')}
        actions={<Btn variant="primary" icon="grid-2x2" onClick={() => go('services')}>{t('nav.services')}</Btn>} />
      {processApplications.length > 0 && (
        <div className="mb-20">
          <div className="flex ac gap-8 mb-12"><div className="eyebrow">Applications</div><Badge tone="info">{processApplications.length}</Badge></div>
          <div className="grid g-12" style={{ gap: 16 }}>
            {processApplications.map((app) => (
              <div className="col-6" key={app.key}>
                <ProcessTrackerCard ct={{ key: app.key }} />
              </div>
            ))}
          </div>
        </div>
      )}
      <Card>
        <CardHead icon="package-check" title={t('svc.purchasedTitle')} sub={rows.length + ' ' + t('svc.itemsWord')} />
        <div className="tbl-wrap" style={{ border: 'none', borderRadius: 0 }}>
          <table className="tbl">
            <thead><tr><th>{t('nav.services')}</th><th>{t('col.category')}</th><th>{t('col.amount')}</th><th>{t('col.status')}</th><th></th></tr></thead>
            <tbody>
              {rows.length === 0 ? (
                <tr><td colSpan="5"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>{t('svc.noPurchased')}</div></td></tr>
              ) : rows.map((row) => {
                const svc = P.services.find((s) => s.k === row.k) || row;
                return (
                  <tr key={row.id || row.k}>
                    <td className="nm">{t('svc.' + svc.k)}</td>
                    <td className="muted">{t('scat.' + svc.cat)}</td>
                    <td className="nm tnum">{svc.p}{svc.u || ''}</td>
                    <td><Badge tone={row.status === 'cancelled' ? 'bad' : row.status === 'paused' ? 'warn' : 'ok'} dot>{t('st.' + row.status)}</Badge></td>
                    <td className="txt-r"><Btn variant="ghost" size="sm" icon="settings" onClick={() => openModal('manageService', { purchase: row, service: svc })}>{t('c.manage')}</Btn></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
}

/* ===== DOCUMENTS ===== */
function DocumentsPage({ openModal, blankProfile, contact, onRefresh }) {
  const { t } = useT();
  const folders = blankProfile ? [] : P.folders;
  const tracker = window.PROCESS_TRACKER || {};
  const formType = tracker.detectFormType ? tracker.detectFormType(contact) : null;
  const docStatus = contact && formType && tracker.documentStatusFromContact
    ? tracker.documentStatusFromContact(contact, formType)
    : { items: tracker.DOCUMENT_CHECKLIST || [], total: (tracker.DOCUMENT_CHECKLIST || []).length, doneCount: 0 };
  const visibleChecklistDocs = (docStatus.items || []).filter((doc) => doc.key !== 'application_fee' && (doc.completed || doc.url));
  const files = visibleChecklistDocs.length
    ? visibleChecklistDocs.map((doc) => ({
      name: doc.label,
      meta: doc.url ? 'Üretilen doküman hazır' : 'Doküman tamamlandı',
      url: doc.url,
      ok: true,
      d: '—',
    }))
    : (blankProfile ? [] : P.files);
  React.useEffect(() => {
    if (!onRefresh) return undefined;
    Promise.resolve(onRefresh()).catch(() => {});
    return undefined;
  }, []);
  return (
    <>
      <PageHead title={t('nav.documents')} sub={t('sub.documents')}
        actions={<><Btn variant="ghost" icon="folder-plus">{t('c.newFolder')}</Btn><Btn variant="primary" icon="upload" onClick={() => openModal('upload')}>{t('c.upload')}</Btn></>} />
      <Card className="mb-24" style={{ overflow: 'hidden' }}>
        <div className="card-bd" style={{ borderBottom: '1px solid var(--line-2)' }}>
          <div className="flex ac gap-12 wrap">
            <div className="hd-ic" style={{ width: 40, height: 40, background: 'var(--surface-3)', color: 'var(--ink-600)' }}><Icon name="list-checks" size={19} /></div>
            <div className="grow">
              <div className="strong" style={{ fontSize: 15 }}>Belge Checklist</div>
              <div className="muted" style={{ fontSize: 12.5 }}>Sadece üretilmiş belgeler görünür; manuel işaretleme yok.</div>
            </div>
            <Badge tone={visibleChecklistDocs.length ? 'ok' : 'warn'} dot>{visibleChecklistDocs.length} belge</Badge>
          </div>
        </div>
        <div className="tbl-wrap" style={{ border: 0, borderRadius: 0 }}>
          <table className="tbl">
            <thead><tr><th>Belge</th><th>Durum</th><th></th></tr></thead>
            <tbody>
              {visibleChecklistDocs.length === 0 ? (
                <tr><td colSpan="3"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>{t('doc.awaiting')}</div></td></tr>
              ) : visibleChecklistDocs.map((doc) => (
                <tr key={doc.key}>
                  <td>
                    <div className="flex ac gap-10">
                      <div className="l-ic" style={doc.completed ? { width: 32, height: 32, background: 'var(--ok-bg)', color: 'var(--ok)' } : { width: 32, height: 32, background: 'var(--surface-3)', color: 'var(--ink-500)' }}>
                        <Icon name={doc.completed ? 'check' : 'file-text'} size={16} />
                      </div>
                      <div>
                        <div className="nm">{doc.label}</div>
                        <div className="dim" style={{ fontSize: 11 }}>{doc.url ? 'Üretilen doküman hazır' : 'Doküman tamamlandı'}</div>
                      </div>
                    </div>
                  </td>
                  <td><Badge tone="ok" dot>{t('c.verified')}</Badge></td>
                  <td className="txt-r">{doc.url ? <Btn variant="ghost" size="sm" icon="link" onClick={() => window.open(doc.url, '_blank')}>Belge Linki</Btn> : <span className="muted">URL bekleniyor</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
      <div className="eyebrow mb-12">{t('col.folders')}</div>
      <div className="grid g-12 mb-24" style={{ gap: 14 }}>
        {folders.map((f, i) => (
          <div className="col-3" key={i}>
            <Card className="card-pad pointer" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div className="hd-ic" style={{ width: 40, height: 40, background: 'var(--surface-3)', color: 'var(--ink-500)' }}><Icon name={f.ic} size={19} /></div>
              <div className="grow"><div className="strong" style={{ fontSize: 14 }}>{t(f.tk)}</div><div className="dim" style={{ fontSize: 12 }}>{f.n} {t('col.files')}</div></div>
              <Icon name="chevron-right" size={16} className="dim" />
            </Card>
          </div>
        ))}
      </div>
      <div className="eyebrow mb-12">{t('col.recent')}</div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>{t('col.name')}</th><th>{t('col.addedBy')}</th><th>{t('col.date')}</th><th>{t('col.status')}</th><th></th></tr></thead>
          <tbody>
            {files.length === 0 ? (
              <tr><td colSpan="5"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>{t('doc.awaiting')}</div></td></tr>
            ) : files.map((f, i) => (
              <tr key={i} className="pointer">
                <td><div className="flex ac gap-10"><div className="l-ic" style={f.ok ? { width: 32, height: 32, background: 'var(--surface-3)', color: 'var(--ink-500)' } : { width: 32, height: 32, background: 'var(--bad-bg)', color: 'var(--bad)' }}><Icon name={f.ic || 'file-check-2'} size={16} /></div><div><div className="nm">{f.name || t('doc.' + f.tk)}</div><div className="dim" style={{ fontSize: 11.5 }}>{f.meta || t('doc.awaiting')}</div></div></div></td>
                <td className="muted">{f.byK ? t('by.' + f.byK) : '—'}</td>
                <td className="muted mono" style={{ fontSize: 12.5 }}>{f.d}</td>
                <td>{f.ok ? <Badge tone="ok" dot>{t('c.verified')}</Badge> : <Badge tone="bad" dot>{t('c.missing')}</Badge>}</td>
                <td className="txt-r">{f.url ? <Btn variant="ghost" size="sm" icon="link" onClick={() => window.open(f.url, '_blank')}>Belge Linki</Btn> : f.ok ? <Btn variant="ghost" size="sm" icon="link" disabled title="Belge URL alanı boş">URL bekleniyor</Btn> : <Btn variant="soft" size="sm" icon="upload" onClick={() => openModal('upload')}>{t('c.upload')}</Btn>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* ===== MESSAGES ===== */
function MessagesPage() {
  const { t } = useT();
  const threads = [
    { whoK: 'immigration', av: 'IM', c: 'brand', lastK: 'm.appt', tm: '2h', n: 2 },
    { whoK: 'support', av: 'SP', c: 'accent', lastK: 'm.doc', tm: '1d', n: 0 },
    { whoK: 'relocation', av: 'RL', c: 'neut', lastK: 'm.reloc', tm: '3d', n: 0 },
  ];
  const [active, setActive] = useState(0);
  const conv = [
    { me: false, k: 'msg.c1', t: '09:12' }, { me: true, k: 'msg.c2', t: '09:20' },
    { me: false, k: 'msg.c3', t: '09:24' }, { me: false, k: 'msg.c4', t: '2h' },
  ];
  const tone = (c) => c === 'brand' ? { bg: 'var(--brand-100)', fg: 'var(--brand-700)' } : c === 'accent' ? { bg: 'var(--accent-100)', fg: 'var(--accent-700)' } : { bg: 'var(--neut-bg)', fg: 'var(--neut)' };
  return (
    <div style={{ height: '100%' }}>
      <div className="card" style={{ display: 'flex', height: 'calc(100vh - 66px - 60px)', minHeight: 460, overflow: 'hidden' }}>
        <div style={{ width: 300, borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column' }} className="desktop-only">
          <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--line-2)' }} className="flex jb ac"><div className="h3">{t('msg.inbox')}</div><IconBtn name="square-pen" /></div>
          <div style={{ overflowY: 'auto', flex: 1 }}>
            {threads.map((th, i) => (
              <div key={i} onClick={() => setActive(i)} className="pointer" style={{ display: 'flex', gap: 11, padding: '13px 16px', borderBottom: '1px solid var(--line-2)', background: active === i ? 'var(--brand-50)' : 'transparent' }}>
                <Avatar size="md" tone={tone(th.c)}>{th.av}</Avatar>
                <div className="grow" style={{ minWidth: 0 }}><div className="flex jb"><span className="nm" style={{ fontSize: 13.5 }}>{t('who.' + th.whoK)}</span><span className="dim" style={{ fontSize: 11 }}>{th.tm}</span></div><div className="dim" style={{ fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t(th.lastK)}</div></div>
                {th.n > 0 && <span className="nav-badge">{th.n}</span>}
              </div>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ padding: '13px 20px', borderBottom: '1px solid var(--line-2)' }} className="flex ac gap-12">
            <Avatar size="md" tone={tone(threads[active].c)}>{threads[active].av}</Avatar>
            <div className="grow"><div className="strong">{t('who.' + threads[active].whoK)}</div><div className="dim flex ac gap-6" style={{ fontSize: 12 }}><i style={{ background: 'var(--ok)', width: 7, height: 7, borderRadius: 99, display: 'inline-block' }} />{t('m.reply')}</div></div>
            <IconBtn name="phone" /><IconBtn name="info" />
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--surface-2)' }}>
            {conv.map((m, i) => (
              <div key={i} style={{ alignSelf: m.me ? 'flex-end' : 'flex-start', maxWidth: '74%' }}>
                <div style={{ padding: '10px 14px', borderRadius: 14, fontSize: 13.5, lineHeight: 1.5, background: m.me ? 'var(--brand-500)' : '#fff', color: m.me ? '#fff' : 'var(--ink-800)', border: m.me ? 'none' : '1px solid var(--line)', borderBottomRightRadius: m.me ? 4 : 14, borderBottomLeftRadius: m.me ? 14 : 4 }}>{t(m.k)}</div>
                <div className="dim" style={{ fontSize: 10.5, marginTop: 4, textAlign: m.me ? 'right' : 'left' }}>{m.t}</div>
              </div>
            ))}
          </div>
          <div style={{ padding: '13px 16px', borderTop: '1px solid var(--line-2)' }} className="flex ac gap-10">
            <IconBtn name="paperclip" />
            <input className="input" placeholder={t('m.write')} style={{ flex: 1 }} />
            <Btn variant="primary" icon="send">{t('c.send')}</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ===== INVOICES ===== */
function InvoicesPage({ openModal, blankProfile }) {
  const { t } = useT();
  const invoices = blankProfile ? [] : P.invoices;
  return (
    <>
      <PageHead title={t('nav.invoices')} sub={t('sub.invoices')}
        actions={<><Btn variant="ghost" icon="life-buoy" onClick={() => openModal('ticket', { catK: 'it', subject: t('ticket.itInvoiceSubject') })}>{t('c.openItTicket')}</Btn><Btn variant="ghost" icon="download">{t('c.statement')}</Btn><Btn variant="primary" icon="credit-card">{t('c.paymentMethods')}</Btn></>} />
      <div className="grid g-12 mb-20" style={{ gap: 16 }}>
        <div className="col-3"><Stat icon="wallet" tone="amber" value={blankProfile ? '€0.00' : '€290.00'} label={t('iv.outBalance')} /></div>
        <div className="col-3"><Stat icon="check-check" value={blankProfile ? '€0.00' : '€160.00'} label={t('iv.paidYear')} /></div>
        <div className="col-3"><Stat icon="receipt" tone="blue" value={String(invoices.length)} label={t('iv.totalInv')} /></div>
        <div className="col-3"><Stat icon="calendar-clock" value={blankProfile ? '—' : '14 Jun'} label={t('iv.nextDue')} /></div>
      </div>
      {!blankProfile && <Alert tone="warn" icon="triangle-alert" title={t('iv.alert')} action={<Btn variant="primary" size="sm">{t('c.payNow')}</Btn>} />}
      <div className="tbl-wrap mt-16">
        <table className="tbl">
          <thead><tr><th>{t('col.invoice')}</th><th>{t('nav.services')}</th><th>{t('col.amount')}</th><th>{t('col.date')}</th><th>{t('col.status')}</th><th></th></tr></thead>
          <tbody>
            {invoices.length === 0 ? (
              <tr><td colSpan="6"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>—</div></td></tr>
            ) : invoices.map((inv, i) => (
              <tr key={i}>
                <td className="mono nm" style={{ fontSize: 12.5 }}>{inv.id}</td>
                <td className="muted">{t('iv.' + inv.svcK)}</td>
                <td className="nm tnum">{inv.amt}</td>
                <td className="muted mono" style={{ fontSize: 12.5 }}>{inv.due}</td>
                <td><Badge tone={inv.stc} dot>{t('st.' + inv.st)}</Badge></td>
                <td className="txt-r">{inv.st === 'outstanding' ? <Btn variant="primary" size="sm">{t('c.pay')}</Btn> : <IconBtn name="download" />}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* ===== SUPPORT ===== */
function SupportPage({ openModal, tickets }) {
  const { t } = useT();
  const cards = [{ ic: 'book-open', k: 'kb' }, { ic: 'messages-square', k: 'chat' }, { ic: 'phone', k: 'call' }, { ic: 'calendar-plus', k: 'book' }];
  return (
    <>
      <PageHead title={t('nav.support')} sub={t('sub.support')}
        actions={<Btn variant="primary" icon="plus" onClick={() => openModal('ticket')}>{t('c.newTicket')}</Btn>} />
      <div className="grid g-12 mb-24" style={{ gap: 14 }}>
        {cards.map((c, i) => (
          <div className="col-3" key={i}><Card className="card-pad pointer" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div className="hd-ic" style={{ width: 40, height: 40 }}><Icon name={c.ic} size={19} /></div>
            <div><div className="strong" style={{ fontSize: 14 }}>{t('sup.' + c.k)}</div><div className="dim" style={{ fontSize: 12 }}>{t('sup.' + c.k + 'S')}</div></div>
          </Card></div>
        ))}
      </div>
      <Card>
        <CardHead icon="life-buoy" title={t('sup.yourTickets')} sub={t('sup.yourTicketsSub')} />
        <div className="tbl-wrap" style={{ border: 'none', borderRadius: 0 }}>
          <table className="tbl">
            <thead><tr><th>{t('col.ticket')}</th><th>{t('col.subject')}</th><th>{t('col.category')}</th><th>{t('col.status')}</th><th>{t('col.updated')}</th></tr></thead>
            <tbody>
              {(tickets || P.tickets).map((tk, i) => (
                <tr key={i} className="pointer">
                  <td className="mono nm" style={{ fontSize: 12.5 }}>{tk.id}</td>
                  <td className="nm">{tk.subject || t('t.' + tk.tk)}</td>
                  <td className="muted">{t('cat.' + tk.catK)}</td>
                  <td><Badge tone={tk.stc} dot>{t('st.' + tk.st)}</Badge></td>
                  <td className="muted">{tk.upd} {t('col.ago')}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
}

/* ===== CASES ===== */
function formatFieldValue(value) {
  const text = String(value || '').trim();
  if (!text) return '';
  if (/^\d{4}-\d{2}-\d{2}T/.test(text)) return text.slice(0, 10);
  return text;
}

function contactFieldValue(contact, keys, fallback) {
  const wanted = (Array.isArray(keys) ? keys : [keys]).filter(Boolean);
  const values = contact || {};
  const raw = contact?.raw || {};
  const custom = contact?.customFields || contact?.fields || raw.customFields || [];
  const norm = (value) => String(value || '').toLowerCase().replace(/[\s._-]+/g, '');
  for (const key of wanted) {
    const direct = values[key] ?? raw[key];
    if (direct != null && String(direct).trim() !== '') return direct;
    const stripped = String(key).replace(/^contact\./, '').replace(/^business\./, '');
    const strippedValue = values[stripped] ?? raw[stripped];
    if (strippedValue != null && String(strippedValue).trim() !== '') return strippedValue;
  }
  if (Array.isArray(custom)) {
    const found = custom.find((field) => wanted.some((key) => [
      field?.key, field?.fieldKey, field?.name, field?.id, field?.fieldId, field?.customFieldId
    ].some((candidate) => norm(candidate) === norm(key))));
    const value = found?.value ?? found?.field_value ?? found?.fieldValue;
    if (value != null && String(value).trim() !== '') return value;
  } else if (custom && typeof custom === 'object') {
    for (const key of wanted) {
      const direct = custom[key];
      if (direct != null && String(direct).trim() !== '') return direct;
      const foundKey = Object.keys(custom).find((item) => norm(item) === norm(key));
      if (foundKey && custom[foundKey] != null && String(custom[foundKey]).trim() !== '') return custom[foundKey];
    }
  }
  return fallback || '';
}

function isFilledContactValue(value) {
  const text = String(value ?? '').trim();
  return !!text && text !== '—' && text.toLowerCase() !== 'eksik';
}

function submittedFormChips(contact, formKey) {
  const tags = (contact?.tags || contact?.raw?.tags || []).map((tag) => String(tag).toLowerCase());
  const chips = [];
  if (formKey === 'blue_card' || tags.some((tag) => tag.includes('blue_card'))) chips.push({ key: 'blue_card', label: 'Blue Card', tone: 'info' });
  if (formKey === 'employee_card' || tags.some((tag) => tag.includes('employee_card'))) chips.push({ key: 'employee_card', label: 'Employee Card', tone: 'warn' });
  return chips.length ? chips : (formKey ? [{ key: formKey, label: formKey === 'blue_card' ? 'Blue Card' : 'Employee Card', tone: 'info' }] : []);
}

function contactDisplayName(contact) {
  return [contactFieldValue(contact, ['firstName', 'first_name', 'contact.first_name']), contactFieldValue(contact, ['lastName', 'last_name', 'contact.last_name'])]
    .filter(Boolean).join(' ').trim() || contact?.name || contact?.email || '—';
}

function contactInitials(contact) {
  const name = contactDisplayName(contact);
  const parts = name.split(/\s+/).filter(Boolean);
  return (parts.length > 1 ? parts[0][0] + parts[1][0] : name.slice(0, 2)).toUpperCase();
}

function labelFromPlaceholder(row) {
  const raw = String(row?.placeholder || row?.label || '').replace(/[{}]/g, '').trim();
  const labels = {
    ApplicationType: 'Başvuru Tipi', FirstName: 'Ad', LastName: 'Soyad', Email: 'E-posta', Phone: 'Telefon',
    BirthCountry: 'Doğum Ülkesi', BirthCountryCode: 'Doğum Ülkesi Kodu', BirthDate: 'Doğum Tarihi',
    BirthName: 'Doğum Adı', BirthPlace: 'Doğum Yeri', Citizenship: 'Vatandaşlık', Gender: 'Cinsiyet',
    MaritalStatus: 'Medeni Durum', Nationality: 'Uyruk', PassportNumber: 'Pasaport No',
    DateOfIssue: 'Veriliş Tarihi', ExpirationDate: 'Geçerlilik Tarihi', NationalId: 'Ulusal Kimlik No',
    EmployerName: 'İşveren Adı', CompanyName: 'Şirket', Position: 'Pozisyon', Occupation: 'Meslek',
    Address: 'Adres', City: 'Şehir', Country: 'Ülke', PostalCode: 'Posta Kodu',
  };
  if (labels[raw]) return labels[raw];
  if (!raw) return row?.fieldName || 'Alan';
  return raw.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim();
}

function buildContactCardSections(contact, rows, formKey) {
  const mkRow = (label, value, key) => ({ l: label, v: formatFieldValue(value), key });
  const schemaRows = rows.filter((row) => row.schemaSource === 'v3');
  if (schemaRows.length) {
    const bucketFor = (row) => {
      const id = String(row.sectionId || '');
      const title = String(row.sectionTitle || row.section || '');
      const raw = `${id} ${title}`.toLowerCase();
      if (id === 'contact_kisisel_iletisim') return { id, title: 'Kişisel İletişim', filterId: id };
      if (id === 'personal_information') return { id, title: 'Kişisel Bilgiler', filterId: 'personal_information' };
      if (id === 'company') return { id, title: 'Şirket Bilgileri', filterId: 'company' };
      if (/residence|czechia|shipping|address|adres|ikamet|kargo/.test(raw)) return { id, title, filterId: 'addresses' };
      if (/passport|travel|seyahat|pasaport/.test(raw)) return { id, title: 'Pasaport / Seyahat Belgesi', filterId: 'passport_travel_document' };
      if (/last_employment|previous_stay|employment|önceki|son istihdam/.test(raw)) return { id, title, filterId: 'last_employment' };
      if (/spouse|children|parents|siblings|family|eş|cocuk|çocuk|anne|baba|kardeş|kardes/.test(raw)) return { id, title, filterId: 'family_information' };
      if (/consent|onay/.test(raw)) return { id, title: 'Onaylar', filterId: 'approvals' };
      return { id, title: title || 'Form Bölümü', filterId: id };
    };
    const familyMemberIndex = (row, type) => {
      const raw = `${row?.label || row?.placeholder || ''} ${row?.fieldName || ''} ${row?.formKey || ''}`.toLowerCase();
      const pattern = type === 'child'
        ? /(?:çocuk|child)\s*([1-4])|child([1-4])/
        : /(?:kardeş|kardes|sibling)\s*([1-4])|sibling([1-4])/;
      const match = raw.match(pattern);
      const index = Number(match?.[1] || match?.[2] || 0);
      return index >= 1 && index <= 4 ? index : 0;
    };
    const familyCount = (type) => {
      const wanted = type === 'child' ? 'numChildren' : 'numSiblings';
      const row = schemaRows.find((item) => item.formKey === wanted);
      const value = row ? row.value : '';
      if (/^(0|no|none|yok|hayır|hayir)$/i.test(String(value || '').trim())) return 0;
      const numeric = Number.parseInt(String(value || '').match(/\d+/)?.[0] || '', 10);
      return Number.isFinite(numeric) ? Math.max(0, Math.min(4, numeric)) : 4;
    };
    const sections = new Map();
    const addSectionRow = (section, row) => {
      if (!sections.has(section.id)) sections.set(section.id, Object.assign({}, section, { rows: [], seen: new Set() }));
      const target = sections.get(section.id);
      const key = row.updateKey || row.fieldName || row.key || row.label;
      if (target.seen.has(key)) return;
      target.seen.add(key);
      target.rows.push(mkRow(row.label || row.placeholder || row.fieldName || 'Alan', row.value, key));
    };
    schemaRows.forEach((row) => {
      const bucket = bucketFor(row);
      const sectionId = String(row.sectionId || '');
      const raw = `${sectionId} ${row.sectionTitle || row.section || ''}`.toLowerCase();
      if (/parents|anne|baba/.test(raw)) {
        const label = String(row.label || row.placeholder || '');
        const parent = label.startsWith('Baba - ') ? 'Baba' : (label.startsWith('Anne - ') ? 'Anne' : '');
        if (parent) {
          addSectionRow({ id: `${bucket.filterId}:${sectionId}:${parent}`, title: parent, filterId: bucket.filterId }, Object.assign({}, row, { label: label.replace(`${parent} - `, '') }));
          return;
        }
      }
      if (/children|çocuk|cocuk/.test(raw)) {
        const index = familyMemberIndex(row, 'child');
        const count = familyCount('child');
        if (index && index <= count) {
          addSectionRow({ id: `${bucket.filterId}:${sectionId}:${index}`, title: `Çocuk ${index}`, filterId: bucket.filterId }, Object.assign({}, row, { label: String(row.label || '').replace(new RegExp(`^(?:Çocuk|Child)\\s*${index}\\s*-\\s*`, 'i'), '') }));
        }
        return;
      }
      if (/siblings|kardeş|kardes/.test(raw)) {
        const index = familyMemberIndex(row, 'sibling');
        const count = familyCount('sibling');
        if (index && index <= count) {
          addSectionRow({ id: `${bucket.filterId}:${sectionId}:${index}`, title: `Kardeş ${index}`, filterId: bucket.filterId }, Object.assign({}, row, { label: String(row.label || '').replace(new RegExp(`^(?:Kardeş|Kardes|Sibling)\\s*${index}\\s*-\\s*`, 'i'), '') }));
        }
        return;
      }
      addSectionRow(bucket, row);
    });
    return Array.from(sections.values()).map((section) => ({
      id: section.id,
      title: section.title,
      filterId: section.filterId,
      rows: section.rows,
    })).filter((section) => section.rows.length);
  }
  const byPlaceholder = {};
  rows.forEach((row) => {
    const clean = String(row.placeholder || '').replace(/[{}]/g, '').trim();
    if (clean && !byPlaceholder[clean]) byPlaceholder[clean] = row;
  });
  const pickRow = (names, label, fallbackKeys) => {
    const row = (Array.isArray(names) ? names : [names]).map((name) => byPlaceholder[name]).find(Boolean);
    return mkRow(label, row?.value || contactFieldValue(contact, fallbackKeys || []), row?.fieldName || label);
  };
  const formLabel = formKey === 'blue_card' ? 'Blue Card' : (formKey === 'employee_card' ? 'Employee Card' : '—');
  const used = new Set();
  const use = (row) => {
    [row?.fieldName, row?.placeholder, String(row?.placeholder || '').replace(/[{}]/g, '').trim()].filter(Boolean).forEach((key) => used.add(key));
    return row;
  };

  const contactRows = [
    mkRow('Başvuru Tipi', formLabel, 'application_type'),
    use(pickRow('FirstName', 'Ad', ['firstName', 'first_name', 'contact.first_name'])),
    use(pickRow('LastName', 'Soyad', ['lastName', 'last_name', 'contact.last_name'])),
    use(pickRow('Email', 'E-posta', ['email', 'contact.email'])),
    use(pickRow('Phone', 'Telefon', ['phone', 'contact.phone'])),
  ];

  const sectionMap = [
    { id: 'personal_information', title: 'Kişisel Bilgiler', filterId: 'personal_information', test: (row) => row.section === 'A - Personal data' },
    { id: 'company', title: 'İşveren', filterId: 'company', test: (row) => row.section === 'F - Employment / Company' },
    { id: 'addresses', title: 'Adres Bilgileri', filterId: 'addresses', test: (row) => /^B |^C1 |^C2 /.test(row.section) },
    { id: 'passport_travel_document', title: 'Pasaport Bilgileri', filterId: 'passport_travel_document', test: (row) => row.section === 'D - Passport / Permit' },
    { id: 'last_employment', title: 'Son İstihdam', filterId: 'last_employment', test: (row) => row.section === 'E - Previous stay / Previous work' },
    { id: 'family_information', title: 'Aile Bilgileri', filterId: 'family_information', test: (row) => ['G - Spouse', 'H - Children', 'I - Parents', 'J - Siblings'].includes(row.section) },
    { id: 'approvals', title: 'Onaylar', filterId: 'approvals', test: (row) => row.section === 'K - Education / Occupation' },
  ];

  const sections = [{ id: 'contact_kisisel_iletisim', title: 'Kişisel İletişim', filterId: 'contact_kisisel_iletisim', rows: contactRows }];
  sectionMap.forEach((def) => {
    const sectionRows = rows
      .filter((row) => ![row.fieldName, row.placeholder, String(row.placeholder || '').replace(/[{}]/g, '').trim()].some((key) => used.has(key)) && def.test(row))
      .map((row) => mkRow(labelFromPlaceholder(row), row.value, row.fieldName));
    const dedupedRows = def.id === 'personal_information'
      ? sectionRows.filter((row) => !['Ad', 'Soyad', 'E-posta', 'Telefon'].includes(row.l))
      : sectionRows;
    if (dedupedRows.length) sections.push({ ...def, rows: dedupedRows });
  });
  return sections;
}

function ContactRow({ row }) {
  const filled = isFilledContactValue(row.v);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
      margin: filled ? 0 : '6px 0', padding: filled ? '10px 0' : '9px 10px',
      borderBottom: filled ? '1px solid var(--line-2)' : 'none',
      border: filled ? 'none' : '1px solid var(--bad-line)',
      borderRadius: filled ? 0 : 10, background: filled ? 'transparent' : 'var(--bad-bg)'
    }}>
      <span style={{ fontSize: 12.5, fontWeight: filled ? 500 : 700, color: filled ? 'var(--ink-500)' : 'var(--bad)' }}>{row.l}</span>
      <span style={{ fontSize: 13.5, color: filled ? 'var(--ink-900)' : 'var(--bad)', fontWeight: 650, textAlign: 'right', wordBreak: 'break-word' }}>
        {filled ? row.v : 'Eksik'}
      </span>
    </div>
  );
}

function ApplicationFieldsCard({ ct, contact, fieldMappings }) {
  const [showAll, setShowAll] = useState(false);
  const formKey = ct && (ct.key === 'blue_card' || ct.key === 'employee_card') ? ct.key : '';
  if (!formKey || !window.YEYE_FIELD_MAPPING) return null;
  const rows = window.YEYE_FIELD_MAPPING.forForm(fieldMappings || [], formKey, contact || {});
  const filled = rows.filter((row) => row.value);
  const visibleRows = showAll ? rows : (filled.length ? filled : rows).slice(0, 24);
  const sections = visibleRows.reduce((acc, row) => {
    (acc[row.section] = acc[row.section] || []).push(row);
    return acc;
  }, {});
  const copy = {
    empty: contact ? 'No submitted values found yet.' : 'GHL contact data is not connected for this session.',
    mapped: 'mapped fields',
    submitted: 'submitted values',
    showAll: 'Show all mapped fields',
    showFilled: 'Show submitted only',
    missing: 'Waiting',
  };

  return (
    <Card>
      <CardHead icon="clipboard-list" title="Application data" sub={`${rows.length} ${copy.mapped} · ${filled.length} ${copy.submitted}`} />
      <div className="card-bd" style={{ paddingTop: 0 }}>
        {!rows.length ? (
          <div className="muted" style={{ padding: '4px 0 14px' }}>{copy.empty}</div>
        ) : (
          <>
            <div className="flex jb ac wrap gap-10 mb-14">
              <div className="muted" style={{ fontSize: 12.5 }}>Blue Card / Employee Card fields are read from the GHL mapping library.</div>
              <Btn variant="ghost" size="sm" icon={showAll ? 'eye' : 'list'} onClick={() => setShowAll((v) => !v)}>
                {showAll ? copy.showFilled : copy.showAll}
              </Btn>
            </div>
            <div className="flex col gap-16">
              {Object.keys(sections).map((section) => (
                <div key={section}>
                  <div className="eyebrow mb-8">{section}</div>
                  <div className="grid g-12" style={{ gap: 10 }}>
                    {sections[section].map((row) => (
                      <div className="col-4" key={`${row.fieldName}-${row.placeholder}`}>
                        <div style={{ border: '1px solid var(--line-2)', borderRadius: 'var(--r-sm)', padding: 12, minHeight: 76, background: row.value ? 'var(--surface)' : 'var(--surface-2)' }}>
                          <div className="dim" style={{ fontSize: 11.5, marginBottom: 6, lineHeight: 1.35 }}>{row.label}</div>
                          <div className={row.value ? 'strong' : 'muted'} style={{ fontSize: 13, lineHeight: 1.35, wordBreak: 'break-word' }}>
                            {formatFieldValue(row.value) || copy.missing}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </Card>
  );
}

function FormSubmissionPage({ ct, contact, fieldMappings, onRefresh, syncState }) {
  const { t } = useT();
  const [activeSection, setActiveSection] = useState('all');
  const [activeForm, setActiveForm] = useState('');
  const [onlyMissing, setOnlyMissing] = useState(false);
  const formKey = ct && (ct.key === 'blue_card' || ct.key === 'employee_card') ? ct.key : '';
  const activeFormKey = activeForm || formKey;
  const rows = activeFormKey && window.YEYE_FIELD_MAPPING
    ? window.YEYE_FIELD_MAPPING.forForm(fieldMappings || [], activeFormKey, contact || {})
    : [];
  const filled = rows.filter((row) => row.value);
  const missing = rows.filter((row) => !row.value);
  const allSections = buildContactCardSections(contact || {}, rows, activeFormKey);
  const visibleSections = allSections
    .filter((section) => activeSection === 'all' || section.filterId === activeSection || section.id === activeSection)
    .map((section) => ({ ...section, rows: onlyMissing ? section.rows.filter((row) => !isFilledContactValue(row.v)) : section.rows }))
    .filter((section) => section.rows.length);
  const formChips = submittedFormChips(contact, formKey);
  const contactName = contactDisplayName(contact || {});
  const contactEmail = contact?.email || contactFieldValue(contact, ['email', 'contact.email']);
  const contactPhone = contactFieldValue(contact, ['phone', 'contact.phone']);
  const companyName = contactFieldValue(contact, [
    'business.name', 'business.companyName', 'companyName', 'company_name', 'contact.company_name', 'contact.employer_name'
  ]);
  const companyMeta = [
    contactFieldValue(contact, ['business.city', 'company_city', 'contact.company_city']),
    contactFieldValue(contact, ['business.country', 'company_country', 'contact.company_country']),
    contactFieldValue(contact, ['business.status', 'company_status'])
  ].filter(Boolean).join(' · ');
  const primaryFilters = [
    { id: 'all', label: 'Tümü' },
    { id: 'contact_kisisel_iletisim', label: 'İletişim' },
    { id: 'personal_information', label: 'Kişisel Bilgiler' },
    { id: 'company', label: 'Şirket Bilgileri' },
    { id: 'addresses', label: 'Adres Bilgileri' },
    { id: 'passport_travel_document', label: 'Pasaport / Seyahat Belgesi' },
  ].filter((filter) => filter.id === 'all' || allSections.some((section) => section.filterId === filter.id || section.id === filter.id));
  const otherFilters = [
    { id: 'last_employment', label: 'Son İstihdam' },
    { id: 'family_information', label: 'Aile Bilgileri' },
    { id: 'approvals', label: 'Onaylar' },
  ].filter((filter) => allSections.some((section) => section.filterId === filter.id || section.id === filter.id));
  const otherActive = otherFilters.some((filter) => filter.id === activeSection);
  const lastSync = syncState && syncState.lastSync
    ? new Date(syncState.lastSync).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    : '—';

  useEffect(() => {
    if (!onRefresh) return undefined;
    let cancelled = false;
    onRefresh();
    const timer = setInterval(() => { if (!cancelled) onRefresh(); }, 15000);
    return () => { cancelled = true; clearInterval(timer); };
  }, [formKey]);

  useEffect(() => {
    if (formKey) setActiveForm(formKey);
  }, [formKey]);

  return (
    <>
      <div className="flex ac gap-8 mb-16">
        <Icon name="arrow-left" size={16} />
        <span className="muted" style={{ fontSize: 13, fontWeight: 650 }}>Müşteriler</span>
      </div>
      <Card className="mb-18" style={{ overflow: 'hidden' }}>
        <div className="card-bd">
          <div className="flex ac wrap gap-16">
            <Avatar size="lg" tone={{ bg: 'var(--brand-400)', fg: '#fff' }}>{contactInitials(contact || {})}</Avatar>
            <div className="grow" style={{ minWidth: 260 }}>
              <div className="flex ac gap-8 wrap">
                <div className="h2">{contactName}</div>
                <Badge tone="ok">Aktif</Badge>
              </div>
              <div className="muted mono" style={{ fontSize: 12.5, marginTop: 5 }}>{[contactEmail, contactPhone].filter(Boolean).join(' · ') || '—'}</div>
            </div>
            <div className="flex ac gap-8 wrap" style={{ justifyContent: 'flex-end' }}>
              <Btn variant={onlyMissing ? 'primary' : 'ghost'} icon="circle-alert" onClick={() => setOnlyMissing((v) => !v)}>Eksik Alanlar</Btn>
              <Btn variant="ghost" icon="pencil">Düzenle</Btn>
            </div>
          </div>
        </div>
      </Card>
      {companyName && (
        <Card className="mb-18" style={{ borderColor: 'var(--accent-300)' }}>
          <div className="card-bd">
            <div className="flex ac gap-14">
              <Avatar tone={{ bg: 'var(--accent-100)', fg: 'var(--accent-700)' }}>{String(companyName).slice(0, 2).toUpperCase()}</Avatar>
              <div className="grow">
                <div className="eyebrow">Bağlı Firma · GHL business</div>
                <div className="strong" style={{ fontSize: 15 }}>{companyName}</div>
                {companyMeta && <div className="muted mono" style={{ fontSize: 11.5 }}>{companyMeta}</div>}
              </div>
              <Btn variant="primary" iconR="chevron-right" style={{ background: 'var(--accent-500)' }}>Firma Detayı</Btn>
            </div>
          </div>
        </Card>
      )}
      {syncState && syncState.error && (
        <Alert tone="warn" icon="triangle-alert" title="GHL sync warning">{syncState.error}</Alert>
      )}
      {rows.length === 0 ? (
        <Card className="mt-16"><div className="card-bd"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>—</div></div></Card>
      ) : (
        <>
          <div className="flex ac gap-7 wrap mb-18">
            {primaryFilters.map((filter) => (
              <button key={filter.id} className={'btn btn-sm ' + (activeSection === filter.id ? 'btn-primary' : 'btn-ghost')} onClick={() => setActiveSection(filter.id)}>{filter.label}</button>
            ))}
            {otherFilters.length > 0 && (
              <select value={otherActive ? activeSection : ''} onChange={(e) => setActiveSection(e.target.value || 'all')} className={'btn btn-sm ' + (otherActive ? 'btn-primary' : 'btn-ghost')} style={{ height: 34 }}>
                <option value="">Diğerleri</option>
                {otherFilters.map((filter) => <option key={filter.id} value={filter.id}>{filter.label}</option>)}
              </select>
            )}
            <div className="grow" />
            <Btn variant="ghost" size="sm" icon={syncState && syncState.syncing ? 'loader-circle' : 'refresh-cw'} onClick={onRefresh}>
              {syncState && syncState.syncing ? 'Senkronize' : `Son sync ${lastSync}`}
            </Btn>
            <Btn variant={onlyMissing ? 'primary' : 'ghost'} size="sm" icon="circle-alert" onClick={() => setOnlyMissing((v) => !v)}>
              Sadece Eksikler ({missing.length})
            </Btn>
          </div>

          <Card className="mb-18">
            <div className="card-bd">
              <div className="mb-10" style={{ fontWeight: 800, fontSize: 12, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '.055em' }}>
                {'Submit Edilen Formlar'.toLocaleUpperCase('tr-TR')}
              </div>
              <div className="flex ac gap-8 wrap">
                {formChips.map((chip) => (
                  <button key={chip.key} className={'btn btn-sm ' + (activeFormKey === chip.key ? 'btn-primary' : 'btn-ghost')} onClick={() => { setActiveForm(chip.key); setActiveSection('all'); }}>
                    {chip.label}
                  </button>
                ))}
              </div>
            </div>
          </Card>

          <div className="flex col gap-16">
            {visibleSections.length === 0 ? (
              <Card><div className="card-bd"><div className="muted" style={{ padding: 18, textAlign: 'center' }}>—</div></div></Card>
            ) : visibleSections.map((section) => {
              const sectionFilled = section.rows.filter((row) => isFilledContactValue(row.v)).length;
              return (
                <Card key={section.id} style={{ overflow: 'hidden' }}>
                  <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line-2)', fontWeight: 750, fontSize: 13, color: 'var(--ink-900)', letterSpacing: '.04em' }}>
                    {String(section.title || '').toLocaleUpperCase('tr-TR')}
                    <span className="muted mono" style={{ fontSize: 11.5, fontWeight: 600, marginLeft: 8 }}>{sectionFilled}/{section.rows.length}</span>
                  </div>
                  <div style={{ padding: '6px 20px 12px' }}>
                    {section.rows.map((row) => <ContactRow key={`${section.id}-${row.key}-${row.l}`} row={row} />)}
                  </div>
                </Card>
              );
            })}
          </div>
        </>
      )}
    </>
  );
}

function CasesPage({ ct, contact, fieldMappings }) {
  const { t } = useT();
  const tracker = window.PROCESS_TRACKER;
  const formKey = ct && (ct.key === 'blue_card' || ct.key === 'employee_card') ? ct.key : 'employee_card';
  const effectiveDoc = contact && tracker ? tracker.processDocFromContact(contact, formKey, { completedStages: {} }) : null;
  const progress = effectiveDoc && tracker ? tracker.calculateProgress(effectiveDoc) : (ct && ct.pct) || 50;
  const cases = [
    { id: ct?.caseId || 'YE-CZ-2026-0142', title: t('case.' + formKey), st: ct?.curr || t('cstat.ministry'), stc: ct?.currTone || 'info', pct: progress },
  ];
  return (
    <>
      <PageHead title={t('nav.cases')} sub={t('sub.cases')} actions={<Btn variant="primary" icon="plus">{t('c.open')}</Btn>} />
      <div className="flex col gap-14 mb-20">
        {cases.map((c, i) => (
          <Card key={i} className="card-pad">
            <div className="flex jb ac wrap gap-12">
              <div className="flex ac gap-12"><div className="hd-ic" style={{ width: 40, height: 40 }}><Icon name="folder-kanban" size={19} /></div>
                <div><div className="strong">{c.title}</div><div className="dim mono" style={{ fontSize: 12 }}>{c.id}</div></div></div>
              <div className="flex ac gap-16"><div style={{ width: 160 }}><Progress value={c.pct} thin /></div><Badge tone={c.stc} dot>{c.st}</Badge><Btn variant="ghost" size="sm" iconR="arrow-right">{t('c.open')}</Btn></div>
            </div>
          </Card>
        ))}
      </div>
      <div className="grid g-12" style={{ gap: 16 }}>
        <div className="col-5"><ProcessTrackerCard ct={{ key: formKey }} /></div>
        <div className="col-7"><ApplicationFieldsCard ct={{ key: formKey }} contact={contact} fieldMappings={fieldMappings} /></div>
      </div>
    </>
  );
}

/* ===== APPOINTMENTS — Calendar (June 2026) ===== */
const CAL_EVENTS = [
  { d: 9, key: 'police', time: '09:30', tone: 'ok', ic: 'shield' },
  { d: 14, key: 'deadline', time: '23:59', tone: 'bad', ic: 'file-warning' },
  { d: 19, key: 'biometrics', time: '11:00', tone: 'info', ic: 'fingerprint' },
  { d: 27, key: 'consult', time: '10:00', tone: 'brand', ic: 'video' },
];
const TODAY = 7, MONTH_IDX = 5, FIRST_DOW = 0, DAYS_IN = 30;
function evTone(tone) {
  const m = { ok: ['var(--ok-bg)', 'var(--ok)'], info: ['var(--info-bg)', 'var(--info)'], bad: ['var(--bad-bg)', 'var(--bad)'], brand: ['var(--brand-500)', '#fff'] };
  const [bg, fg] = m[tone] || m.ok; return { background: bg, color: fg };
}
function ApptDetail({ e, title, loc, dim }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: 14 }}>
      <div className="flex ac gap-10 mb-12">
        <div className="l-ic" style={{ ...evTone(e.tone), width: 36, height: 36 }}><Icon name={e.ic} size={18} /></div>
        <div className="grow"><div className="strong" style={{ fontSize: 14 }}>{title}</div></div>
      </div>
      <div className="flex col gap-8">
        <div className="flex ac gap-8 muted" style={{ fontSize: 12.5 }}><Icon name="clock" size={14} /> {e.time}</div>
        <div className="flex ac gap-8 muted" style={{ fontSize: 12.5 }}><Icon name="map-pin" size={14} /> {loc}</div>
      </div>
      <Btn variant="ghost" size="sm" className="btn-block mt-12" iconR="arrow-right">{dim}</Btn>
    </div>
  );
}
const APPT_CATEGORIES = [
  { key: 'immigration', icon: 'shield', match: (e) => ['police', 'biometrics', 'ministry', 'immigration'].includes(e.key) },
  { key: 'medical', icon: 'stethoscope', match: (e) => ['medical', 'health', 'checkup'].includes(e.key) },
  { key: 'document', icon: 'file-text', match: (e) => ['document', 'signing', 'notary'].includes(e.key) },
  { key: 'personal', icon: 'user-round', match: (e) => ['custom', 'google', 'personal'].includes(e.key) },
  { key: 'other', icon: 'circle-dashed', match: () => true },
];

function apptCategoryOf(e) {
  if (e.category) return e.category;
  for (const c of APPT_CATEGORIES) if (c.match(e)) return c.key;
  return 'other';
}

function AppointmentsPage({ events, openModal }) {
  const { t, dict } = useT();
  const [view, setView] = useState('month');
  const [sel, setSel] = useState(9);
  const [filter, setFilter] = useState('all');
  const allRows = (events || CAL_EVENTS).map((e) => ({ ...e, category: apptCategoryOf(e) }));
  const rows = filter === 'all' ? allRows : allRows.filter((e) => e.category === filter);
  const evByDay = {};
  rows.forEach((e) => { (evByDay[e.d] = evByDay[e.d] || []).push(e); });
  const selEvents = evByDay[sel] || [];
  const chipStyle = (active) => ({
    display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 11px', borderRadius: 999,
    border: '1px solid ' + (active ? 'var(--brand-500)' : 'var(--line)'),
    background: active ? 'var(--brand-50)' : 'var(--surface)', color: active ? 'var(--brand-700)' : 'var(--ink-700)',
    fontSize: 12.5, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
  });
  const cells = [];
  for (let i = 0; i < FIRST_DOW; i++) cells.push(null);
  for (let d = 1; d <= DAYS_IN; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  const dow = (d) => dict.weekdays[(FIRST_DOW + d - 1) % 7];
  const titleOf = (e) => e.title || t('ev.' + e.key);
  const locOf = (e) => e.loc || t('ev.' + e.key + 'Loc');

  return (
    <>
      <PageHead title={t('nav.appointments')} sub={t('sub.appointments')}
        actions={<><Seg items={[{ value: 'month', label: t('c.month') }, { value: 'list', label: t('c.list') }]} value={view} onChange={setView} /><Btn variant="primary" icon="calendar-plus" onClick={() => openModal('calendarEvent')}>{t('c.schedule')}</Btn></>} />
      <div className="flex wrap gap-8" style={{ marginBottom: 16 }}>
        <button style={chipStyle(filter === 'all')} onClick={() => setFilter('all')}>{t('task.cat.all')}</button>
        {APPT_CATEGORIES.map((c) => (
          <button key={c.key} style={chipStyle(filter === c.key)} onClick={() => setFilter(c.key)}>
            <Icon name={c.icon} size={13} />{t('appt.cat.' + c.key)}
          </button>
        ))}
      </div>
      {view === 'month' ? (
        <div className="dash-grid">
          <div className="col-8">
            <Card>
              <div className="cal-head">
                <div className="flex ac gap-10"><IconBtn name="chevron-left" /><div className="h3" style={{ minWidth: 150 }}>{dict.months[MONTH_IDX]} 2026</div><IconBtn name="chevron-right" /></div>
                <div className="grow" />
                <Btn variant="ghost" size="sm" icon="dot" onClick={() => setSel(TODAY)}>{t('c.today')}</Btn>
              </div>
              <div className="cal-grid">{dict.weekdays.map((w, i) => <div className="cal-dow" key={i}>{w}</div>)}</div>
              <div className="cal-grid">
                {cells.map((d, i) => {
                  if (d === null) return <div className="cal-cell empty" key={i} />;
                  const evs = evByDay[d] || [];
                  return (
                    <div key={i} className={'cal-cell ' + (d === TODAY ? 'today ' : '') + (d === sel ? 'sel' : '')} onClick={() => setSel(d)}>
                      <div className="cal-num">{d}</div>
                      {evs.map((e, j) => <div key={j} className={'cal-ev ' + e.tone}><span className="ev-dot" /><span className="ev-time mono">{e.time}</span> {titleOf(e).split(' — ')[0]}</div>)}
                    </div>
                  );
                })}
              </div>
            </Card>
          </div>
          <div className="col-4">
            <Card style={{ height: '100%' }}>
              <CardHead icon="calendar-clock" title={dow(sel) + ' · ' + sel + ' ' + dict.months[MONTH_IDX]} sub={selEvents.length + ' ' + (selEvents.length === 1 ? t('appt.event') : t('appt.events'))} />
              <div className="card-bd">
                {selEvents.length === 0
                  ? <div className="flex col ac jc" style={{ padding: '34px 10px', textAlign: 'center', gap: 10 }}><div className="hd-ic" style={{ width: 44, height: 44, background: 'var(--surface-3)', color: 'var(--ink-400)' }}><Icon name="calendar-x" size={20} /></div><div className="muted" style={{ fontSize: 13 }}>{t('appt.noEvents')}</div></div>
                  : <div className="flex col gap-12">{selEvents.map((e, i) => <ApptDetail key={i} e={e} title={titleOf(e)} loc={locOf(e)} dim={t('c.details')} />)}</div>}
              </div>
            </Card>
          </div>
          <div className="col-12">
            <Card>
              <CardHead icon="list" title={t('appt.upcoming')} sub={t('appt.thisMonth')} />
              <div className="card-bd" style={{ paddingTop: 4, paddingBottom: 4 }}>
                <div className="rowlist">
                  {rows.map((e, i) => (
                    <div className="lrow pointer" key={i} onClick={() => setSel(e.d)}>
                      <div className="l-ic" style={evTone(e.tone)}><Icon name={e.ic} size={18} /></div>
                      <div className="l-bd"><div className="l-t">{titleOf(e)}</div><div className="l-s">{dow(e.d)} {e.d} {dict.months[MONTH_IDX]} · {e.time} · {locOf(e)}</div></div>
                      <Btn variant="ghost" size="sm">{t('c.details')}</Btn>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          </div>
        </div>
      ) : (
        <Card><div className="card-bd"><div className="rowlist">
          {rows.map((e, i) => (
            <div className="lrow" key={i}>
              <div className="l-ic" style={evTone(e.tone)}><Icon name={e.ic} size={18} /></div>
              <div className="l-bd"><div className="l-t">{titleOf(e)}</div><div className="l-s">{dow(e.d)} {e.d} {dict.months[MONTH_IDX]} · {e.time} · {locOf(e)}</div></div>
              <Btn variant="ghost" size="sm">{t('c.details')}</Btn>
            </div>
          ))}
        </div></div></Card>
      )}
    </>
  );
}

/* ===== TASKS ===== */
const TASK_CATEGORIES = [
  { key: 'immigration', icon: 'shield', tone: 'info' },
  { key: 'document', icon: 'file-text', tone: 'neut' },
  { key: 'finance', icon: 'receipt', tone: 'warn' },
  { key: 'appointment', icon: 'calendar', tone: 'info' },
  { key: 'admin', icon: 'briefcase', tone: 'neut' },
  { key: 'other', icon: 'circle-dashed', tone: 'neut' },
];

function taskCatMeta(key) {
  return TASK_CATEGORIES.find((c) => c.key === key) || TASK_CATEGORIES[TASK_CATEGORIES.length - 1];
}

function TasksPage({ tasks, openModal, onSync, syncState, onToggleTask, contact }) {
  const { t } = useT();
  const [filter, setFilter] = useState('all');
  const rows = (tasks || []).map((tk) => ({ ...tk, category: tk.category || 'other' }));
  const filtered = filter === 'all' ? rows : rows.filter((tk) => tk.category === filter);
  const chipStyle = (active) => ({
    display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 11px', borderRadius: 999,
    border: '1px solid ' + (active ? 'var(--brand-500)' : 'var(--line)'),
    background: active ? 'var(--brand-50)' : 'var(--surface)', color: active ? 'var(--brand-700)' : 'var(--ink-700)',
    fontSize: 12.5, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
  });
  return (
    <>
      <PageHead title={t('nav.tasks')} sub={t('sub.tasks')}
        actions={<Btn variant="ghost" icon="refresh-cw" onClick={onSync} disabled={syncState && syncState.syncing}>{syncState && syncState.syncing ? t('task.syncing') : t('task.syncGhl')}</Btn>} />
      {syncState && syncState.error && (
        <div className="alert warn" style={{ marginBottom: 14 }}>
          <div className="a-ic"><Icon name="alert-triangle" size={16} /></div>
          <div className="grow"><div className="a-t">{syncState.error}</div></div>
        </div>
      )}
      <div className="flex wrap gap-8" style={{ marginBottom: 16 }}>
        <button style={chipStyle(filter === 'all')} onClick={() => setFilter('all')}>{t('task.cat.all')}</button>
        {TASK_CATEGORIES.map((c) => (
          <button key={c.key} style={chipStyle(filter === c.key)} onClick={() => setFilter(c.key)}>
            <Icon name={c.icon} size={13} />{t('task.cat.' + c.key)}
          </button>
        ))}
      </div>
      <Card><div className="card-bd"><div className="rowlist">
        {filtered.length === 0 ? (
          <div className="lrow" style={{ borderBottom: 'none', justifyContent: 'center', padding: '24px 0', color: 'var(--ink-400)', fontSize: 13 }}>
            <Icon name="circle-check-big" size={16} />
            <span style={{ marginLeft: 8 }}>{t('task.empty')}</span>
          </div>
        ) : filtered.map((tk, i) => {
          const meta = taskCatMeta(tk.category);
          return (
            <div className="lrow" key={i}>
              <button className="icon-btn" onClick={() => onToggleTask && onToggleTask(tk)} style={{ width: 28, height: 28, color: tk.done ? 'var(--brand-500)' : 'var(--ink-300)' }}><Icon name={tk.done ? 'circle-check-big' : 'circle'} size={20} /></button>
              <div className="l-bd">
                <div className="l-t" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', color: tk.done ? 'var(--ink-400)' : 'var(--ink-900)' }}>
                  {tk.taskType && <Badge tone={tk.taskTypeTone}>{t(tk.taskTypeLabelKey)}</Badge>}
                  <span style={{ textDecoration: tk.done ? 'line-through' : 'none' }}>{tk.title || t(tk.tk)}</span>
                </div>
                <div className="l-s" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 2 }}>
                  <Icon name={meta.icon} size={12} />{t('task.cat.' + tk.category)}
                </div>
              </div>
              <div className="flex ac gap-8">
                <Badge tone={tk.tone} dot>{(tk.done ? t('c.done') : t('c.due')) + ' ' + tk.due}</Badge>
                {tk.taskType !== 'bilgi' && <Btn variant="ghost" size="sm" icon="paperclip" onClick={(e) => { e.stopPropagation(); openModal("taskAttachment", { task: tk, contact }); }}>{t("task.attach.btn")}</Btn>}
              </div>
            </div>
          );
        })}
      </div></div></Card>
    </>
  );
}

/* ===== REPORTS ===== */
function MiniBars() {
  const data = [40, 55, 48, 62, 70, 58, 75, 68, 82, 78, 90, 85];
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 96, padding: '0 2px' }}>
      {data.map((h, i) => (
        <div key={i} className="grow" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ width: '100%', height: h + '%', borderRadius: 6, background: i === data.length - 1 ? 'var(--brand-500)' : 'var(--brand-100)' }} />
          <span className="dim" style={{ fontSize: 9.5 }}>{i + 1}</span>
        </div>
      ))}
    </div>
  );
}
function ReportsPage() {
  const { t } = useT();
  return (
    <>
      <PageHead title={t('nav.reports')} sub={t('sub.reports')} actions={<Btn variant="ghost" icon="download">{t('c.exportPdf')}</Btn>} />
      <div className="grid g-12 mb-20" style={{ gap: 16 }}>
        <div className="col-3"><Stat icon="folder-check" value="92%" label={t('rep.completion')} trend="+8%" /></div>
        <div className="col-3"><Stat icon="clock" tone="blue" value="34d" label={t('rep.processing')} /></div>
        <div className="col-3"><Stat icon="shield-check" value="100%" label={t('rep.compliance')} /></div>
        <div className="col-3"><Stat icon="file-check-2" value="18" label={t('rep.docs')} /></div>
      </div>
      <Card><CardHead icon="chart-line" title={t('rep.activity')} sub={t('rep.last12')} /><div className="card-bd"><MiniBars /></div></Card>
    </>
  );
}

function SimplePage({ icon, title, sub }) {
  return (
    <div style={{ maxWidth: 520, margin: '8vh auto', textAlign: 'center' }}>
      <div className="hd-ic" style={{ width: 60, height: 60, margin: '0 auto 18px', borderRadius: 16 }}><Icon name={icon} size={28} /></div>
      <h1 className="h1" style={{ marginBottom: 8 }}>{title}</h1>
      <p className="muted">{sub}</p>
    </div>
  );
}

const AVATAR_EMOJIS = ['🙂', '😎', '🤩', '🥳', '🦸', '🧑‍💻', '🐱', '🐶', '🦊', '🐼', '🐨', '🐯', '🦁', '🌟', '⚡', '🚀', '🎯', '🌈', '🌵', '🍀', '☕', '🎨', '📚', '💼'];

function AvatarSection() {
  const { t } = useT();
  const [avatar, setAvatarState] = useState(() => (window.YEYE_AUTH.getAvatar && window.YEYE_AUTH.getAvatar()) || null);
  const [uploadErr, setUploadErr] = useState(null);

  const apply = (av) => { window.YEYE_AUTH.setAvatar(av); setAvatarState(av); setUploadErr(null); };

  const onFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (file.size > 400 * 1024) { setUploadErr(t('set.avatarTooLarge')); return; }
    const reader = new FileReader();
    reader.onload = () => apply({ type: 'image', value: reader.result });
    reader.onerror = () => setUploadErr(t('set.avatarReadFailed'));
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const preview = avatar && avatar.type === 'emoji'
    ? <div className="avatar a-lg" style={{ background: 'var(--brand-100)', color: 'var(--ink-900)', fontSize: 26, width: 60, height: 60 }}>{avatar.value}</div>
    : avatar && avatar.type === 'image'
      ? <img src={avatar.value} alt="" className="avatar a-lg" style={{ width: 60, height: 60, borderRadius: '50%', objectFit: 'cover' }} />
      : <Avatar size="lg" tone={{ bg: 'var(--brand-500)', fg: '#fff' }}>?</Avatar>;

  return (
    <Card>
      <CardHead icon="user" title={t('set.avatar')} sub={t('set.avatarSub')} />
      <div className="card-bd">
        <div className="flex ac gap-16" style={{ marginBottom: 18 }}>
          {preview}
          <div className="flex col gap-6">
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>{t('set.avatarCurrent')}</div>
            {avatar && <button className="btn btn-ghost btn-sm" onClick={() => apply(null)} style={{ alignSelf: 'flex-start' }}>{t('set.avatarRemove')}</button>}
          </div>
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 10 }}>{t('set.avatarPickEmoji')}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(48px, 1fr))', gap: 8, marginBottom: 18 }}>
          {AVATAR_EMOJIS.map((emo) => (
            <button key={emo} type="button" onClick={() => apply({ type: 'emoji', value: emo })}
              style={{
                aspectRatio: '1', border: '1px solid var(--line)', borderRadius: 12, background: avatar && avatar.value === emo ? 'var(--brand-100)' : 'var(--surface)',
                fontSize: 24, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{emo}</button>
          ))}
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 8 }}>{t('set.avatarUpload')}</div>
        <label className="btn btn-soft btn-sm" style={{ cursor: 'pointer', display: 'inline-flex' }}>
          <Icon name="upload" size={14} />{t('set.avatarUploadBtn')}
          <input type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
        </label>
        {uploadErr && <div className="alert bad" style={{ marginTop: 12 }}><div className="a-ic"><Icon name="alert-triangle" size={16} /></div><div className="grow"><div className="a-t">{uploadErr}</div></div></div>}
        <div className="dim" style={{ fontSize: 11, marginTop: 8 }}>{t('set.avatarUploadHint')}</div>
      </div>
    </Card>
  );
}

function SettingsPage() {
  const { t } = useT();
  const [current, setCurrent] = useState('');
  const [next, setNext] = useState('');
  const [confirm, setConfirm] = useState('');
  const [status, setStatus] = useState(null);
  const [busy, setBusy] = useState(false);

  const errText = (code) => {
    switch (code) {
      case 'wrong-current': return t('set.pwWrongCurrent');
      case 'too-short': return t('set.pwTooShort');
      case 'same-as-current': return t('set.pwSameAsCurrent');
      case 'mismatch': return t('set.pwMismatch');
      case 'not-signed-in': return t('set.pwNotSignedIn');
      default: return t('set.pwGeneric');
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    setStatus(null);
    if (next !== confirm) { setStatus({ ok: false, code: 'mismatch' }); return; }
    setBusy(true);
    try {
      const res = await window.YEYE_AUTH.changePassword(current, next);
      if (res && res.ok) {
        setStatus({ ok: true });
        setCurrent(''); setNext(''); setConfirm('');
      } else {
        setStatus({ ok: false, code: (res && res.code) || 'unknown' });
      }
    } catch (err) {
      setStatus({ ok: false, code: 'unknown' });
    } finally {
      setBusy(false);
    }
  };

  const fieldStyle = {
    height: 44, borderRadius: 10, border: '1px solid var(--line)',
    padding: '0 12px', fontSize: 14, background: 'var(--surface)',
    color: 'var(--ink-900)', outline: 'none',
  };

  return (
    <>
      <PageHead title={t('nav.settings')} sub={t('pg.settingsSub')} />
      <div style={{ maxWidth: 520, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <AvatarSection />
        <Card>
          <CardHead icon="lock" title={t('set.changePassword')} sub={t('set.changePasswordSub')} />
          <div className="card-bd">
            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-700)' }}>
                {t('set.currentPassword')}
                <input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} required autoComplete="current-password" style={fieldStyle} />
              </label>
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-700)' }}>
                {t('set.newPassword')}
                <input type="password" value={next} onChange={(e) => setNext(e.target.value)} required minLength={6} autoComplete="new-password" style={fieldStyle} />
              </label>
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-700)' }}>
                {t('set.confirmPassword')}
                <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required minLength={6} autoComplete="new-password" style={fieldStyle} />
              </label>
              {status && !status.ok && (
                <div className="alert bad" style={{ margin: 0 }}>
                  <div className="a-ic"><Icon name="alert-triangle" size={16} /></div>
                  <div className="grow"><div className="a-t">{errText(status.code)}</div></div>
                </div>
              )}
              {status && status.ok && (
                <div className="alert ok" style={{ margin: 0 }}>
                  <div className="a-ic"><Icon name="check" size={16} /></div>
                  <div className="grow"><div className="a-t">{t('set.pwUpdated')}</div></div>
                </div>
              )}
              <div>
                <Btn variant="primary" type="submit" disabled={busy}>{busy ? t('c.saving') : t('set.savePassword')}</Btn>
              </div>
            </form>
          </div>
        </Card>
      </div>
    </>
  );
}

Object.assign(window, {
  ServicesPage, PurchasedServicesPage, DocumentsPage, MessagesPage, InvoicesPage, SupportPage,
  FormSubmissionPage, CasesPage, AppointmentsPage, TasksPage, ReportsPage, SimplePage, SettingsPage, AvatarSection,
});
