/* Compliance Document Library */

const CERTS = [
  {
    id: 'iso27001', name: 'ISO 27001:2022', dot: '#1d4ed8', dotBg: '#eff6ff',
    zh: { desc: '資訊安全管理系統（ISMS）國際認證，覆蓋 MaiAgent 雲端平台所有資料處理範疇，每三年換發、每年監督審查。', scope: '全球', until: '2026-11-30' },
    en: { desc: 'International Information Security Management System (ISMS) certification covering all MaiAgent cloud data processing. Renewed every 3 years with annual surveillance audits.', scope: 'Global', until: '2026-11-30' },
  },
  {
    id: 'iso27701', name: 'ISO 27701:2019', dot: '#7c3aed', dotBg: '#f5f3ff',
    zh: { desc: '隱私資訊管理系統（PIMS）國際認證，作為 ISO 27001 的隱私延伸，確保個人資料處理符合 GDPR / 台灣個資法等隱私法規要求。', scope: '全球', until: '2026-11-30' },
    en: { desc: 'Privacy Information Management System (PIMS) certification extending ISO 27001 — ensures personal data processing meets GDPR, Taiwan PDPA, and other privacy regulation requirements.', scope: 'Global', until: '2026-11-30' },
  },
];

const DOCS = [
  { id: 'd1', cat: 'iso27001', fmt: 'PDF',  size: '1.1 MB', updated: '2023-12-01',
    zh: { title: 'ISO 27001:2022 認證書（掃描版）', desc: 'SGS 台灣核發，有效期至 2026-11-30，可附於客戶採購投標文件中。' },
    en: { title: 'ISO 27001:2022 Certificate (Scanned)', desc: 'Issued by SGS Taiwan, valid until 2026-11-30. Suitable for customer procurement submissions.' } },
  { id: 'd2', cat: 'iso27701', fmt: 'PDF',  size: '980 KB', updated: '2023-12-01',
    zh: { title: 'ISO 27701:2019 認證書（掃描版）', desc: 'SGS 台灣核發，有效期至 2026-11-30，隱私資訊管理系統認證，適合需要隱私合規佐證的客戶需求。' },
    en: { title: 'ISO 27701:2019 Certificate (Scanned)', desc: 'Issued by SGS Taiwan, valid until 2026-11-30. Privacy Information Management System certification for privacy compliance requirements.' } },
  { id: 'd3', cat: 'security', fmt: 'PDF',  size: '2.4 MB', updated: '2026-05-01',
    zh: { title: 'MaiAgent 資安白皮書', desc: '詳述平台架構、加密機制（AES-256、TLS 1.3）、存取控制、災備計畫與漏洞揭露政策。' },
    en: { title: 'MaiAgent Security Whitepaper', desc: 'Covers platform architecture, encryption (AES-256, TLS 1.3), access controls, disaster recovery, and vulnerability disclosure.' } },
  { id: 'd4', cat: 'security', fmt: 'PDF',  size: '340 KB', updated: '2026-03-05',
    zh: { title: '滲透測試報告摘要（2026 Q1）', desc: '第三方滲透測試結果摘要，無高危漏洞，已於 2026-02-28 完成全部修補。' },
    en: { title: 'Penetration Test Report Summary (2026 Q1)', desc: 'Third-party pen test summary — no critical vulnerabilities, all findings remediated by 2026-02-28.' } },
  { id: 'd5', cat: 'security', fmt: 'XLSX', size: '84 KB', updated: '2026-04-10',
    zh: { title: '資安問卷填答範本（企業採購用）', desc: '預填 MaiAgent 資安基本資料，可加速客戶 IT 部門的廠商評估流程。' },
    en: { title: 'Security Questionnaire Pre-filled Template', desc: 'Pre-filled MaiAgent security details to accelerate customer IT vendor assessments.' } },
];

const FMT_STYLE = {
  PDF:  { color: '#ef4444', bg: '#fef2f2' },
  DOCX: { color: '#2563eb', bg: '#eff6ff' },
  XLSX: { color: '#059669', bg: '#ecfdf5' },
};

const CAT_KEYS = {
  all:      { zh: '全部',          en: 'All' },
  iso27001: { zh: 'ISO 27001',     en: 'ISO 27001' },
  iso27701: { zh: 'ISO 27701',     en: 'ISO 27701' },
  security: { zh: '資安文件',      en: 'Security Docs' },
};

const CompliancePage = ({ t, lang }) => {
  const isZh = lang === 'zh';
  const [catFilter, setCatFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [downloaded, setDownloaded] = React.useState({});

  const filtered = DOCS.filter(d => {
    const info = isZh ? d.zh : d.en;
    const matchCat = catFilter === 'all' || d.cat === catFilter;
    const matchSearch = !search || info.title.toLowerCase().includes(search.toLowerCase()) || info.desc.toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSearch;
  });

  function handleDownload(id) {
    setDownloaded(v => ({ ...v, [id]: true }));
  }

  return (
    <div style={{ padding: '24px', maxWidth: 1000, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 22 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--mai-fg)', margin: '0 0 4px' }}>{t('comp.title')}</h1>
        <p style={{ margin: 0, color: 'var(--mai-fg-sub)', fontSize: 14 }}>{t('comp.sub')}</p>
      </div>

      {/* Certification cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14, marginBottom: 28 }}>
        {CERTS.map(c => {
          const info = isZh ? c.zh : c.en;
          const isOngoing = info.until === '持續有效' || info.until === 'Ongoing';
          return (
            <div key={c.id} style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: c.dotBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg viewBox="0 0 20 20" width="22" height="22" fill={c.dot}>
                    <path fillRule="evenodd" d="M10 1a9 9 0 100 18A9 9 0 0010 1zm3.707 7.707a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                </div>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: '#1f2937' }}>{c.name}</div>
                  <div style={{ fontSize: 11.5, color: isOngoing ? '#059669' : '#6b7280', fontWeight: 500, marginTop: 2 }}>
                    {isOngoing ? (isZh ? '✓ 持續有效' : '✓ Ongoing') : (isZh ? `有效期至 ${info.until}` : `Valid until ${info.until}`)}
                    {' · '}
                    {isZh ? '範圍：' : 'Scope: '}{info.scope}
                  </div>
                </div>
              </div>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--mai-fg-sub)', lineHeight: 1.65 }}>{info.desc}</p>
            </div>
          );
        })}
      </div>

      {/* Document library */}
      <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, overflow: 'hidden' }}>
        {/* Toolbar */}
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <h2 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: '#1f2937', flex: 1 }}>{t('comp.docs')}</h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, border: '1px solid var(--mai-border)', borderRadius: 8, padding: '0 10px', height: 34 }}>
            <Icon name="search" size={14} />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder={isZh ? '搜尋文件…' : 'Search documents…'}
              style={{ border: 'none', outline: 'none', fontSize: 13, width: 150, background: 'transparent' }}
            />
          </div>
        </div>

        {/* Category filter */}
        <div style={{ padding: '10px 20px', borderBottom: '1px solid var(--mai-border)', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {Object.keys(CAT_KEYS).map(c => (
            <button
              key={c}
              onClick={() => setCatFilter(c)}
              style={{
                padding: '4px 12px', borderRadius: 16, fontSize: 12, cursor: 'pointer',
                border: catFilter === c ? 'none' : '1px solid var(--mai-border)',
                background: catFilter === c ? 'var(--mai-primary)' : 'white',
                color: catFilter === c ? 'white' : 'var(--mai-fg-sub)',
              }}
            >
              {CAT_KEYS[c][isZh ? 'zh' : 'en']}
            </button>
          ))}
        </div>

        {/* Document rows */}
        {filtered.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--mai-fg-sub)', fontSize: 14 }}>
            {isZh ? '找不到符合的文件' : 'No matching documents'}
          </div>
        ) : (
          filtered.map((d, i) => {
            const info = isZh ? d.zh : d.en;
            const fmtStyle = FMT_STYLE[d.fmt] || { color: '#6b7280', bg: '#f9fafb' };
            return (
              <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 20px', borderTop: i > 0 ? '1px solid var(--mai-border)' : 'none' }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background: fmtStyle.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name="file-text" size={17} style={{ color: fmtStyle.color }} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: '#1f2937' }}>{info.title}</span>
                    <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: fmtStyle.bg, color: fmtStyle.color }}>{d.fmt}</span>
                  </div>
                  <p style={{ margin: 0, fontSize: 12.5, color: 'var(--mai-fg-sub)', lineHeight: 1.5 }}>{info.desc}</p>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 11, color: 'var(--mai-fg-sub)', marginBottom: 6 }}>{d.size} · {d.updated}</div>
                  <button
                    onClick={() => handleDownload(d.id)}
                    style={{
                      padding: '5px 13px', borderRadius: 7, fontSize: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4,
                      border: downloaded[d.id] ? 'none' : '1px solid var(--mai-border)',
                      background: downloaded[d.id] ? '#ecfdf5' : 'white',
                      color: downloaded[d.id] ? '#059669' : '#374151',
                    }}
                  >
                    <Icon name={downloaded[d.id] ? 'check' : 'download'} size={12} />
                    {downloaded[d.id] ? (isZh ? '已下載' : 'Downloaded') : t('common.download')}
                  </button>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Footer note */}
      <div style={{ marginTop: 16, padding: '11px 16px', background: '#f9fafb', borderRadius: 8, fontSize: 12.5, color: 'var(--mai-fg-sub)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icon name="lock" size={13} />
        {isZh
          ? '所有文件僅限 MaiAgent 授權夥伴下載。如有特殊需求，請聯繫你的夥伴經理。'
          : 'All documents are for authorised MaiAgent partners only. Contact your Partner Manager for specific requests.'}
      </div>
    </div>
  );
};

Object.assign(window, { CompliancePage });
