/* eslint-disable */
// Comments, Disqus embed that loads under every article.
//
// To activate:
//   1. Sign up free at https://disqus.com → "I want to install Disqus on my site".
//   2. Pick a "shortname", e.g. cbm-cw. This becomes part of your moderation URL.
//   3. Edit the SHORTNAME constant below to match.
//   4. In the Disqus admin, set the trusted domain to cbm.cw.
//   5. Moderate at https://<SHORTNAME>.disqus.com/admin/
//
// Privacy: Disqus loads only after the visitor has accepted "marketing" cookies
// (or has dismissed the banner). Until then we show a tap-to-load placeholder.

const SHORTNAME = 'cbm-cw-1';   // ← replace after Disqus signup

const Comments = ({ slug, title }) => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [allowed, setAllowed] = React.useState(false);
  const [loaded, setLoaded] = React.useState(false);

  // Check consent on mount and subscribe to changes.
  React.useEffect(() => {
    const sync = () => {
      const c = (window.readConsent && window.readConsent()) || null;
      setAllowed(!!(c && c.marketing));
    };
    sync();
    window.addEventListener('cbm:consentchange', sync);
    return () => window.removeEventListener('cbm:consentchange', sync);
  }, []);

  // Lazy-load Disqus only after consent + once per page life.
  React.useEffect(() => {
    if (!allowed || loaded) return;
    if (SHORTNAME === 'cbm-cw-placeholder') return; // Skip if not configured

    const pageUrl = window.location.origin + window.location.pathname + '#/article/' + encodeURIComponent(slug);
    const pageId  = 'article-' + slug;

    // Disqus reset (for SPAs)
    window.disqus_config = function () {
      this.page.url = pageUrl;
      this.page.identifier = pageId;
      this.page.title = title;
    };

    if (window.DISQUS && typeof window.DISQUS.reset === 'function') {
      window.DISQUS.reset({ reload: true, config: window.disqus_config });
      setLoaded(true);
      return;
    }

    const s = document.createElement('script');
    s.src = 'https://' + SHORTNAME + '.disqus.com/embed.js';
    s.setAttribute('data-timestamp', String(Date.now()));
    document.body.appendChild(s);
    setLoaded(true);
  }, [allowed, slug, title, loaded]);

  // Re-render when navigating between articles (SPA).
  React.useEffect(() => {
    if (loaded && window.DISQUS) {
      const pageUrl = window.location.origin + window.location.pathname + '#/article/' + encodeURIComponent(slug);
      window.DISQUS.reset({
        reload: true,
        config: function () {
          this.page.url = pageUrl;
          this.page.identifier = 'article-' + slug;
          this.page.title = title;
        }
      });
    }
  }, [slug, title]);

  return (
    <section className="cbm-comments">
      <div className="cbm-comments__header">
        <span className="cbm-eyebrow">{t('comments_eyebrow')}</span>
        <div className="cbm-section-rule" />
        <h2 className="cbm-section__title">{t('comments_title')}</h2>
        <p className="cbm-section__lede" style={{marginTop: 10, fontSize: 15}}>
          {t('comments_lede')}
        </p>
      </div>

      {allowed ? (
        <div id="disqus_thread" className="cbm-comments__thread" />
      ) : (
        <div className="cbm-comments__optin">
          <p>{t('comments_consent_body')}</p>
          <button
            className="cbm-btn cbm-btn--gold"
            onClick={() => {
              if (window.writeConsent) {
                window.writeConsent({ necessary: true, analytics: false, marketing: true });
              }
              setAllowed(true);
            }}
          >
            {t('comments_consent_cta')}
          </button>
          <p style={{fontSize: 12, marginTop: 16, color: 'var(--cbm-muted)'}}>
            {t('comments_consent_note')}
          </p>
        </div>
      )}
    </section>
  );
};

Object.assign(window, { Comments });
