// Top-level renderer for the news article page.
// Detects viewport via matchMedia and renders desktop or mobile layout.
// Mounts the reused LeadForm component at the #book anchor.

function CDLeadSection({ hookId }) {
  return (
    <section className="cd-lead-section" id="book">
      <div className="cd-lead-section__inner">
        <h2 className="cd-lead-section__heading">Book your free contract review</h2>
        <p className="cd-lead-section__subline">
          30-minute call. Verified builder. We'll review your provisional-sum lines and the variations clauses to negotiate.
        </p>
        <div className="cd-form-shell">
          <LeadForm hookId={hookId} />
        </div>
      </div>
    </section>
  );
}

function CDArticlePage() {
  // Viewport detection — drives which layout component renders.
  // Two breakpoints: ≤480 mobile, ≥901 desktop. 481-900 falls back to a
  // single-column reflow of the desktop component (controlled via CSS).
  const [viewport, setViewport] = cdUseState(() => {
    if (typeof window === 'undefined') return 'desktop';
    const w = window.innerWidth;
    if (w <= 480) return 'mobile';
    return 'desktop';
  });

  cdUseEffect(() => {
    const mq = window.matchMedia('(max-width: 480px)');
    const onChange = () => {
      setViewport(mq.matches ? 'mobile' : 'desktop');
    };
    onChange();
    if (mq.addEventListener) {
      mq.addEventListener('change', onChange);
      return () => mq.removeEventListener('change', onChange);
    } else {
      mq.addListener(onChange);
      return () => mq.removeListener(onChange);
    }
  }, []);

  // PageView already fired by Meta Pixel base in <head>. Reused LeadForm fires
  // Lead event on submit — no extra wiring needed.
  cdUseEffect(() => {
    console.log('[CD article page_view]', { hookId: 'article_fixed_price', viewport });
  }, [viewport]);

  const topic = window.TOPIC;
  const mostRead = window.MOST_READ || [];

  if (viewport === 'mobile') {
    return (
      <>
        <CDVariationDenseMobile topic={topic} mostRead={mostRead} bodySize={17} />
        <CDLeadSection hookId="article_fixed_price" />
        <CDMobileMostRead mostRead={mostRead} padX={16} />
        <CDMobileFooter padX={16} />
      </>
    );
  }

  return (
    <>
      <CDVariationDense topic={topic} mostRead={mostRead} bodySize={18} />
      <CDLeadSection hookId="article_fixed_price" />
      <CDFooter />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<CDArticlePage />);
