/* MostlyPDF — RenderRunner (F147). The tool UI for the two MostlyRender-backed tools:
   html-to-pdf (paste HTML) and url-to-pdf (enter a URL). Unlike the file-based Runner in
   app.jsx these take a text/URL input and receive back a HOSTED PDF URL (MostlyRender renders
   it), so the flow is: submit → { pdfUrl } → open/download.

   Copy is intentionally plain strings (not tr() keys) — same as MostlyPrivacy's DocWizard
   (F145) — so this feature ships without expanding the i18n catalog for every locale. The
   surrounding chrome (Nav/Footer) is still localized in app.jsx.

   SSR-safe: registers a factory on window; no DOM/window access at eval time. app.jsx calls
   the factory with its React/hooks/style helpers so this file needs no imports of its own. */
(function () {
  'use strict';
  // Factory: app.jsx passes its closure's React + hooks + the S() style parser + endpoint.
  window.MostlyPDFRenderRunner = function makeRenderRunner(deps) {
    const { React, useState, S, endpoint, ic } = deps;

    // slug → UI config. Both are tier 'free' render-engine tools.
    const CONF = {
      'html-to-pdf': {
        icon: 'code',
        kind: 'html',
        heading: 'HTML to PDF',
        answer: 'Paste your HTML (inline CSS welcome) and render it to a clean, paginated A4 PDF.',
        inputLabel: 'Your HTML',
        placeholder: '<!doctype html>\n<html>\n  <body>\n    <h1>Invoice #1024</h1>\n    <p>Thanks for your business.</p>\n  </body>\n</html>',
        runLabel: 'Convert to PDF',
        sample: '<!doctype html><html><body style="font:16px/1.6 system-ui;padding:40px"><h1>Hello, PDF</h1><p>This HTML was rendered to a paginated A4 document by MostlyPDF.</p></body></html>',
      },
      'url-to-pdf': {
        icon: 'link',
        kind: 'url',
        heading: 'Webpage to PDF',
        answer: 'Enter a public web address and capture the whole page as a paginated A4 PDF.',
        inputLabel: 'Web address',
        placeholder: 'https://example.com/page',
        runLabel: 'Capture as PDF',
        sample: '',
      },
    };

    function RenderRunner(props) {
      const slug = props.slug;
      const go = props.go;
      const conf = CONF[slug] || CONF['html-to-pdf'];
      const [value, setValue] = useState('');
      const [paper, setPaper] = useState('A4');
      const [phase, setPhase] = useState('idle'); // idle | working | success | error
      const [errMsg, setErrMsg] = useState('');
      const [result, setResult] = useState(null); // { pdfUrl }

      function valid() {
        const v = (value || '').trim();
        if (conf.kind === 'url') return /^https?:\/\/\S+$/i.test(v);
        return v.length > 0;
      }

      async function run() {
        if (!valid()) {
          setErrMsg(conf.kind === 'url' ? 'Enter a full web address starting with http:// or https://' : 'Paste some HTML to convert.');
          setPhase('error');
          return;
        }
        setPhase('working');
        setErrMsg('');
        try {
          const options = conf.kind === 'url' ? { url: value.trim(), paper } : { html: value, paper };
          const res = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ tool: slug, options }),
          });
          const j = await res.json().catch(() => ({}));
          if (!res.ok) throw new Error(j.error || 'PDF rendering failed');
          if (!j.pdfUrl) throw new Error('No PDF was produced. Please try again.');
          setResult({ pdfUrl: j.pdfUrl });
          setPhase('success');
        } catch (err) {
          const net = /Failed to fetch|NetworkError/i.test(err.message) ? ' — check your connection and try again.' : '';
          setErrMsg(err.message + net);
          setPhase('error');
        }
      }

      const label = (t) => React.createElement('span', { style: S('font-size:12px;font-weight:500;color:var(--fg);') }, t);
      const backBar = React.createElement('div', {
        onClick: () => go && go('landing'),
        style: S('display:inline-flex;align-items:center;gap:8px;font-size:13px;color:var(--fg-muted);cursor:pointer;margin-bottom:18px;'),
      }, ['All tools ', React.createElement('span', { style: S('color:var(--fg-subtle);') }, '/'), ' ', React.createElement('span', { style: S('color:var(--fg);font-weight:500;') }, 'Convert')]);

      const head = React.createElement('div', { style: S('display:flex;align-items:flex-start;gap:16px;margin-bottom:22px;') }, [
        React.createElement('span', { key: 'ic', style: S('display:inline-grid;place-items:center;width:54px;height:54px;border-radius:15px;background:var(--accent-bg-soft);color:var(--accent);flex:none;') }, ic ? ic(conf.icon, 26) : null),
        React.createElement('div', { key: 'h' }, [
          React.createElement('h1', { key: 't', style: S('font-family:var(--font-display);font-size:30px;font-weight:600;letter-spacing:-0.03em;margin:0;') }, conf.heading),
          React.createElement('p', { key: 'a', style: S('font-size:15px;line-height:1.5;color:var(--fg-muted);margin:7px 0 0;max-width:42em;text-wrap:pretty;') }, conf.answer),
        ]),
      ]);

      let panel;
      if (phase === 'success' && result) {
        panel = React.createElement('div', { className: 'forge-card', style: S('padding:26px;text-align:center;') }, [
          React.createElement('div', { key: 'ok', style: S('font-family:var(--font-display);font-size:20px;font-weight:600;letter-spacing:-0.02em;margin-bottom:6px;') }, 'Your PDF is ready'),
          React.createElement('p', { key: 'p', style: S('font-size:13.5px;color:var(--fg-muted);margin:0 0 16px;') }, 'Rendered by MostlyRender into a paginated ' + paper + ' document.'),
          React.createElement('div', { key: 'btns', style: S('display:flex;gap:10px;justify-content:center;flex-wrap:wrap;') }, [
            React.createElement('a', { key: 'dl', href: result.pdfUrl, target: '_blank', rel: 'noopener', download: slug + '.pdf', className: 'forge-btn forge-btn--primary forge-btn--lg' }, React.createElement('span', {}, 'Download PDF')),
            React.createElement('button', { key: 'again', onClick: () => { setPhase('idle'); setResult(null); }, className: 'forge-btn forge-btn--secondary forge-btn--lg' }, 'Convert another'),
          ]),
        ]);
      } else {
        const input = conf.kind === 'url'
          ? React.createElement('input', {
              key: 'in', className: 'forge-input', type: 'url', value, placeholder: conf.placeholder,
              onChange: (ev) => setValue(ev.target.value), autoFocus: true,
            })
          : React.createElement('textarea', {
              key: 'in', className: 'forge-input', value, placeholder: conf.placeholder, spellCheck: false,
              onChange: (ev) => setValue(ev.target.value),
              style: S('min-height:220px;font-family:var(--font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:13px;line-height:1.5;resize:vertical;'),
            });
        panel = React.createElement('div', { className: 'forge-card', style: S('padding:22px;display:flex;flex-direction:column;gap:14px;') }, [
          React.createElement('div', { key: 'field', style: S('display:flex;flex-direction:column;gap:7px;') }, [label(conf.inputLabel), input]),
          conf.sample ? React.createElement('button', {
            key: 'sample', onClick: () => setValue(conf.sample),
            style: S('align-self:flex-start;font-size:12.5px;font-weight:600;color:var(--accent);background:none;border:none;cursor:pointer;padding:0;'),
          }, 'Use a sample') : null,
          React.createElement('div', { key: 'paper', style: S('display:flex;flex-direction:column;gap:7px;max-width:220px;') }, [
            label('Page size'),
            React.createElement('select', { className: 'forge-input', value: paper, onChange: (ev) => setPaper(ev.target.value) }, [
              React.createElement('option', { key: 'A4', value: 'A4' }, 'A4'),
              React.createElement('option', { key: 'Letter', value: 'Letter' }, 'US Letter'),
              React.createElement('option', { key: 'Legal', value: 'Legal' }, 'US Legal'),
            ]),
          ]),
          phase === 'error' ? React.createElement('div', { key: 'err', style: S('font-size:12.5px;color:var(--bad);font-weight:500;') }, errMsg) : null,
          React.createElement('div', { key: 'run' }, [
            React.createElement('button', {
              onClick: run, disabled: phase === 'working', className: 'forge-btn forge-btn--primary forge-btn--lg',
            }, React.createElement('span', {}, phase === 'working' ? 'Rendering…' : conf.runLabel)),
          ]),
          React.createElement('p', { key: 'note', style: S('font-size:12px;color:var(--fg-subtle);margin:0;line-height:1.5;') },
            'Also available programmatically — see the API docs. Rendering is powered by MostlyRender, part of the Mostly Tiny portfolio.'),
        ]);
      }

      // AEO on-page FAQ (crawlable) — mirrors the seo.config page FAQ.
      const faq = [
        conf.kind === 'url'
          ? { q: 'Is Webpage to PDF free?', a: 'Yes — paste a public URL and download a paginated A4 PDF, free to start with no watermark.' }
          : { q: 'Is HTML to PDF free?', a: 'Yes — paste HTML and download a paginated A4 PDF, free to start with no watermark.' },
        { q: 'What page sizes are supported?', a: 'A4, US Letter and US Legal, each paginated with print margins.' },
        { q: 'Can I use it through an API?', a: 'Yes — the same conversion is available on the transparent, flat-priced MostlyPDF API with a key from your dashboard.' },
      ];
      const faqBlock = React.createElement('div', { style: S('max-width:760px;margin:34px auto 0;') },
        faq.map((f, i) => React.createElement('details', { key: i, style: S('border-top:1px solid var(--hairline);padding:14px 0;') }, [
          React.createElement('summary', { key: 'q', style: S('font-weight:600;font-size:15px;cursor:pointer;') }, f.q),
          React.createElement('p', { key: 'a', style: S('font-size:14px;line-height:1.6;color:var(--fg-muted);margin:8px 0 0;') }, f.a),
        ])));

      return React.createElement('div', { style: S('max-width:1100px;margin:0 auto;padding:26px 28px 8px;') }, [
        React.createElement('div', { key: 'back' }, backBar),
        React.createElement('div', { key: 'head' }, head),
        React.createElement('div', { key: 'panel' }, panel),
        React.createElement('div', { key: 'faq' }, faqBlock),
      ]);
    }

    return RenderRunner;
  };
})();
