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

const rootDir = path.join(__dirname, '..');
const documentVersion = '0.4';
const documentDate = '2026-08-04';

const documents = [
  {
    lang: 'en',
    input: 'WHITEPAPER.md',
    output: 'WHITEPAPER.html',
    pageTitle: 'PLAIS Chain Whitepaper',
    eyebrow: 'PLAIS CHAIN',
    heading: 'Whitepaper',
    tocLabel: 'Contents',
    alternateLabel: '한국어',
    alternateHref: '/whitepaper/ko',
    markdownHref: '/whitepaper.md',
    markdownLabel: 'View Markdown source'
  },
  {
    lang: 'ko',
    input: 'WHITEPAPER_KO.md',
    output: 'WHITEPAPER_KO.html',
    pageTitle: 'PLAIS Chain 한국어 백서',
    eyebrow: 'PLAIS CHAIN',
    heading: '한국어 백서',
    tocLabel: '목차',
    alternateLabel: 'English',
    alternateHref: '/whitepaper',
    markdownHref: '/whitepaper/ko.md',
    markdownLabel: 'Markdown 원본 보기'
  }
];

function escapeHtml(value) {
  return String(value)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function renderInline(value) {
  return escapeHtml(value)
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" rel="noreferrer">$1</a>');
}

function slugify(value) {
  return String(value)
    .normalize('NFC')
    .toLowerCase()
    .replace(/[^\p{L}\p{N}]+/gu, '-')
    .replace(/^-+|-+$/g, '') || 'section';
}

function renderMarkdown(markdown) {
  const lines = markdown.replace(/\r\n/g, '\n').split('\n');
  const html = [];
  const toc = [];
  let listType = '';
  let inCode = false;
  let codeLines = [];

  function closeList() {
    if (listType) {
      html.push(`</${listType}>`);
      listType = '';
    }
  }

  function openList(type) {
    if (listType === type) return;
    closeList();
    html.push(`<${type}>`);
    listType = type;
  }

  function closeCode() {
    if (!inCode) return;
    html.push(`<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`);
    codeLines = [];
    inCode = false;
  }

  for (const line of lines) {
    if (line.startsWith('```')) {
      if (inCode) closeCode();
      else {
        closeList();
        inCode = true;
        codeLines = [];
      }
      continue;
    }

    if (inCode) {
      codeLines.push(line);
      continue;
    }

    const heading = line.match(/^(#{1,3})\s+(.+)$/);
    if (heading) {
      closeList();
      const level = heading[1].length;
      const headingText = heading[2].trim();
      const id = slugify(headingText);
      if (level === 2) toc.push({ id, text: headingText });
      html.push(`<h${level} id="${id}">${renderInline(headingText)}</h${level}>`);
      continue;
    }

    const unordered = line.match(/^[-*]\s+(.+)$/);
    if (unordered) {
      openList('ul');
      html.push(`<li>${renderInline(unordered[1].trim())}</li>`);
      continue;
    }

    const ordered = line.match(/^\d+[.)]\s+(.+)$/);
    if (ordered) {
      openList('ol');
      html.push(`<li>${renderInline(ordered[1].trim())}</li>`);
      continue;
    }

    if (!line.trim()) {
      closeList();
      continue;
    }

    closeList();
    if (line.startsWith('> ')) html.push(`<blockquote>${renderInline(line.slice(2).trim())}</blockquote>`);
    else html.push(`<p>${renderInline(line.trim())}</p>`);
  }

  closeCode();
  closeList();
  return { body: html.join('\n'), toc };
}

function buildPage(config) {
  const inputPath = path.join(rootDir, 'docs', config.input);
  const outputPath = path.join(rootDir, 'docs', config.output);
  const rendered = renderMarkdown(fs.readFileSync(inputPath, 'utf8'));
  const html = `<!doctype html>
<html lang="${config.lang}">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="PLAI Chain candidate-network architecture, asset policy, security controls, risks, and launch gates.">
    <title>${escapeHtml(config.pageTitle)}</title>
    <style>
      :root {
        color-scheme: dark;
        --bg: #08111f;
        --panel: #0f2038;
        --paper: #f8fbff;
        --ink: #172033;
        --muted: #607089;
        --line: #d9e3f2;
        --accent: #19b981;
        --accent-2: #2f7df6;
      }
      * { box-sizing: border-box; }
      html { scroll-behavior: smooth; }
      body {
        margin: 0;
        font-family: "Malgun Gothic", "Apple SD Gothic Neo", system-ui, sans-serif;
        background:
          linear-gradient(125deg, rgba(25, 185, 129, 0.16), transparent 32%),
          linear-gradient(145deg, transparent 48%, rgba(47, 125, 246, 0.16)),
          var(--bg);
        color: var(--paper);
      }
      .shell { width: min(1180px, calc(100% - 32px)); margin: 0 auto; padding: 36px 0 48px; }
      header { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 24px; }
      .eyebrow { margin: 0 0 8px; color: #9fdcbc; font-size: 13px; font-weight: 800; letter-spacing: .12em; }
      header h1 { margin: 0; font-size: clamp(34px, 5vw, 58px); line-height: 1.04; }
      .header-actions { display: flex; align-items: center; justify-content: flex-end; gap: 10px; flex-wrap: wrap; }
      .meta, .button {
        min-height: 42px;
        display: inline-flex;
        align-items: center;
        padding: 10px 14px;
        border-radius: 8px;
        font-weight: 800;
      }
      .meta { border: 1px solid rgba(25, 185, 129, .38); background: rgba(25, 185, 129, .12); color: #c9ffe8; }
      .button { border: 1px solid rgba(47, 125, 246, .58); background: rgba(47, 125, 246, .18); color: #eef6ff; text-decoration: none; }
      .button:hover { background: rgba(47, 125, 246, .3); }
      .layout { display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 20px; align-items: start; }
      nav { position: sticky; top: 18px; max-height: calc(100vh - 36px); overflow-y: auto; border: 1px solid rgba(255, 255, 255, .12); border-radius: 8px; background: rgba(15, 32, 56, .92); padding: 16px; }
      nav h2 { margin: 0 0 12px; font-size: 16px; }
      nav a { display: block; padding: 8px 0; border-top: 1px solid rgba(255, 255, 255, .08); color: #cfe0f7; font-size: 13px; text-decoration: none; }
      nav a:hover { color: #fff; }
      article { border-radius: 8px; background: var(--paper); color: var(--ink); padding: clamp(22px, 4vw, 54px); box-shadow: 0 24px 64px rgba(0, 0, 0, .3); }
      article h1 { margin: 0; padding-bottom: 18px; border-bottom: 2px solid var(--line); color: #0a1628; font-size: clamp(32px, 5vw, 52px); }
      article h2 { margin: 38px 0 14px; padding-top: 4px; color: #0d2440; font-size: 25px; }
      article h3 { margin: 26px 0 10px; color: #163a62; font-size: 19px; }
      article p, article li { color: #26364d; font-size: 16px; line-height: 1.72; }
      article ul, article ol { margin: 10px 0 18px; padding-left: 24px; }
      article li { margin: 6px 0; }
      article a { color: #145eb0; }
      blockquote { margin: 18px 0; padding: 12px 16px; border-left: 4px solid var(--accent); background: #eefaf6; color: #26364d; }
      code { padding: 2px 6px; border-radius: 6px; background: #eaf1fb; color: #0f4f8f; font-family: Consolas, "Courier New", monospace; font-size: .92em; }
      pre { overflow-x: auto; padding: 16px; border-radius: 8px; background: #0d1728; color: #d8e8ff; }
      pre code { padding: 0; background: transparent; color: inherit; }
      .source-link { display: inline-flex; margin-top: 20px; color: #cfe0f7; text-decoration: none; }
      @media (max-width: 900px) {
        header { display: block; }
        .header-actions { justify-content: flex-start; margin-top: 16px; }
        .layout { grid-template-columns: 1fr; }
        nav { position: static; max-height: none; }
      }
    </style>
  </head>
  <body>
    <main class="shell">
      <header>
        <div>
          <p class="eyebrow">${escapeHtml(config.eyebrow)}</p>
          <h1>${escapeHtml(config.heading)}</h1>
        </div>
        <div class="header-actions">
          <a class="button" href="${config.alternateHref}">${escapeHtml(config.alternateLabel)}</a>
          <a class="button" href="/">Chain Home</a>
          <a class="button" href="https://aisfor.kr/home">PLAIFOR Home</a>
          <div class="meta">v${documentVersion} · ${documentDate}</div>
        </div>
      </header>
      <div class="layout">
        <nav aria-label="${escapeHtml(config.tocLabel)}">
          <h2>${escapeHtml(config.tocLabel)}</h2>
          ${rendered.toc.map((item) => `<a href="#${item.id}">${renderInline(item.text)}</a>`).join('\n          ')}
        </nav>
        <article>
          ${rendered.body}
        </article>
      </div>
      <a class="source-link" href="${config.markdownHref}">${escapeHtml(config.markdownLabel)}</a>
    </main>
  </body>
</html>
`;

  fs.writeFileSync(outputPath, html, 'utf8');
  return { inputPath, outputPath, sections: rendered.toc.length };
}

const results = documents.map(buildPage);
console.log(JSON.stringify({ ok: true, version: documentVersion, documents: results }, null, 2));
