import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';

const root = process.cwd();
const sourcePath = join(root, 'child', 'time-to-retire-the-cane.html');
const outDir = join(root, 'child', 'ccr');

const sourceHtml = readFileSync(sourcePath, 'utf8');

const cards = [...sourceHtml.matchAll(
  /<a class="news-card" href="([^"]+)"[^>]*>\s*<img src="([^"]+)" alt="([^"]*)">[\s\S]*?<h3>([\s\S]*?)<\/h3>[\s\S]*?<p>([\s\S]*?)<\/p>/g
)].map((match) => {
  const href = match[1];
  const imgSrc = match[2];
  const alt = match[3];
  const title = decodeHtml(match[4].trim());
  const summary = decodeHtml(match[5].trim());
  const fileName = `${slugify(title)}.html`;
  return { href, imgSrc, alt, title, summary, fileName };
});

if (!cards.length) {
  throw new Error('No news cards found in source page.');
}

mkdirSync(outDir, { recursive: true });

const escapeHtml = (value) =>
  String(value)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

function decodeHtml(value) {
  return String(value)
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&ndash;/g, 'â€“')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>');
}

function slugify(value) {
  return String(value)
    .toLowerCase()
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/&/g, ' and ')
    .replace(/['â€™â€œâ€"!?.,:;()]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

function localizePath(value) {
  if (/^https?:\/\//i.test(value) || value.startsWith('/')) return value;
  return `../${value}`;
}

const navLinks = [
  ['Home', '../index.html'],
  ['About', '../index.html#about'],
  ['Our Work', '../index.html#work'],
  ['Achievements', '../index.html#achievements'],
  ['Support', '../index.html#support'],
  ['Team', '../index.html#team'],
  ['Contact', '../index.html#contact'],
];

let generatedCount = 0;

for (const card of cards) {
  const heroImage = localizePath(card.imgSrc);
  const filePath = join(outDir, card.fileName);
  if (existsSync(filePath)) continue;

  const title = card.title;
  const description = `${title} | Stop Child Cruelty Trust`;
  const summary = card.summary || title;
  const sampleText = `This is a placeholder page for ${title}. Replace this sample copy with the final article text when the story is ready.`;

  const html = `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="${escapeHtml(description)}">
  <link rel="icon" type="image/png" href="../images/cropped-new-Stop-Child-Cruelty-Trust-2024.png">
  <link rel="apple-touch-icon" href="../images/cropped-new-Stop-Child-Cruelty-Trust-2024.png">
  <title>${escapeHtml(title)} | Stop Child Cruelty Trust</title>
  <style>
    :root{
      --ink:#18212f;
      --muted:#334155;
      --line:#dde4ec;
      --paper:#fff;
      --soft:#f5f7fa;
      --red:#d72128;
      --red-dark:#a9151b;
      --shadow:0 18px 48px rgba(24,33,47,.11);
      --radius:8px;
      --max:1240px;
    }
    *{box-sizing:border-box}
    html{scroll-behavior:smooth;scroll-padding-top:86px}
    body{margin:0;font-family:Inter,"Segoe UI",Arial,sans-serif;color:var(--ink);background:var(--paper);line-height:1.6}
    img{max-width:100%;display:block}
    a{color:inherit;text-decoration:none}
    p{margin:0 0 1rem;color:var(--muted)}
    h1,h2,h3{margin:0;line-height:1.12;letter-spacing:0}
    h1{font-size:clamp(2.2rem,4.8vw,4.6rem)}
    h2{font-size:clamp(1.35rem,2.4vw,2.05rem)}
    .container{width:min(var(--max),calc(100% - 32px));margin:0 auto}
    .site-header{position:sticky;top:0;z-index:40;background:rgba(255,255,255,.96);border-bottom:1px solid rgba(221,228,236,.82);backdrop-filter:blur(14px)}
    .nav-wrap{display:flex;align-items:center;justify-content:space-between;gap:18px;min-height:76px}
    .brand{display:flex;align-items:center;gap:12px;min-width:220px;font-weight:800}
    .brand img{width: 84px; height: 84px;object-fit:contain}
    .brand span{display:block;font-size:.95rem;line-height:1.18}
    .brand small{display:block;margin-top:2px;color:var(--muted);font-weight:700;font-size:.72rem;text-transform:uppercase}
    .nav-toggle{display:none;width:42px;height:42px;border:1px solid var(--line);background:#fff;border-radius:6px;cursor:pointer}
    .nav-toggle span{display:block;width:18px;height:2px;margin:5px auto;background:var(--ink)}
    .site-nav{display:flex;align-items:center;gap:4px;flex-wrap:wrap;justify-content:flex-end;font-size:.92rem;font-weight:700}
    .site-nav a{padding:10px 12px;border-radius:6px;color:#263242}
    .site-nav a:hover,.site-nav a:focus{background:var(--soft);color:var(--red)}
    .site-nav a.home-link{background:var(--soft);border:1px solid var(--line);color:var(--ink);border-radius:8px;padding:12px 18px}
    .site-nav a.home-link:hover,.site-nav a.home-link:focus{background:#eef2f7;color:var(--red)}
    .site-nav a.donate-link{background:var(--red);color:#fff;border-radius:8px;padding:12px 18px;margin-left:4px}
    .site-nav a.donate-link:hover,.site-nav a.donate-link:focus{background:var(--red-dark);color:#fff}
    .button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:12px 18px;border-radius:6px;border:1px solid transparent;background:var(--red);color:#fff;font-weight:800;transition:transform .18s ease,background .18s ease,border-color .18s ease}
    .button:hover{background:var(--red-dark);transform:translateY(-1px)}
    .button.secondary{background:#fff;color:var(--ink);border-color:var(--line)}
    .hero{position:relative;min-height:100vh;display:grid;align-items:end;overflow:hidden;background:var(--ink);border-bottom:1px solid var(--line)}
    .hero::before{content:"";position:absolute;inset:0;background:linear-gradient(90deg,rgba(12,18,28,.60) 0%,rgba(12,18,28,.30) 42%,rgba(12,18,28,.08) 100%),url("${heroImage}") center center / cover no-repeat;transform:scale(1.01)}
    .hero::after{content:"";position:absolute;inset:auto 0 0;height:160px;background:linear-gradient(0deg,rgba(255,255,255,1),rgba(255,255,255,0))}
    .hero-grid{position:relative;z-index:1;display:grid;grid-template-columns:minmax(0,1fr);min-height:100vh;align-items:end;padding:92px 0 74px}
    .hero-panel{max-width:760px;color:#fff}
    .eyebrow{display:inline-flex;align-items:center;gap:8px;margin-bottom:14px;color:#ff8085;font-size:.82rem;font-weight:900;text-transform:uppercase;letter-spacing:.06em}
    .eyebrow::before{content:"";width:34px;height:2px;background:currentColor}
    .hero p{max-width:760px;margin-top:18px;font-size:1.04rem;color:rgba(255,255,255,.90)}
    .hero-meta{display:inline-flex;align-items:center;gap:10px;margin-top:24px;padding:10px 14px;background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.18);border-radius:999px;backdrop-filter:blur(8px);color:#fff;font-size:.92rem;font-weight:700}
    .detail-band{padding:42px 0 62px;position:relative;z-index:2;margin-top:-52px}
    .paper{background:#fff;border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden}
    .paper-body{padding:28px}
    .paper-body h2{margin-bottom:16px;text-transform:uppercase;font-size:1.02rem;letter-spacing:.02em}
    .paper-body .lead{font-size:1.12rem;color:var(--ink);font-weight:600;margin-bottom:18px}
    .paper-body p{color:var(--ink);font-size:1.03rem}
    .site-footer{background:#101822;color:#fff;padding:42px 0 20px;margin-top:0}
    .site-footer h3,.site-footer p{color:#fff}
    .site-footer p,.site-footer a{color:rgba(255,255,255,.74)}
    .footer-grid{display:grid;grid-template-columns:1.3fr .8fr .9fr;gap:24px;align-items:start}
    .footer-grid h3{margin:0 0 10px;color:#fff;font-size:1rem}
    .footer-links{display:grid;gap:9px}
    .footer-links a{color:rgba(255,255,255,.74)}
    .footer-links a:hover,.footer-links a:focus{color:#fff}
    .copyright{margin-top:24px;padding-top:18px;border-top:1px solid rgba(255,255,255,.14);color:rgba(255,255,255,.68);font-size:.9rem}
    .company-credit{margin-top:10px;font-size:.9rem;color:rgba(255,255,255,.78)}
    .company-credit a{color:#fff;font-weight:700}
    @media (max-width:980px){
      .nav-wrap{position:relative}
      .nav-toggle{display:block}
      .site-nav{display:none;position:absolute;top:100%;right:0;left:0;background:#fff;border:1px solid var(--line);border-top:none;padding:12px 0 16px;box-shadow:0 16px 40px rgba(24,33,47,.12);flex-direction:column;align-items:stretch;justify-content:flex-start;gap:0}
      .site-nav.open{display:flex}
      .site-nav a{width:100%;padding:14px 18px;border-radius:0}
      .site-nav a.home-link{border-radius:0}
      .site-nav a.donate-link{margin-left:0;border-radius:0}
      .footer-grid{grid-template-columns:1fr}
      .hero{min-height:92vh}
      .hero-grid{min-height:92vh;padding:92px 0 62px}
      .detail-band{margin-top:0;padding-top:26px}
    }
    @media (max-width:720px){
      .container{width:min(var(--max),calc(100% - 28px))}
      .paper-body{padding:22px}
    }
  </style>
</head>
<body>
  <header class="site-header">
    <div class="container nav-wrap">
      <a class="brand" href="../index.html" aria-label="Home">
        <img src="../images/cropped-new-Stop-Child-Cruelty-Trust-2024.png" alt="Stop Child Cruelty Trust logo">
        <span>Stop Child Cruelty Trust</span>
      </a>
      <button class="nav-toggle" type="button" aria-expanded="false" aria-controls="site-nav" aria-label="Open menu"><span></span><span></span><span></span></button>
      <nav class="site-nav" id="site-nav" aria-label="Site sections">
        ${navLinks.map(([label, href], index) => `<a${index === 0 ? ' class="home-link"' : ''} href="${href}">${label}</a>`).join('\n        ')}
        <a class="donate-link" href="../index.html#donate">Donate</a>
      </nav>
    </div>
  </header>

  <main>
    <section class="hero">
      <div class="container hero-grid">
        <div class="hero-panel">
          <span class="eyebrow">News Placeholder</span>
          <h1>${escapeHtml(title)}</h1>
          <p>${escapeHtml(summary)}</p>
          <div class="hero-meta">Placeholder page / News / SCCT</div>
        </div>
      </div>
    </section>

    <section class="detail-band">
      <div class="container">
        <article class="paper">
          <div class="paper-body">
            <h2>Sample Text</h2>
            <p class="lead">${escapeHtml(sampleText)}</p>
          </div>
        </article>
      </div>
    </section>
  </main>

  <footer class="site-footer">
    <div class="container">
      <div class="footer-grid">
        <div>
          <h3>Stop Child Cruelty Trust</h3>
          <p>Focused on ending violence against children, especially corporal punishment, through advocacy, training, education, public awareness and national reform.</p>
        </div>
        <div>
          <h3>Menu</h3>
          <div class="footer-links">
            <a href="../index.html#about">About Us</a>
            <a href="../index.html#work">Our Work</a>
            <a href="../index.html#support">Support Us</a>
            <a href="../index.html#donate">Donate</a>
          </div>
        </div>
        <div>
          <h3>Resources</h3>
          <div class="footer-links">
            <a href="../index.html#achievements">Campaigns</a>
            <a href="../index.html#support">Child Protection Alliance</a>
            <a href="../index.html#work">Law</a>
            <a href="../index.html#contact">News and inquiries</a>
          </div>
        </div>
      </div>
      <div class="copyright">&copy; 2026 Stop Child Cruelty Trust (SCCT). Recreated as a clean single page website.</div>
      <div class="company-credit">Website by <a href="https://pageliao.com" target="_blank" rel="noopener">Pageliao Pvt Ltd</a></div>
    </div>
  </footer>

  <script>
    const toggle = document.querySelector('.nav-toggle');
    const nav = document.querySelector('#site-nav');
    if (toggle && nav) {
      toggle.addEventListener('click', () => {
        const isOpen = nav.classList.toggle('open');
        toggle.setAttribute('aria-expanded', String(isOpen));
        toggle.setAttribute('aria-label', isOpen ? 'Close menu' : 'Open menu');
      });
      nav.addEventListener('click', (event) => {
        if (event.target.closest('a')) {
          nav.classList.remove('open');
          toggle.setAttribute('aria-expanded', 'false');
          toggle.setAttribute('aria-label', 'Open menu');
        }
      });
    }
  </script>
</body>
</html>
`;

  writeFileSync(filePath, html, 'utf8');
  generatedCount += 1;
}

let rewrittenSource = sourceHtml;
for (const card of cards) {
  rewrittenSource = rewrittenSource.replace(
    new RegExp(`href="${escapeRegExp(card.href)}"`, 'g'),
    `href="ccr/${card.fileName}"`
  );
}

writeFileSync(sourcePath, rewrittenSource, 'utf8');

console.log(`Generated ${generatedCount} new placeholder pages in ${outDir}`);

function escapeRegExp(value) {
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}




