// HTML to PDF — render an HTML snippet or URL to PDF via browser print.
// Uses a hidden iframe; calling window.print() on it invokes the native "Save as PDF".

window.TOOL_HANDLERS['html-to-pdf'] = function HtmlToPdfTool() {
  const [mode, setMode] = React.useState('html');  // 'html' | 'url'
  const [html, setHtml] = React.useState('<h1>Hello</h1>\n<p>Edit this HTML and hit <b>Print to PDF</b>.</p>');
  const [url, setUrl] = React.useState('https://example.com');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const printHtml = () => {
    setBusy(true); setErr('');
    try {
      const doc = `<!doctype html><html><head><meta charset="utf-8"><title>Export</title>
        <style>body{font-family:ui-sans-serif,system-ui,sans-serif;line-height:1.55;max-width:720px;margin:24px auto;padding:0 16px;color:#111}</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 { setBusy(false); setTimeout(() => iframe.remove(), 1000); }
        }, 150);
      };
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  const printUrl = () => {
    setErr('');
    const w = window.open(url, '_blank');
    if (!w) return setErr('Popup blocked — allow popups to open a URL for printing.');
    setTimeout(() => { try { w.focus(); w.print(); } catch {} }, 1200);
  };

  return (
    <div className="mini-tool">
      <div className="mini-row">
        <button className={`filter-pill ${mode === 'html' ? 'active' : ''}`} onClick={() => setMode('html')}>Paste HTML</button>
        <button className={`filter-pill ${mode === 'url' ? 'active' : ''}`} onClick={() => setMode('url')}>Use a URL</button>
      </div>

      {mode === 'html' ? (
        <>
          <label className="mini-label" style={{ marginTop: 14 }}>HTML</label>
          <textarea className="mini-input mini-textarea"
            style={{ minHeight: 260, fontFamily: 'ui-monospace, monospace', fontSize: 12 }}
            value={html} onChange={(e) => setHtml(e.target.value)} />
          <div className="cmp-meta" style={{ marginTop: 6 }}>Tip: in the print dialog choose "Save as PDF" as destination.</div>
        </>
      ) : (
        <>
          <label className="mini-label" style={{ marginTop: 14 }}>URL</label>
          <input className="mini-input" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com" />
          <div className="cmp-meta" style={{ marginTop: 6 }}>Opens a new tab and triggers the browser's print dialog.</div>
        </>
      )}

      {err && <div style={{ color: '#c8321f', marginTop: 10 }}>{err}</div>}
      <div className="cmp-actions">
        <button className="btn btn-primary" onClick={mode === 'html' ? printHtml : printUrl} disabled={busy}>
          <window.Icon name="doc" size={16} /> Print to PDF
        </button>
      </div>
    </div>
  );
};
