"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HtmlIFrame = void 0;
const tslib_1 = require("tslib");
const react_1 = require("react");
const react_2 = tslib_1.__importDefault(require("react"));
const HtmlIFrame = ({ className, html, id }) => {
    const [contentHeight, setContentHeight] = (0, react_1.useState)(200);
    const srcDoc = (0, react_1.useMemo)(() => {
        const css = `
      html, body {
        margin: 0;
        padding: 0;
        background: transparent;
        font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
        font-size: 12px;
        line-height: 1.4;
        color: #374151;
        word-break: break-word;
      }
      body { overflow: hidden; padding-bottom: 32px; }
      #__root > :last-child { margin-bottom: 0 !important; }
      #__end { height: 1px; }
      a { color: #2563eb; text-decoration: underline; }
      img, video { max-width: 100%; height: auto; display: block; }
      /* reset margin default gây hụt */
      p, ul, ol, h1, h2, h3, h4, h5, h6 { margin: 0; }
      p + p { margin-top: 10px; }
      ul, ol { padding-left: 18px; }
      li + li { margin-top: 6px; }
    `;
        const script = `
      (function () {
        function getDocHeight() {
          var root = document.getElementById('__root');
          var end = document.getElementById('__end');

          // Ưu tiên đo bottom theo layout thực tế
          if (root && end) {
            var r1 = root.getBoundingClientRect();
            var r2 = end.getBoundingClientRect();
            // bottom của end relative với top root
            var h = (r2.bottom - r1.top);
            return Math.ceil(h || 0);
          }

          // fallback
          var body = document.body;
          var html = document.documentElement;
          var h2 = Math.max(
            body ? body.scrollHeight : 0,
            html ? html.scrollHeight : 0
          );
          return Math.ceil(h2 || 0);
        }

        var lastSent = 0;

        function measure() {
          var h = getDocHeight();
          var out = h + 2;

          if (Math.abs(out - lastSent) < 2) return;
          lastSent = out;

          window.parent.postMessage(
            { type: 'IFRAME_HEIGHT', id: '${id}', height: out },
            '*'
          );
        }

        var rafId = null;
        function requestMeasure() {
          if (rafId) cancelAnimationFrame(rafId);
          rafId = requestAnimationFrame(function () {
            rafId = null;
            measure();
          });
        }

        window.addEventListener('load', requestMeasure);

        try {
          new ResizeObserver(requestMeasure).observe(document.documentElement);
          if (document.body) new ResizeObserver(requestMeasure).observe(document.body);
        } catch (e) {}

        function hookImages() {
          var imgs = document.images || [];
          for (var i = 0; i < imgs.length; i++) {
            if (!imgs[i].complete) {
              imgs[i].addEventListener('load', requestMeasure);
              imgs[i].addEventListener('error', requestMeasure);
            }
          }
        }

        requestMeasure();
        setTimeout(requestMeasure, 50);
        setTimeout(requestMeasure, 150);
        setTimeout(function () { hookImages(); requestMeasure(); }, 0);
      })();
    `;
        return `<!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <style>${css}</style>
        </head>
        <body>
          <div id="__root">
            ${html !== null && html !== void 0 ? html : ''}
            <div id="__end"></div>
          </div>
          <script>${script}</script>
        </body>
      </html>`;
    }, [html, id]);
    (0, react_1.useEffect)(() => {
        const handler = (e) => {
            var _a, _b;
            if (((_a = e.data) === null || _a === void 0 ? void 0 : _a.type) !== 'IFRAME_HEIGHT')
                return;
            if (((_b = e.data) === null || _b === void 0 ? void 0 : _b.id) !== id)
                return;
            const h = Number(e.data.height) || 0;
            setContentHeight((prev) => (Math.abs(prev - h) < 2 ? prev : h));
        };
        window.addEventListener('message', handler);
        return () => window.removeEventListener('message', handler);
    }, [id]);
    const renderH = Math.max(0, contentHeight);
    return (react_2.default.createElement("iframe", { className: className, sandbox: 'allow-scripts allow-popups allow-forms', srcDoc: srcDoc, style: {
            width: '100%',
            height: `${renderH}px`,
            border: 'none',
            display: 'block',
        }, title: `noti-html-${id}` }));
};
exports.HtmlIFrame = HtmlIFrame;
//# sourceMappingURL=HtmlIFrame.js.map