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

const rootDir = path.join(__dirname, '..');
const inputPath = path.join(rootDir, 'docs', 'WHITEPAPER.md');
const outputPath = path.join(rootDir, 'docs', 'WHITEPAPER.html');

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

function renderInline(value) {
  return escapeHtml(value)
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
}

function slugify(value) {
  return String(value)
    .toLowerCase()
    .replace(/[^a-z0-9가-힣]+/g, '-')
    .replace(/^-+|-+$/g, '') || 'section';
}

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

  function closeList() {
    if (inList) {
      html.push('</ul>');
      inList = false;
    }
  }

  function closeCode() {
    if (inCode) {
      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;
    }

    if (/^#\s+/.test(line)) {
      closeList();
      const text = line.replace(/^#\s+/, '').trim();
      html.push(`<h1 id="${slugify(text)}">${renderInline(text)}</h1>`);
      continue;
    }

    if (/^##\s+/.test(line)) {
      closeList();
      const text = line.replace(/^##\s+/, '').trim();
      const id = slugify(text);
      toc.push({ id, text });
      html.push(`<h2 id="${id}">${renderInline(text)}</h2>`);
      continue;
    }

    if (/^###\s+/.test(line)) {
      closeList();
      const text = line.replace(/^###\s+/, '').trim();
      html.push(`<h3 id="${slugify(text)}">${renderInline(text)}</h3>`);
      continue;
    }

    if (/^-\s+/.test(line)) {
      if (!inList) {
        html.push('<ul>');
        inList = true;
      }
      html.push(`<li>${renderInline(line.replace(/^-\s+/, '').trim())}</li>`);
      continue;
    }

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

    closeList();
    html.push(`<p>${renderInline(line.trim())}</p>`);
  }

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

const markdown = fs.readFileSync(inputPath, 'utf8');
const rendered = renderMarkdown(markdown);
const updatedAt = new Date().toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' });

const html = `<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AISFOR-CHAIN Whitepaper</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; }

      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;
        text-transform: uppercase;
      }

      h1 {
        margin: 0;
        font-size: clamp(34px, 5vw, 58px);
        line-height: 1.04;
        letter-spacing: 0;
      }

      .meta {
        flex: 0 0 auto;
        padding: 12px 14px;
        border: 1px solid rgba(25, 185, 129, 0.38);
        border-radius: 8px;
        background: rgba(25, 185, 129, 0.12);
        color: #c9ffe8;
        font-weight: 700;
      }

      .header-actions {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 10px;
        flex-wrap: wrap;
      }

      .lang-button {
        min-height: 42px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 10px 14px;
        border: 1px solid rgba(47, 125, 246, 0.58);
        border-radius: 8px;
        background: rgba(47, 125, 246, 0.18);
        color: #eef6ff;
        font-weight: 800;
        text-decoration: none;
      }

      .lang-button:hover {
        background: rgba(47, 125, 246, 0.28);
      }

      .layout {
        display: grid;
        grid-template-columns: 280px minmax(0, 1fr);
        gap: 20px;
        align-items: start;
      }

      nav {
        position: sticky;
        top: 18px;
        border: 1px solid rgba(255, 255, 255, 0.12);
        border-radius: 8px;
        background: rgba(15, 32, 56, 0.86);
        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, 0.08);
        color: #cfe0f7;
        font-size: 13px;
        text-decoration: none;
      }

      nav a:hover { color: #ffffff; }

      article {
        border-radius: 8px;
        background: var(--paper);
        color: var(--ink);
        padding: clamp(22px, 4vw, 54px);
        box-shadow: 0 24px 64px rgba(0, 0, 0, 0.3);
      }

      article h1 {
        color: #0a1628;
        padding-bottom: 18px;
        border-bottom: 2px solid var(--line);
      }

      article h2 {
        margin: 34px 0 14px;
        padding-top: 4px;
        color: #0d2440;
        font-size: 25px;
        letter-spacing: 0;
      }

      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 {
        margin: 10px 0 18px;
        padding-left: 22px;
      }

      article li { margin: 6px 0; }

      code {
        padding: 2px 6px;
        border-radius: 6px;
        background: #eaf1fb;
        color: #0f4f8f;
        font-family: Consolas, "Courier New", monospace;
        font-size: 0.92em;
      }

      pre {
        overflow-x: auto;
        padding: 16px;
        border-radius: 8px;
        background: #0d1728;
        color: #d8e8ff;
      }

      pre code {
        padding: 0;
        background: transparent;
        color: inherit;
      }

      .back {
        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; }
      }
    </style>
  </head>
  <body>
    <main class="shell">
      <header>
        <div>
          <p class="eyebrow">AISFOR-CHAIN</p>
          <h1>Whitepaper</h1>
        </div>
        <div class="header-actions">
          <a class="lang-button" href="./WHITEPAPER_KO.html">한국어로 보기</a>
          <div class="meta">Updated ${escapeHtml(updatedAt)}</div>
        </div>
      </header>
      <div class="layout">
        <nav aria-label="Table of contents">
          <h2>목차</h2>
          ${rendered.toc.map((item) => `<a href="#${item.id}">${renderInline(item.text)}</a>`).join('\n          ')}
        </nav>
        <article>
          ${rendered.body}
        </article>
      </div>
      <a class="back" href="./WHITEPAPER.md">Markdown 원본 보기</a>
    </main>
  </body>
</html>
`;

fs.writeFileSync(outputPath, html, 'utf8');
console.log(JSON.stringify({ ok: true, inputPath, outputPath }, null, 2));
