// components/_gaokao-multi-export-block.jsx — Wave 19-E2
// 批量 PDF / 多方案对比导出 block — rendered inline on dashboard.
//
// Props:
//   reports   — Array of report objects from /api/user/reports
//   userInfo  — { name, examId } — optional
//   lang      — 'zh' | 'en'
//
// Behaviour:
//   - Shows header + per-row checkboxes on the dashboard reports list
//   - Export button is disabled until 2–3 reports are selected
//   - On click: calls mergeReportsToPrintableHtml, opens new window, triggers print
//   - Keeps Wave 17-A single-report export path completely untouched
//
// Exposes window.GaokaoMultiExportBlock.

const GaokaoMultiExportBlock = ({ reports = [], userInfo = {}, lang = 'zh' }) => {
  const [selected, setSelected] = React.useState(new Set());

  // ── i18n dict ──────────────────────────────────────────────────────────────
  const dict = React.useMemo(() => {
    const base = (window.I18N && window.I18N[lang] && window.I18N[lang].gk && window.I18N[lang].gk.multiExport) || {};
    const isZh = lang !== 'en';
    return {
      header:       base.header       || (isZh ? '📦 批量导出对比 PDF' : '📦 Batch Export Comparison PDF'),
      hint:         base.hint         || (isZh ? '选 2–3 个方案后可导出对比报告' : 'Select 2–3 plans to export a comparison report'),
      exportBtn:    base.exportBtn    || (isZh ? '导出对比 PDF' : 'Export Comparison PDF'),
      disabledHint: base.disabledHint || (isZh ? '请先选择 2–3 个方案' : 'Select 2–3 plans first'),
      selectedCount:(n) => base.selectedCount
        ? base.selectedCount(n)
        : (isZh ? `已选 ${n} / 3 个方案` : `${n}/3 plans selected`),
      maxHint:      base.maxHint      || (isZh ? '最多选 3 个方案' : 'Maximum 3 plans'),
      noReports:    base.noReports    || (isZh ? '暂无可选方案' : 'No reports available'),
      colSelect:    base.colSelect    || (isZh ? '选择' : 'Select'),
      colName:      base.colName      || (isZh ? '方案名称' : 'Plan Name'),
      colDate:      base.colDate      || (isZh ? '日期' : 'Date'),
      colTag:       base.colTag       || (isZh ? '类型' : 'Type'),
    };
  }, [lang]);

  // ── Checkbox toggle (cap at 3) ─────────────────────────────────────────────
  const toggleSelect = (id) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        if (next.size >= 3) return prev; // cap at 3
        next.add(id);
      }
      return next;
    });
  };

  const canExport = selected.size >= 2 && selected.size <= 3;

  // ── Resolve merge function from lib ────────────────────────────────────────
  const getMerger = () => {
    if (window.GaokaoMultiReportExport && window.GaokaoMultiReportExport.mergeReportsToPrintableHtml) {
      return window.GaokaoMultiReportExport.mergeReportsToPrintableHtml;
    }
    // Inline fallback for environments where lib script isn't loaded
    return (rpts, uInfo, lng) => {
      const isZh = lng !== 'en';
      const escH = (v) => String(v == null ? '' : v)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
      const rows = rpts.map((r, i) => `<tr><td>${i + 1}</td><td>${escH(r.name)}</td><td>${escH(r.date || '')}</td></tr>`).join('');
      return `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${isZh ? '对比报告' : 'Comparison'}</title><style>@page{size:A4;margin:12mm}body{font-family:sans-serif;font-size:13px}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ccc;padding:6px}</style></head><body><h1>${isZh ? '方案对比报告' : 'Plan Comparison'}</h1><table><tr><th>#</th><th>${isZh ? '方案名称' : 'Plan'}</th><th>${isZh ? '日期' : 'Date'}</th></tr>${rows}</table></body></html>`;
    };
  };

  // ── Export handler ─────────────────────────────────────────────────────────
  const handleExport = () => {
    if (!canExport) return;
    const selectedReports = reports.filter((r) => selected.has(r.id));
    if (selectedReports.length < 2) return;

    let html;
    try {
      const mergeF = getMerger();
      html = mergeF(selectedReports, userInfo, lang);
    } catch (err) {
      alert((lang !== 'en' ? '导出失败：' : 'Export failed: ') + (err && err.message));
      return;
    }

    const win = window.open('', '_blank', 'width=900,height=750');
    if (!win) {
      alert(lang !== 'en' ? '请允许弹出窗口以导出 PDF' : 'Please allow popups to export PDF');
      return;
    }
    win.document.open();
    win.document.write(html);
    win.document.close();
    win.focus();
    setTimeout(() => { win.print(); }, 500);
  };

  // ── Styles ─────────────────────────────────────────────────────────────────
  const containerStyle = {
    background: 'var(--pb-surface-alt, #f4f3f0)',
    border: '1px solid var(--pb-border, #e0e0e0)',
    borderRadius: 8,
    padding: '16px 18px',
    marginBottom: 16,
  };

  const headerStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
    gap: 12,
    flexWrap: 'wrap',
  };

  const titleStyle = {
    fontFamily: 'var(--pb-serif, serif)',
    fontSize: 15,
    fontWeight: 700,
    color: 'var(--pb-navy-900, #0a1628)',
  };

  const hintStyle = {
    fontSize: 11,
    color: 'var(--pb-fg-muted, #888)',
    marginTop: 2,
  };

  const tableStyle = {
    width: '100%',
    borderCollapse: 'collapse',
    fontSize: 12,
  };

  const thStyle = {
    padding: '6px 8px',
    fontSize: 10,
    fontWeight: 700,
    textTransform: 'uppercase',
    letterSpacing: '0.06em',
    background: 'var(--pb-navy-900, #0a1628)',
    color: '#fff',
    textAlign: 'left',
    whiteSpace: 'nowrap',
  };

  const tdStyle = {
    padding: '7px 8px',
    borderBottom: '1px solid var(--pb-border, #e8e8e8)',
    verticalAlign: 'middle',
  };

  const exportBtnStyle = {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 6,
    padding: '8px 18px',
    fontSize: 13,
    fontWeight: 700,
    borderRadius: 6,
    border: 'none',
    cursor: canExport ? 'pointer' : 'not-allowed',
    background: canExport ? 'var(--pb-gold-500, #c9a96e)' : 'var(--pb-border, #e0e0e0)',
    color: canExport ? 'var(--pb-navy-900, #0a1628)' : 'var(--pb-fg-muted, #aaa)',
    opacity: 1,
    transition: 'background 0.15s, color 0.15s',
    flexShrink: 0,
  };

  const checkboxStyle = {
    width: 16,
    height: 16,
    cursor: 'pointer',
    accentColor: 'var(--pb-gold-700, #a07830)',
  };

  // ── Render: no reports ─────────────────────────────────────────────────────
  if (!reports || reports.length === 0) {
    return null; // Don't show block if no reports exist
  }

  const countLabel = dict.selectedCount(selected.size);

  return (
    <div style={containerStyle} data-testid="multi-export-block">
      {/* Header row */}
      <div style={headerStyle}>
        <div>
          <div style={titleStyle}>{dict.header}</div>
          <div style={hintStyle}>{dict.hint}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
          <span
            data-testid="multi-export-count"
            style={{ fontSize: 11, color: selected.size >= 2 ? 'var(--pb-gold-700, #a07830)' : 'var(--pb-fg-muted, #888)', fontWeight: selected.size >= 2 ? 700 : 400 }}
          >
            {countLabel}
          </span>
          <button
            type="button"
            data-testid="multi-export-btn"
            disabled={!canExport}
            onClick={handleExport}
            title={!canExport ? dict.disabledHint : dict.exportBtn}
            style={exportBtnStyle}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <polyline points="6 9 6 2 18 2 18 9"/>
              <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/>
              <rect x="6" y="14" width="12" height="8"/>
            </svg>
            {dict.exportBtn}
          </button>
        </div>
      </div>

      {/* Reports selection table */}
      <div style={{ overflowX: 'auto', borderRadius: 6, border: '1px solid var(--pb-border, #e0e0e0)' }}>
        <table style={tableStyle} data-testid="multi-export-table">
          <thead>
            <tr>
              <th style={{ ...thStyle, width: 40, textAlign: 'center' }}>{dict.colSelect}</th>
              <th style={{ ...thStyle, minWidth: 140 }}>{dict.colName}</th>
              <th style={{ ...thStyle, width: 90 }}>{dict.colDate}</th>
              <th style={{ ...thStyle, width: 60 }}>{dict.colTag}</th>
            </tr>
          </thead>
          <tbody>
            {reports.map((r, i) => {
              const isChecked = selected.has(r.id);
              const isDisabled = !isChecked && selected.size >= 3;
              return (
                <tr
                  key={r.id || i}
                  data-testid={`multi-export-row-${r.id}`}
                  onClick={() => !isDisabled && toggleSelect(r.id)}
                  style={{
                    cursor: isDisabled ? 'not-allowed' : 'pointer',
                    background: isChecked ? 'var(--pb-gold-50, #fef9ef)' : (i % 2 === 0 ? '#fff' : 'var(--pb-surface-alt, #f8f7f4)'),
                    opacity: isDisabled ? 0.5 : 1,
                    transition: 'background 0.1s',
                  }}
                >
                  <td style={{ ...tdStyle, textAlign: 'center' }}>
                    <input
                      type="checkbox"
                      data-testid={`multi-export-checkbox-${r.id}`}
                      checked={isChecked}
                      disabled={isDisabled}
                      onChange={() => !isDisabled && toggleSelect(r.id)}
                      onClick={(e) => e.stopPropagation()}
                      style={checkboxStyle}
                      aria-label={r.name || `Report ${r.id}`}
                    />
                  </td>
                  <td style={{ ...tdStyle, fontWeight: isChecked ? 700 : 400 }}>
                    {r.name || (lang !== 'en' ? `方案${i + 1}` : `Plan ${i + 1}`)}
                  </td>
                  <td style={{ ...tdStyle, fontFamily: 'var(--pb-mono, monospace)', fontSize: 11, color: 'var(--pb-fg-muted, #888)' }}>
                    {r.date || '—'}
                  </td>
                  <td style={{ ...tdStyle }}>
                    <span style={{
                      padding: '1px 6px',
                      fontSize: 9,
                      fontWeight: 700,
                      borderRadius: 3,
                      background: r.tag === 'PAID' ? 'var(--pb-gold-100, #fef3d4)' : 'var(--pb-navy-50, #eef1f7)',
                      color: r.tag === 'PAID' ? 'var(--pb-gold-700, #a07830)' : 'var(--pb-navy-700, #1e3a6e)',
                      fontFamily: 'var(--pb-mono, monospace)',
                    }}>
                      {r.tag || 'FREE'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {selected.size === 3 && (
        <div style={{ fontSize: 11, color: 'var(--pb-fg-muted, #888)', marginTop: 6, textAlign: 'right' }}>
          {dict.maxHint}
        </div>
      )}
    </div>
  );
};

window.GaokaoMultiExportBlock = GaokaoMultiExportBlock;
