<div id="module-root" data-module-slug="module 1 test data">
  <!-- The module content from Google Sheets will appear here -->
  Loading module...
</div>

<script>
(async function () {
  // >>>>> EDIT THIS: put your actual Spreadsheet ID here <<<<<
  const SPREADSHEET_ID = '1JuH5DYhzSrdfYm9UCa4nIlfUsxJNMac2zuoOUHRWrTA';
  const SHEET_NAME = 'Modules';

  const root = document.getElementById('module-root');
  const targetSlug = root.dataset.moduleSlug;

  // We'll use a simple public helper that turns your sheet into JSON.
  const url = `https://opensheet.elk.sh/${SPREADSHEET_ID}/${encodeURIComponent(SHEET_NAME)}`;

  try {
    const res = await fetch(url);
    if (!res.ok) {
      throw new Error('Network response was not ok');
    }

    const rows = await res.json(); // Each row is an object with your column names as keys
    const module = rows.find(row => row.slug === targetSlug);

    if (!module) {
      root.innerHTML = `<p>Module not found for slug: <code>${targetSlug}</code>.</p>`;
      return;
    }

    // Turn the plain body_text into basic paragraphs
    const bodyText = module.body_text || '';
    const paragraphs = bodyText
      .split(/\n\s*\n/) // split on blank lines
      .map(p => p.trim())
      .filter(p => p.length > 0)
      .map(p => `<p>${p}</p>`)
      .join('');

    root.innerHTML = `
      <article class="rg-module">
        <header>
          <h1>${module.title}</h1>
          ${module.short_blurb ? `<p><em>${module.short_blurb}</em></p>` : ''}
        </header>

        ${paragraphs}

        ${module.statute_ids ? `
          <section>
            <h2>Key Statutes Referenced</h2>
            <p>${module.statute_ids}</p>
          </section>
        ` : ''}

        ${module.case_ids ? `
          <section>
            <h2>Key Cases Referenced</h2>
            <p>${module.case_ids}</p>
          </section>
        ` : ''}
      </article>
    `;
  } catch (err) {
    console.error(err);
    root.innerHTML = '<p>Sorry, there was a problem loading this module.</p>';
  }
})();
</script>