// Word to PDF — parse DOCX with mammoth.js, render HTML preview, print to PDF via browser dialog.

const MAMMOTH_URL = 'https://cdn.jsdelivr.net/npm/mammoth@1.8.0/mammoth.browser.min.js';

window.TOOL_HANDLERS['word-to-pdf'] = function WordToPdfTool() {
  const [loading, setLoading] = React.useState(false);
  const [file, setFile] = React.useState(null);
  const [html, setHtml] = React.useState('');
  const [warnings, setWarnings] = React.useState([]);
  const [stats, setStats] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [printing, setPrinting] = React.useState(false);

  const handleFile = async (f) => {
    if (!f) return;
    setLoading(true);
    setErr('');
    setFile(f);
    setHtml('');
    setWarnings([]);
    setStats(null);

    try {
      await window.loadScript(MAMMOTH_URL);

      const arrayBuffer = await f.arrayBuffer();
      const result = await mammoth.convertToHtml(
        { arrayBuffer },
        {
          convertImage: mammoth.images.imgElement((image) =>
            image.read('base64').then((imageBuffer) => ({
              src: 'data:' + image.contentType + ';base64,' + imageBuffer
            }))
          )
        }
      );

      const htmlContent = result.value;
      const msgs = (result.messages || []).filter((m) => m.type === 'warning');

      // Gather stats from the generated HTML
      const tmpDiv = document.createElement('div');
      tmpDiv.innerHTML = htmlContent;
      const paragraphs = tmpDiv.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li').length;
      const images = tmpDiv.querySelectorAll('img').length;
      const tables = tmpDiv.querySelectorAll('table').length;

      setHtml(htmlContent);
      setWarnings(msgs);
      setStats({ paragraphs, images, tables });
    } catch (e) {
      setErr(e.message || 'Failed to convert file. Make sure it is a valid .docx file.');
    } finally {
      setLoading(false);
    }
  };

  const printToPdf = () => {
    setPrinting(true);
    setErr('');
    try {
      const printCss = `
*, *::before, *::after { box-sizing: border-box; }
body {
  font-family: Georgia, "Times New Roman", serif;
  line-height: 1.6;
  color: #1a1a1a;
  max-width: 680px;
  margin: 0 auto;
  padding: 32px 24px;
}
h1 { font-size: 24px; margin: 28px 0 12px; font-weight: 700; }
h2 { font-size: 20px; margin: 24px 0 10px; font-weight: 700; }
h3 { font-size: 17px; margin: 20px 0 8px; font-weight: 700; }
h4, h5, h6 { font-size: 15px; margin: 16px 0 6px; font-weight: 600; }
p { margin: 0 0 10px; }
ul, ol { margin: 0 0 12px; padding-left: 28px; }
li { margin-bottom: 4px; }
table { border-collapse: collapse; width: 100%; margin: 14px 0; }
th, td { border: 1px solid #999; padding: 6px 10px; text-align: left; font-size: 13px; }
th { background: #f0f0f0; font-weight: 600; }
img { max-width: 100%; height: auto; margin: 8px 0; }
a { color: #1a56db; text-decoration: underline; }
blockquote { margin: 12px 0; padding: 8px 16px; border-left: 3px solid #ccc; color: #555; }
pre, code { font-family: ui-monospace, monospace; font-size: 12px; }
pre { background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto; }
@media print {
  body { padding: 0; }
  @page { margin: 20mm 18mm; size: A4; }
  img { page-break-inside: avoid; }
  h1, h2, h3 { page-break-after: avoid; }
  table { page-break-inside: auto; }
  tr { page-break-inside: avoid; }
}`;

      const title = file ? file.name.replace(/\.[^.]+$/, '') : 'Document';
      const doc = `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title><style>${printCss}</style></head><body>${html}</body></html>`;

      const iframe = document.createElement('iframe');
      iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;';
      iframe.sandbox = 'allow-modals allow-same-origin';
      document.body.appendChild(iframe);
      iframe.srcdoc = doc;
      iframe.onload = () => {
        setTimeout(() => {
          try {
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
          } catch (e) { setErr(e.message); }
          finally { setPrinting(false); setTimeout(() => iframe.remove(), 1000); }
        }, 200);
      };
    } catch (e) {
      setErr(e.message);
      setPrinting(false);
    }
  };

  const reset = () => {
    setFile(null);
    setHtml('');
    setWarnings([]);
    setStats(null);
    setErr('');
    setLoading(false);
    setPrinting(false);
  };

  // Inject preview styles once
  React.useEffect(() => {
    const id = 'wtpdf-preview-styles';
    if (document.getElementById(id)) return;
    const style = document.createElement('style');
    style.id = id;
    style.textContent = `
.wtpdf-preview { background: #fff; color: #1a1a1a; padding: 32px 28px; max-width: 700px; margin: 0 auto; border-radius: 10px; border: 1px solid var(--id-border); box-shadow: 0 2px 12px rgba(0,0,0,.08); font-family: Georgia, "Times New Roman", serif; line-height: 1.6; font-size: 14px; overflow: auto; max-height: 500px; }
.wtpdf-preview h1 { font-size: 22px; margin: 24px 0 10px; font-weight: 700; }
.wtpdf-preview h2 { font-size: 18px; margin: 20px 0 8px; font-weight: 700; }
.wtpdf-preview h3 { font-size: 16px; margin: 16px 0 6px; font-weight: 700; }
.wtpdf-preview h4, .wtpdf-preview h5, .wtpdf-preview h6 { font-size: 14px; margin: 12px 0 4px; font-weight: 600; }
.wtpdf-preview p { margin: 0 0 10px; }
.wtpdf-preview ul, .wtpdf-preview ol { margin: 0 0 10px; padding-left: 24px; }
.wtpdf-preview li { margin-bottom: 3px; }
.wtpdf-preview table { border-collapse: collapse; width: 100%; margin: 12px 0; }
.wtpdf-preview th, .wtpdf-preview td { border: 1px solid #ccc; padding: 5px 8px; text-align: left; font-size: 12px; }
.wtpdf-preview th { background: #f5f5f5; font-weight: 600; }
.wtpdf-preview img { max-width: 100%; height: auto; margin: 6px 0; border-radius: 4px; }
.wtpdf-preview a { color: #1a56db; }
.wtpdf-preview blockquote { margin: 10px 0; padding: 6px 14px; border-left: 3px solid #ddd; color: #555; }
.wtpdf-preview pre { background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px; }
.wtpdf-preview code { font-family: ui-monospace, monospace; font-size: 12px; }`;
    document.head.appendChild(style);
  }, []);

  // Loading library / converting
  if (loading) {
    return <window.LoadingCard label="Converting document\u2026" sub={file ? file.name : ''} />;
  }

  // No file yet — show dropzone
  if (!file || !html) {
    return (
      <div className="mini-tool">
        <window.Dropzone
          onFile={handleFile}
          title="Drop a Word document here"
          hint=".docx files supported"
          accept=".docx,.doc,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        />
        {err && (
          <window.ToolError
            error={err}
            hint="Make sure the file is a valid .docx document. Older .doc files are not supported."
            onRetry={reset}
          />
        )}
      </div>
    );
  }

  // Stats line
  const statsLine = stats
    ? ` \u00b7 ${stats.paragraphs} block${stats.paragraphs !== 1 ? 's' : ''}` +
      (stats.images > 0 ? ` \u00b7 ${stats.images} image${stats.images !== 1 ? 's' : ''}` : '') +
      (stats.tables > 0 ? ` \u00b7 ${stats.tables} table${stats.tables !== 1 ? 's' : ''}` : '')
    : '';

  return (
    <div className="mini-tool">
      {/* File info bar */}
      <div style={{ padding: 12, background: 'var(--id-surface-alt)', borderRadius: 10, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <window.Icon name="doc" size={20} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <strong style={{ display: 'block', wordBreak: 'break-all' }}>{file.name}</strong>
          <div className="cmp-meta">{window.fmtBytes(file.size)}{statsLine}</div>
        </div>
      </div>

      {/* Conversion warnings */}
      {warnings.length > 0 && (
        <details style={{ marginBottom: 14, padding: '8px 12px', background: '#fef3cd', borderRadius: 8, fontSize: 13, color: '#664d03' }}>
          <summary style={{ cursor: 'pointer', fontWeight: 600 }}>
            {warnings.length} conversion warning{warnings.length !== 1 ? 's' : ''}
          </summary>
          <ul style={{ margin: '6px 0 0', paddingLeft: 20 }}>
            {warnings.map((w, i) => <li key={i} style={{ marginBottom: 2 }}>{w.message}</li>)}
          </ul>
        </details>
      )}

      {/* Preview */}
      <div className="mini-label" style={{ marginBottom: 8 }}>Preview</div>
      <div className="wtpdf-preview" dangerouslySetInnerHTML={{ __html: html }} />

      <div className="cmp-meta" style={{ marginTop: 8, textAlign: 'center' }}>
        Tip: in the print dialog choose &ldquo;Save as PDF&rdquo; as the destination.
      </div>

      {err && <div style={{ color: '#c8321f', marginTop: 10 }}>{err}</div>}

      {/* Actions */}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={reset}>
          <window.Icon name="upload" size={16} /> Upload another
        </button>
        <button className="btn btn-primary" onClick={printToPdf} disabled={printing || !html}>
          <window.Icon name="doc" size={16} /> {printing ? 'Preparing\u2026' : 'Save as PDF'}
        </button>
      </div>
    </div>
  );
};
