// Regenerates the shared <header>...</header> and <footer>...</footer>
// (+ cookie banner + back-to-top button) blocks in every page from the
// templates in templates/header.{lang}.html and templates/footer.{lang}.html.
//
// Usage: node sync-partials.js
//
// Edit the header/footer for a language ONCE in its template file, then run
// this script — it patches all pages in that language (root, contactos,
// produtos, and the 3 legal pages) automatically. Page-specific content
// (everything between </div id="navBackdrop"> and <footer>) is left untouched.
//
// After running, just deploy the site as usual (nothing else changes).

const fs = require('fs');
const path = require('path');

const ROOT_DIR = __dirname;

const PAGE_TYPES = [
  { dir: '', activeKey: 'home' },
  { dir: 'contactos/', activeKey: 'contactos' },
  { dir: 'produtos/', activeKey: 'services' },
  { dir: 'legal/politica-de-privacidade/', activeKey: 'none' },
  { dir: 'legal/termos-e-condicoes/', activeKey: 'none' },
  { dir: 'legal/resolucao-alternativa-de-litigios/', activeKey: 'none' },
];

const LANGS = ['pt', 'en', 'fr'];
const LANG_OFFSET = { pt: 0, en: 1, fr: 1 };

function depthOf(dir) {
  return dir === '' ? 0 : dir.split('/').filter(Boolean).length;
}

function relPrefix(n) {
  return n === 0 ? './' : '../'.repeat(n);
}

function crossLangHref(pageType, fromLang, toLang, root) {
  if (toLang === fromLang) return './';
  const langFolder = toLang === 'pt' ? '' : `${toLang}/`;
  return `${root}${langFolder}${pageType.dir}`;
}

function readTemplate(kind, lang) {
  return fs.readFileSync(path.join(ROOT_DIR, 'templates', `${kind}.${lang}.html`), 'utf8');
}

function fillTokens(template, tokens) {
  let out = template;
  for (const [key, value] of Object.entries(tokens)) {
    out = out.split(`{{${key}}}`).join(value);
  }
  return out;
}

function patchFile(filePath, headerHtml, footerHtml) {
  let content = fs.readFileSync(filePath, 'utf8');

  const headerRegex = /<header class="header" id="header">[\s\S]*?<div class="nav-backdrop" id="navBackdrop"><\/div>/;
  const footerRegex = /<footer class="footer">[\s\S]*?id="backToTop"[\s\S]*?<\/button>/;

  if (!headerRegex.test(content)) throw new Error(`Header block not found in ${filePath}`);
  if (!footerRegex.test(content)) throw new Error(`Footer block not found in ${filePath}`);

  content = content.replace(headerRegex, headerHtml.trimEnd());
  content = content.replace(footerRegex, footerHtml.trimEnd());

  fs.writeFileSync(filePath, content, 'utf8');
}

function main() {
  const headerTemplates = Object.fromEntries(LANGS.map(l => [l, readTemplate('header', l)]));
  const footerTemplates = Object.fromEntries(LANGS.map(l => [l, readTemplate('footer', l)]));

  let count = 0;

  for (const lang of LANGS) {
    for (const pageType of PAGE_TYPES) {
      const d = depthOf(pageType.dir);
      const root = relPrefix(d + LANG_OFFSET[lang]);
      const home = relPrefix(d);

      const tokens = {
        ROOT: root,
        HOME: home,
        ACTIVE_HOME: pageType.activeKey === 'home' ? ' is-active' : '',
        ACTIVE_SERVICES: pageType.activeKey === 'services' ? ' is-active' : '',
        ACTIVE_CONTACTOS: pageType.activeKey === 'contactos' ? ' is-active' : '',
        HREF_PT: crossLangHref(pageType, lang, 'pt', root),
        HREF_EN: crossLangHref(pageType, lang, 'en', root),
        HREF_FR: crossLangHref(pageType, lang, 'fr', root),
      };

      const headerHtml = fillTokens(headerTemplates[lang], tokens);
      const footerHtml = fillTokens(footerTemplates[lang], tokens);

      const langFolder = lang === 'pt' ? '' : `${lang}/`;
      const filePath = path.join(ROOT_DIR, langFolder, pageType.dir, 'index.html');

      if (!fs.existsSync(filePath)) {
        console.warn(`SKIP (not found): ${filePath}`);
        continue;
      }

      patchFile(filePath, headerHtml, footerHtml);
      console.log(`updated: ${path.relative(ROOT_DIR, filePath)}`);
      count++;
    }
  }

  console.log(`\nDone — ${count} pages synced from templates/.`);
}

main();
