/* MaiAgent Partner Portal — Orders & License Management */

const OrdersPage = ({ t, lang }) => {
  const [tab, setTab] = React.useState('orders');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [showForm, setShowForm] = React.useState(false);
  const [certTarget, setCertTarget] = React.useState(null);
  const [invoiceTarget, setInvoiceTarget] = React.useState(null);

  const STATUS_META = {
    pending:   { zh: '審核中', en: 'In review',  tone: 'amber' },
    approved:  { zh: '已通過', en: 'Approved',   tone: 'blue'  },
    fulfilled: { zh: '已交付', en: 'Fulfilled',  tone: 'green' },
    rejected:  { zh: '未通過', en: 'Rejected',   tone: 'red'   },
  };
  const LIC_META = {
    active:   { zh: '使用中',   en: 'Active',        tone: 'green' },
    expiring: { zh: '即將到期', en: 'Expiring soon', tone: 'amber' },
    expired:  { zh: '已到期',   en: 'Expired',       tone: 'red'   },
  };
  const TONE_STYLE = {
    green: { bg: '#DCFCE7', color: '#15803D', dot: '#22C55E' },
    amber: { bg: '#FEF9C3', color: '#A16207', dot: '#EAB308' },
    blue:  { bg: '#DBEAFE', color: '#1D4ED8', dot: '#3B82F6' },
    red:   { bg: '#FEE2E2', color: '#B91C1C', dot: '#EF4444' },
  };

  const StatusPill = ({ status, meta }) => {
    const s = meta[status]; if (!s) return null;
    const c = TONE_STYLE[s.tone];
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 999, background: c.bg, fontSize: 12, fontWeight: 600, color: c.color }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: c.dot, flexShrink: 0 }} />
        {lang === 'zh' ? s.zh : s.en}
      </span>
    );
  };

  const filteredOrders = statusFilter === 'all' ? ORDERS : ORDERS.filter(o => o.status === statusFilter);

  const statsOrders = {
    total:     ORDERS.length,
    pending:   ORDERS.filter(o => o.status === 'pending').length,
    fulfilled: ORDERS.filter(o => o.status === 'fulfilled').length,
  };
  const statsLic = {
    active:   LICENSES.filter(l => l.status === 'active').length,
    expiring: LICENSES.filter(l => l.status === 'expiring').length,
    total:    LICENSES.length,
  };

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-header__title">
          <div className="page-header__eyebrow">{lang === 'zh' ? '帳務' : 'Account'}</div>
          <h1>{t('orders.title')}</h1>
          <div className="page-header__sub">{t('orders.sub')}</div>
        </div>
        <Btn variant="primary" icon="plus" onClick={() => setShowForm(true)}>{t('orders.new')}</Btn>
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { icon: 'inbox',        label: lang === 'zh' ? '全部訂單'   : 'Total orders',    value: statsOrders.total },
          { icon: 'clock',        label: lang === 'zh' ? '審核中'     : 'Pending review',  value: statsOrders.pending,   warn: statsOrders.pending > 0 },
          { icon: 'check-circle', label: lang === 'zh' ? '已交付'     : 'Fulfilled',       value: statsOrders.fulfilled },
          { icon: 'shield',       label: lang === 'zh' ? '有效授權'   : 'Active licenses', value: `${statsLic.active} / ${statsLic.total}`, sub: statsLic.expiring > 0 ? (lang === 'zh' ? `${statsLic.expiring} 件即將到期` : `${statsLic.expiring} expiring soon`) : '' },
        ].map((k, i) => (
          <div key={i} style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, padding: '16px 18px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: k.warn ? '#FEF9C3' : '#F0F4FF', display: 'grid', placeItems: 'center' }}>
                <Icon name={k.icon} size={16} style={{ color: k.warn ? '#A16207' : 'var(--mai-blue)' }} />
              </div>
              <span style={{ fontSize: 12.5, color: 'var(--mai-fg-3)', fontWeight: 500 }}>{k.label}</span>
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: k.warn ? '#A16207' : 'var(--mai-fg)' }}>{k.value}</div>
            {k.sub && <div style={{ fontSize: 11.5, color: '#D97706', marginTop: 3 }}>{k.sub}</div>}
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 20, background: '#F4F6FF', padding: 4, borderRadius: 10, width: 'fit-content' }}>
        {[{ id: 'orders', label: t('orders.tab.orders') }, { id: 'licenses', label: t('orders.tab.licenses') }].map(tb => (
          <button key={tb.id} onClick={() => setTab(tb.id)}
            style={{ padding: '7px 18px', borderRadius: 8, border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 13, background: tab === tb.id ? 'white' : 'transparent', color: tab === tb.id ? 'var(--mai-fg)' : 'var(--mai-fg-3)', boxShadow: tab === tb.id ? '0 1px 4px rgba(0,0,0,0.1)' : 'none', transition: 'all 0.15s' }}>
            {tb.label}
          </button>
        ))}
      </div>

      {tab === 'orders' && (
        <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
          {/* Filter bar */}
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--mai-border)', display: 'flex', gap: 8, alignItems: 'center' }}>
            <Icon name="filter" size={14} style={{ color: 'var(--mai-fg-3)' }} />
            {['all', 'pending', 'approved', 'fulfilled', 'rejected'].map(s => (
              <button key={s} onClick={() => setStatusFilter(s)}
                style={{ padding: '4px 12px', borderRadius: 999, border: '1px solid ' + (statusFilter === s ? 'var(--mai-blue)' : 'var(--mai-border)'), background: statusFilter === s ? '#EEF2FF' : 'white', color: statusFilter === s ? 'var(--mai-blue)' : 'var(--mai-fg-3)', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
                {s === 'all' ? (lang === 'zh' ? '全部' : 'All') : (lang === 'zh' ? STATUS_META[s].zh : STATUS_META[s].en)}
              </button>
            ))}
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#F8F9FF' }}>
                {[t('orders.col.id'), t('orders.col.customer'), t('orders.col.product'), lang === 'zh' ? '組織 ID' : 'Org ID', t('orders.col.amount'), lang === 'zh' ? '授權期間' : 'License Period', t('orders.col.status'), ''].map((h, i) => (
                  <th key={i} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 12, fontWeight: 700, color: 'var(--mai-fg-3)', borderBottom: '1px solid var(--mai-border)', whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filteredOrders.map((o) => (
                <tr key={o.id} style={{ borderBottom: '1px solid #F1F3FA' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#FAFBFF'}
                  onMouseLeave={e => e.currentTarget.style.background = ''}>
                  <td style={{ padding: '12px 16px', fontSize: 12.5, fontWeight: 700, color: 'var(--mai-blue)', fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap' }}>{o.id}</td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--mai-fg)' }}>{o.endUser[lang]}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--mai-fg-3)', marginTop: 1 }}>{o.rep[lang]}</div>
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: 12.5, color: 'var(--mai-fg-2)' }}>{o.product}</td>
                  <td style={{ padding: '12px 16px', fontSize: 12, fontFamily: 'ui-monospace, monospace', color: o.orgId ? 'var(--mai-fg-2)' : 'var(--mai-fg-3)' }}>{o.orgId || '—'}</td>
                  <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: 'var(--mai-fg)', whiteSpace: 'nowrap' }}>NT$ {(o.amount / 10000).toFixed(0)}萬</td>
                  <td style={{ padding: '12px 16px', fontSize: 12, color: 'var(--mai-fg-3)', whiteSpace: 'nowrap' }}>
                    {o.startDate ? `${o.startDate} ~ ${o.endDate}` : '—'}
                  </td>
                  <td style={{ padding: '12px 16px' }}><StatusPill status={o.status} meta={STATUS_META} /></td>
                  <td style={{ padding: '12px 16px' }}>
                    {o.status === 'fulfilled' && (
                      <div style={{ display: 'flex', gap: 6 }}>
                        <Btn variant="ghost" size="sm" icon="file-text" onClick={() => setCertTarget(o)}>
                          {lang === 'zh' ? '授權書' : 'License Cert'}
                        </Btn>
                        {o.invoice && (
                          <Btn variant="ghost" size="sm" icon="tag" onClick={() => setInvoiceTarget(o)}>
                            {lang === 'zh' ? '發票' : 'Invoice'}
                          </Btn>
                        )}
                      </div>
                    )}
                    {o.note && (
                      <div style={{ fontSize: 11.5, color: '#B45309', marginTop: 4 }}>⚠ {o.note[lang]}</div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filteredOrders.length === 0 && (
            <div style={{ padding: '40px', textAlign: 'center', color: 'var(--mai-fg-3)', fontSize: 13 }}>
              {lang === 'zh' ? '目前沒有符合條件的訂單' : 'No orders match the selected filter'}
            </div>
          )}
        </div>
      )}

      {tab === 'licenses' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {statsLic.expiring > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 18px', background: '#FEF9C3', border: '1px solid #FDE68A', borderRadius: 12 }}>
              <Icon name="alert" size={16} style={{ color: '#A16207', flexShrink: 0 }} />
              <span style={{ fontSize: 13, color: '#92400E', fontWeight: 600 }}>
                {lang === 'zh'
                  ? `${statsLic.expiring} 份授權即將在 30 天內到期，請盡早聯繫客戶洽談續約。`
                  : `${statsLic.expiring} license(s) expiring within 30 days — contact customers to arrange renewal.`}
              </span>
            </div>
          )}
          <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ background: '#F8F9FF' }}>
                  {[t('orders.lic.col.customer'), t('orders.lic.col.product'), 'Org ID', t('orders.lic.col.usage'), t('orders.lic.col.start'), t('orders.lic.col.expiry'), ''].map((h, i) => (
                    <th key={i} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 12, fontWeight: 700, color: 'var(--mai-fg-3)', borderBottom: '1px solid var(--mai-border)', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {LICENSES.map((lic) => {
                  const m = LIC_META[lic.status];
                  const c = TONE_STYLE[m.tone];
                  const daysLeft = Math.max(0, Math.round((new Date(lic.expiry) - new Date()) / 86400000));
                  return (
                    <tr key={lic.id} style={{ borderBottom: '1px solid #F1F3FA' }}
                      onMouseEnter={e => e.currentTarget.style.background = '#FAFBFF'}
                      onMouseLeave={e => e.currentTarget.style.background = ''}>
                      <td style={{ padding: '12px 16px' }}>
                        <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--mai-fg)' }}>{lic.customer[lang]}</div>
                        {lic.isNfr && <span style={{ fontSize: 11, fontWeight: 700, color: '#C49A00', background: '#FFFDE7', padding: '1px 6px', borderRadius: 4, marginTop: 2, display: 'inline-block' }}>NFR</span>}
                      </td>
                      <td style={{ padding: '12px 16px', fontSize: 12.5, color: 'var(--mai-fg-2)' }}>{lic.product}</td>
                      <td style={{ padding: '12px 16px', fontSize: 12, fontFamily: 'ui-monospace, monospace', color: 'var(--mai-fg-3)' }}>{lic.orgId}</td>
                      <td style={{ padding: '12px 16px', minWidth: 120 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <div style={{ flex: 1, height: 6, background: '#EEF2FF', borderRadius: 999, overflow: 'hidden' }}>
                            <div style={{ height: '100%', borderRadius: 999, width: lic.usageRate + '%', background: lic.usageRate >= 90 ? '#EF4444' : lic.usageRate >= 70 ? '#F59E0B' : '#22C55E' }} />
                          </div>
                          <span style={{ fontSize: 11.5, color: 'var(--mai-fg-3)', minWidth: 30, textAlign: 'right' }}>{lic.usageRate}%</span>
                        </div>
                      </td>
                      <td style={{ padding: '12px 16px', fontSize: 12.5, color: 'var(--mai-fg-3)' }}>{lic.start}</td>
                      <td style={{ padding: '12px 16px' }}>
                        <div style={{ fontSize: 12.5, color: lic.status === 'expired' ? '#B91C1C' : 'var(--mai-fg-2)', fontWeight: lic.status !== 'active' ? 700 : 400 }}>{lic.expiry}</div>
                        {lic.status !== 'expired' && <div style={{ fontSize: 11, color: lic.status === 'expiring' ? '#D97706' : 'var(--mai-fg-3)', marginTop: 2 }}>{lang === 'zh' ? `剩 ${daysLeft} 天` : `${daysLeft}d left`}</div>}
                      </td>
                      <td style={{ padding: '12px 16px' }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 999, background: c.bg, fontSize: 12, fontWeight: 600, color: c.color }}>
                          <span style={{ width: 6, height: 6, borderRadius: '50%', background: c.dot }} />
                          {lang === 'zh' ? m.zh : m.en}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {showForm  && <NewOrderModal  t={t} lang={lang} onClose={() => setShowForm(false)} />}
      {certTarget   && <LicenseCertModal order={certTarget}   lang={lang} onClose={() => setCertTarget(null)} />}
      {invoiceTarget && <InvoiceModal    order={invoiceTarget} lang={lang} onClose={() => setInvoiceTarget(null)} />}
    </div>
  );
};

/* ── New Order Modal ── */
const NewOrderModal = ({ t, lang, onClose }) => {
  const [form, setForm] = React.useState({
    dealId: '', orgId: '',
    endUser: '', rep: '', address: '',
    product: '', startDate: '', endDate: '',
    amount: '', note: '',
  });
  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const PRODUCTS = [
    'MaiAgent SaaS 輕量版',
    'MaiAgent SaaS 標準版',
    'MaiAgent SaaS 商業版',
    'MaiAgent SaaS 旗艦企業版',
    'MaiAgent SaaS POC（Pro 方案）',
    'MaiAgent SaaS POC（Enterprise 方案）',
    'MaiAgent 私有部署訂閱版',
    'MaiAgent 私有部署買斷授權',
    'MaiAgent GB10（MaiGPT）',
    'MaiAgent GB10（Agent Builder）',
    'MaiAgent Web Chat',
  ];

  const Field = ({ label, children, required }) => (
    <div>
      <label style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--mai-fg-2)', display: 'block', marginBottom: 6 }}>
        {label}{required && <span style={{ color: '#EF4444', marginLeft: 2 }}>*</span>}
      </label>
      {children}
    </div>
  );

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 560, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column', maxHeight: '90vh' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{t('orders.form.title')}</div>
          <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--mai-fg-3)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={18} /></button>
        </div>

        <div style={{ padding: '20px 24px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Section: 案件資訊 */}
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--mai-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: '1px solid #F1F3FA', paddingBottom: 6 }}>
            {lang === 'zh' ? '案件資訊' : 'Deal Info'}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label={lang === 'zh' ? '關聯案件編號' : 'Related Deal ID'}>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box', fontFamily: 'ui-monospace,monospace', fontSize: 12.5 }} placeholder="DR-2026-XXXX" value={form.dealId} onChange={set('dealId')} />
            </Field>
            <Field label={lang === 'zh' ? '組織 ID' : 'Organization ID'} required>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box', fontFamily: 'ui-monospace,monospace', fontSize: 12.5 }} placeholder="ORG-XXXX" value={form.orgId} onChange={set('orgId')} />
            </Field>
          </div>

          {/* Section: 終端使用者 */}
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--mai-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: '1px solid #F1F3FA', paddingBottom: 6, marginTop: 4 }}>
            {lang === 'zh' ? '終端使用者資訊' : 'End User Info'}
          </div>
          <Field label={lang === 'zh' ? '使用客戶公司名稱（正式抬頭）' : 'End User Company (legal name)'} required>
            <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} placeholder={lang === 'zh' ? '例：永豐金證券股份有限公司' : 'e.g. SinoPac Securities Co., Ltd.'} value={form.endUser} onChange={set('endUser')} />
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label={lang === 'zh' ? '負責人姓名' : 'Representative'}>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} placeholder={lang === 'zh' ? '姓名' : 'Name'} value={form.rep} onChange={set('rep')} />
            </Field>
            <Field label={lang === 'zh' ? '公司地址' : 'Address'}>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} placeholder={lang === 'zh' ? '縣市區路號' : 'City, district, street'} value={form.address} onChange={set('address')} />
            </Field>
          </div>

          {/* Section: 授權內容 */}
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--mai-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: '1px solid #F1F3FA', paddingBottom: 6, marginTop: 4 }}>
            {lang === 'zh' ? '授權內容' : 'License Details'}
          </div>
          <Field label={lang === 'zh' ? '產品 / 方案' : 'Product / Plan'} required>
            <select className="input" style={{ width: '100%' }} value={form.product} onChange={set('product')}>
              <option value="">{lang === 'zh' ? '請選擇產品' : 'Select a product'}</option>
              {PRODUCTS.map(p => <option key={p} value={p}>{p}</option>)}
            </select>
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label={lang === 'zh' ? '授權起始日' : 'Start date'} required>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} type="date" value={form.startDate} onChange={set('startDate')} />
            </Field>
            <Field label={lang === 'zh' ? '授權結束日' : 'End date'} required>
              <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} type="date" value={form.endDate} onChange={set('endDate')} />
            </Field>
          </div>
          <Field label={lang === 'zh' ? '金額 (TWD)' : 'Amount (TWD)'}>
            <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} type="number" min="0" placeholder="3200000" value={form.amount} onChange={set('amount')} />
          </Field>
          <Field label={lang === 'zh' ? '備註' : 'Notes'}>
            <textarea className="input" rows={2} style={{ width: '100%', resize: 'vertical', boxSizing: 'border-box' }} value={form.note} onChange={set('note')} />
          </Field>
        </div>

        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--mai-border)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <Btn variant="ghost" onClick={onClose}>{t('common.cancel')}</Btn>
          <Btn variant="primary" icon="check" onClick={onClose}>{t('orders.form.submit')}</Btn>
        </div>
      </div>
    </div>
  );
};

/* ── License Certificate Modal ── */
const LicenseCertModal = ({ order, lang, onClose }) => {
  const issueDate = order.fulfilled || new Date().toISOString().slice(0, 10);
  const [issueY, issueM, issueD] = issueDate.split('-');

  // Parse start/end dates into 年月日
  const parseDateParts = (d) => {
    if (!d) return { y: '', m: '', day: '' };
    const [y, m, day] = d.split('-');
    return { y, m, day };
  };
  const s = parseDateParts(order.startDate);
  const e = parseDateParts(order.endDate);

  const LEGAL = '本項授權係為非專屬性，不可轉讓之授權。甲方除依使用本【授權軟體】時所接受之授權條件為權力行使外，於未經乙方事前之書面同意，不得自行或使第三人就【授權軟體】為其他方式之使用、重置、修改、讓與、散佈、及銷售等，甲方亦不得對軟體進行逆向工程、反編譯或試圖獲取程式原始碼。甲方違反上述之規定者，乙方將依法追訴並請求損害賠償。若因本合約未能履行或履行不完全所生之爭議，雙方同意本誠信原則協商之，本合約如需涉訟，雙方同意以台灣台北地方法院為第一審管轄法院。';

  // CSS for the document — scoped inside the modal
  const docStyle = {
    fontFamily: "'Noto Serif TC', '思源宋體', 'Source Han Serif TC', 'PMingLiU', 'serif'",
    fontSize: 14,
    color: '#1a1a1a',
    lineHeight: 1.8,
    background: 'white',
    padding: '52px 64px 48px',
  };

  const Underline = ({ value, minWidth = 220 }) => (
    <span style={{ display: 'inline-block', minWidth, borderBottom: '1px solid #333', paddingBottom: 1, verticalAlign: 'bottom', fontWeight: value ? 600 : 400, color: value ? '#1a1a1a' : 'transparent' }}>
      {value || ' '}
    </span>
  );

  // The company seal — replicated in CSS from PDF
  const Seal = () => (
    <div style={{ position: 'relative', width: 80, height: 80, marginTop: 14 }}>
      {/* outer ring */}
      <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2.5px solid #C00', opacity: 0.85 }} />
      {/* inner ring */}
      <div style={{ position: 'absolute', inset: 6, borderRadius: '50%', border: '1.5px solid #C00', opacity: 0.85 }} />
      {/* text arranged in a circle */}
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1 }}>
        <div style={{ fontSize: 7.5, fontWeight: 900, color: '#C00', letterSpacing: '0.05em', textAlign: 'center', lineHeight: 1.4 }}>思邁智能</div>
        <div style={{ fontSize: 6.5, fontWeight: 800, color: '#C00', letterSpacing: '0.02em', textAlign: 'center', lineHeight: 1.4 }}>股份有限公司</div>
        <div style={{ fontSize: 6,   fontWeight: 800, color: '#C00', letterSpacing: '0.05em', textAlign: 'center', lineHeight: 1.4 }}>專用章</div>
      </div>
    </div>
  );

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: '20px' }}>
      <div style={{ background: '#e8e8e8', borderRadius: 12, width: '100%', maxWidth: 740, boxShadow: '0 28px 80px rgba(0,0,0,0.35)', display: 'flex', flexDirection: 'column', maxHeight: '96vh' }}>

        {/* Toolbar */}
        <div style={{ padding: '12px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#555' }}>
            {order.id} · {lang === 'zh' ? '軟體授權暨履約證明書' : 'Software License Certificate'}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="ghost" size="sm" icon="download">{lang === 'zh' ? '下載 PDF' : 'Download PDF'}</Btn>
            <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#555', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16} /></button>
          </div>
        </div>

        {/* Paper */}
        <div style={{ overflowY: 'auto', padding: '0 24px 24px' }}>
          <div style={{ ...docStyle, boxShadow: '0 2px 16px rgba(0,0,0,0.18)', minHeight: 600 }}>

            {/* Logo */}
            <div style={{ marginBottom: 40 }}>
              <img src="assets/maiagent-logo.png" alt="MaiAgent" style={{ height: 36, display: 'block' }} />
            </div>

            {/* Title */}
            <div style={{ textAlign: 'center', fontSize: 22, fontWeight: 900, letterSpacing: '0.06em', marginBottom: 44, fontFamily: 'sans-serif', color: '#111' }}>
              軟體授權暨履約證明書
            </div>

            {/* Parties */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18, marginBottom: 32 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span style={{ minWidth: 72 }}>使用客戶 ：</span>
                <Underline value={order.endUser[lang] || order.customer[lang]} minWidth={260} />
                <span style={{ marginLeft: 10, fontSize: 13 }}>（以下簡稱甲方）</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span style={{ minWidth: 72 }}>授權廠商 ：</span>
                <Underline value="思邁智能股份有限公司" minWidth={200} />
                <span style={{ marginLeft: 10, fontSize: 13 }}>（以下簡稱乙方）</span>
              </div>
            </div>

            {/* Numbered items */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 32 }}>

              {/* 1 */}
              <div style={{ display: 'flex', gap: 6 }}>
                <span style={{ minWidth: 22, fontWeight: 600 }}>1.</span>
                <div>
                  授權軟體產品名稱：<strong>{order.product}</strong>
                </div>
              </div>

              {/* 2 */}
              <div style={{ display: 'flex', gap: 6 }}>
                <span style={{ minWidth: 22, fontWeight: 600 }}>2.</span>
                <div>
                  授權日期與保固：
                  <Underline value={s.y} minWidth={40} />年
                  <Underline value={s.m} minWidth={24} />月
                  <Underline value={s.day} minWidth={24} />日　至
                  <Underline value={e.y} minWidth={40} />年
                  <Underline value={e.m} minWidth={24} />月
                  <Underline value={e.day} minWidth={24} />日，提供保固。乙方同意於保固期內提供【授權軟體】故障排除服務。
                </div>
              </div>

              {/* 3 */}
              <div style={{ display: 'flex', gap: 6 }}>
                <span style={{ minWidth: 22, fontWeight: 600 }}>3.</span>
                <div>
                  <div>授權範圍、禁止事項：</div>
                  <div style={{ paddingLeft: 28, marginTop: 6, fontSize: 13.5, textAlign: 'justify', lineHeight: 2 }}>
                    {LEGAL}
                  </div>
                </div>
              </div>

            </div>

            {/* Signature table */}
            <table style={{ width: '100%', borderCollapse: 'collapse', border: '1.5px solid #333', marginBottom: 32 }}>
              <tbody>
                <tr>
                  {/* Left — MaiAgent */}
                  <td style={{ width: '50%', padding: '16px 20px', borderRight: '1.5px solid #333', verticalAlign: 'top' }}>
                    <div style={{ lineHeight: 2.2, fontSize: 13.5 }}>
                      <div>授權人：思邁智能股份有限公司</div>
                      <div>負責人：張介騰</div>
                      <div>地址：台北市大安區光復南路438號11樓</div>
                    </div>
                    <Seal />
                  </td>
                  {/* Right — client */}
                  <td style={{ width: '50%', padding: '16px 20px', verticalAlign: 'top' }}>
                    <div style={{ lineHeight: 2.4, fontSize: 13.5 }}>
                      <div style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
                        <span style={{ flexShrink: 0 }}>使用者(公司名稱)：</span>
                        <span style={{ flex: 1, borderBottom: '1px solid #555', minWidth: 60, color: order.endUser ? '#1a1a1a' : 'transparent' }}>{order.endUser ? order.endUser[lang] : ' '}</span>
                      </div>
                      <div style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
                        <span style={{ flexShrink: 0 }}>負責人：</span>
                        <span style={{ flex: 1, borderBottom: '1px solid #555', minWidth: 80, color: order.rep ? '#1a1a1a' : 'transparent' }}>{order.rep ? order.rep[lang] : ' '}</span>
                      </div>
                      <div style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
                        <span style={{ flexShrink: 0 }}>地址：</span>
                        <span style={{ flex: 1, borderBottom: '1px solid #555', minWidth: 80, color: order.address ? '#1a1a1a' : 'transparent' }}>{order.address ? order.address[lang] : ' '}</span>
                      </div>
                    </div>
                    <div style={{ marginTop: 20, fontSize: 12.5, color: '#888', textAlign: 'center', paddingTop: 10, borderTop: '1px dashed #ccc' }}>
                      請加蓋發票章、收發章或其他公司印鑑
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            {/* Issue date */}
            <div style={{ textAlign: 'center', fontSize: 14.5, letterSpacing: '0.15em', color: '#222' }}>
              西元&emsp;<strong>{issueY}</strong>&emsp;年&emsp;<strong>{issueM}</strong>&emsp;月&emsp;<strong>{issueD}</strong>&emsp;日
            </div>

          </div>
        </div>
      </div>
    </div>
  );
};

/* ── Invoice Modal ── */
const InvoiceModal = ({ order, lang, onClose }) => {
  const inv = order.invoice;
  const [issueY, issueM, issueD] = inv.issuedAt.split('-');

  const preTax  = Math.round(order.amount / 1.05);
  const taxAmt  = order.amount - preTax;

  const SELLER = {
    name: '思邁智能股份有限公司',
    taxId: '52521009',
    address: '台北市大安區光復南路 438 號 11 樓',
  };

  const Row = ({ label, value, mono, bold }) => (
    <div style={{ display: 'flex', alignItems: 'baseline', padding: '7px 0', borderBottom: '1px solid #F1F3FA' }}>
      <span style={{ minWidth: 140, fontSize: 12.5, color: 'var(--mai-fg-3)', flexShrink: 0 }}>{label}</span>
      <span style={{ fontSize: 13, color: 'var(--mai-fg)', fontWeight: bold ? 700 : 500, fontFamily: mono ? 'ui-monospace, monospace' : 'inherit' }}>{value}</span>
    </div>
  );

  const fmtN = (n) => Math.round(n).toLocaleString();

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}>
      <div style={{ background: '#e8e8e8', borderRadius: 12, width: '100%', maxWidth: 680, boxShadow: '0 28px 80px rgba(0,0,0,0.35)', display: 'flex', flexDirection: 'column', maxHeight: '96vh' }}>

        {/* Toolbar */}
        <div style={{ padding: '12px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#555' }}>
            {inv.no} · {lang === 'zh' ? '統一發票' : 'Tax Invoice'}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="ghost" size="sm" icon="download">{lang === 'zh' ? '下載 PDF' : 'Download PDF'}</Btn>
            <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#555', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16} /></button>
          </div>
        </div>

        {/* Paper */}
        <div style={{ overflowY: 'auto', padding: '0 24px 24px' }}>
          <div style={{ background: 'white', boxShadow: '0 2px 16px rgba(0,0,0,0.18)', padding: '40px 48px' }}>

            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 32 }}>
              <div>
                <img src="assets/maiagent-logo.png" alt="MaiAgent" style={{ height: 32, display: 'block', marginBottom: 10 }} />
                <div style={{ fontSize: 12, color: '#666', lineHeight: 1.8 }}>
                  <div>{SELLER.address}</div>
                  <div>{lang === 'zh' ? '統一編號' : 'Tax ID'}：{SELLER.taxId}</div>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 22, fontWeight: 900, letterSpacing: '0.04em', color: '#111', marginBottom: 8 }}>
                  {lang === 'zh' ? '統一發票' : 'TAX INVOICE'}
                </div>
                <div style={{ fontSize: 13, color: '#555', lineHeight: 2 }}>
                  <div>{lang === 'zh' ? '發票號碼' : 'Invoice No.'}&emsp;<strong style={{ fontFamily: 'ui-monospace,monospace', fontSize: 14, color: '#111' }}>{inv.no}</strong></div>
                  <div>{lang === 'zh' ? '開立日期' : 'Issue Date'}&emsp;<strong>{issueY}{lang === 'zh' ? ' 年 ' : '-'}{issueM}{lang === 'zh' ? ' 月 ' : '-'}{issueD}{lang === 'zh' ? ' 日' : ''}</strong></div>
                </div>
              </div>
            </div>

            {/* Parties */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, border: '1.5px solid #333', marginBottom: 28 }}>
              {/* Seller */}
              <div style={{ padding: '14px 18px', borderRight: '1px solid #ddd' }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#888', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>{lang === 'zh' ? '賣方（乙方）' : 'SELLER'}</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#111', marginBottom: 4 }}>{SELLER.name}</div>
                <div style={{ fontSize: 12, color: '#555', lineHeight: 1.7 }}>
                  <div>{lang === 'zh' ? '統一編號' : 'Tax ID'}：{SELLER.taxId}</div>
                  <div>{SELLER.address}</div>
                </div>
              </div>
              {/* Buyer */}
              <div style={{ padding: '14px 18px' }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#888', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>{lang === 'zh' ? '買受人（甲方）' : 'BUYER'}</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#111', marginBottom: 4 }}>{order.endUser[lang]}</div>
                <div style={{ fontSize: 12, color: '#555', lineHeight: 1.7 }}>
                  <div>{lang === 'zh' ? '統一編號' : 'Tax ID'}：{inv.buyerTaxId}</div>
                  <div>{order.address[lang]}</div>
                </div>
              </div>
            </div>

            {/* Line items table */}
            <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 20, fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#F8F9FF', borderTop: '1.5px solid #333', borderBottom: '1px solid #ddd' }}>
                  <th style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 700, color: '#555', fontSize: 12 }}>{lang === 'zh' ? '品名 / 服務說明' : 'Description'}</th>
                  <th style={{ padding: '9px 14px', textAlign: 'right', fontWeight: 700, color: '#555', fontSize: 12 }}>{lang === 'zh' ? '未稅金額 (TWD)' : 'Amount (excl. tax)'}</th>
                </tr>
              </thead>
              <tbody>
                <tr style={{ borderBottom: '1px solid #F1F3FA' }}>
                  <td style={{ padding: '12px 14px' }}>
                    <div style={{ fontWeight: 600 }}>{order.product}</div>
                    <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>
                      {lang === 'zh' ? '授權期間' : 'License period'}：{order.startDate} ～ {order.endDate}
                    </div>
                    <div style={{ fontSize: 12, color: '#888' }}>Org ID：{order.orgId}</div>
                  </td>
                  <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'ui-monospace, monospace' }}>
                    {fmtN(preTax)}
                  </td>
                </tr>
              </tbody>
            </table>

            {/* Totals */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 32 }}>
              <div style={{ minWidth: 240 }}>
                <Row label={lang === 'zh' ? '小計（未稅）' : 'Subtotal (excl. tax)'} value={`NT$ ${fmtN(preTax)}`} mono />
                <Row label={lang === 'zh' ? '營業稅（5%）' : 'VAT (5%)'} value={`NT$ ${fmtN(taxAmt)}`} mono />
                <div style={{ display: 'flex', alignItems: 'baseline', padding: '10px 0', borderTop: '2px solid #222', marginTop: 4 }}>
                  <span style={{ minWidth: 140, fontSize: 13.5, fontWeight: 700, color: '#111', flexShrink: 0 }}>{lang === 'zh' ? '含稅總計' : 'Total (incl. VAT)'}</span>
                  <span style={{ fontSize: 17, fontWeight: 900, color: '#111', fontFamily: 'ui-monospace, monospace' }}>NT$ {fmtN(order.amount)}</span>
                </div>
              </div>
            </div>

            {/* Footer note */}
            <div style={{ borderTop: '1px solid #E5E7EB', paddingTop: 14, fontSize: 11.5, color: '#999', lineHeight: 1.8 }}>
              <div>{lang === 'zh' ? '本發票依中華民國統一發票使用辦法開立。如有疑問，請聯繫財務部門。' : 'This invoice is issued in accordance with applicable tax regulations. For queries, please contact our finance team.'}</div>
              <div>{lang === 'zh' ? '付款條件：' : 'Payment terms: '}NT$ {fmtN(order.amount)} — {order.startDate}</div>
            </div>

          </div>
        </div>
      </div>
    </div>
  );
};

window.OrdersPage = OrdersPage;
