/**
 * patch-all.js
 * Tự động vá toàn bộ file HTML trong thư mục output:
 *   1. Fix mobile menu (thêm dropdown)
 *   2. Fix opacity:0 animation
 *   3. Fix blur placeholder ảnh
 *   4. Ẩn cookie banner
 *   5. Đổi màu nền sang xanh đen
 *
 * Dùng: node patch-all.js [thư mục]
 * Ví dụ: node patch-all.js ./output
 */

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

const OUT_DIR = process.argv[2] || './output';

// ── Tìm tất cả file HTML đệ quy ─────────────────────────────────────────
function findHTML(dir, list = []) {
  if (!fs.existsSync(dir)) return list;
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) findHTML(full, list);
    else if (entry.name.endsWith('.html')) list.push(full);
  }
  return list;
}

// ════════════════════════════════════════════════════════════════════════
//  DANH SÁCH CÁC PATCH — thêm/xoá tuỳ ý
// ════════════════════════════════════════════════════════════════════════
const PATCHES = [

//   // ── 1. Fix mobile menu button → thêm onclick + id cho chevron ─────────
//   {
//     name: 'Mobile menu button',
//     // Tìm nút Menu gốc (không có onclick)
//     find: /<div class="lg:hidden">\s*<button\s+type="button"\s+class="flex items-center justify-end h-8[^"]*"[^>]*>Menu<svg[^>]*class="lucide lucide-chevron-down[^"]*"[^>]*><path d="m6 9 6 6 6-6"><\/path><\/svg><\/button>\s*<\/div>/s,
//     replace: `<div class="lg:hidden">
//   <button type="button"
//     onclick="var m=document.getElementById('mobile-nav-menu');var icon=document.getElementById('menu-chevron');if(m.style.display==='none'||m.style.display===''){m.style.display='block';icon.style.transform='rotate(180deg)';}else{m.style.display='none';icon.style.transform='rotate(0deg)';}"
//     class="flex items-center justify-end h-8 gap-2 pl-3 py-2 text-sm duration-150 text-white/60 hover:text-white/80">
//     Menu
//     <svg id="menu-chevron" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down w-4 h-4 relative top-[1px]" style="transition:transform 0.2s ease;">
//       <path d="m6 9 6 6 6-6"></path>
//     </svg>
//   </button>
// </div>`,
//   },

//   // ── 2. Thêm dropdown menu ngay trước </nav> ────────────────────────────
//   {
//     name: 'Mobile dropdown menu',
//     // Chỉ thêm nếu chưa có (kiểm tra id)
//     skipIf: (html) => html.includes('id="mobile-nav-menu"'),
//     find: /<\/nav>/,
//     replace: `  <!-- MOBILE DROPDOWN MENU -->
//   <div id="mobile-nav-menu" style="display:none;" class="lg:hidden">
//     <div style="background:rgba(0,0,0,0.96);border-top:1px solid rgba(255,255,255,0.08);padding:8px 0 16px;">
//       <a href="/about" style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;color:rgba(255,255,255,0.75);text-decoration:none;font-size:15px;border-bottom:1px solid rgba(255,255,255,0.05);">Giới thiệu <span style="color:rgba(255,255,255,0.3)">›</span></a>
//       <a href="https://portal.vietnix.vn/aff.php?aff=2857&url=https://vietnix.vn/vps-gia-re/" target="_blank" style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;color:rgba(255,255,255,0.75);text-decoration:none;font-size:15px;border-bottom:1px solid rgba(255,255,255,0.05);">Hạ tầng <span style="color:rgba(255,255,255,0.3)">›</span></a>
//       <a href="/blog" style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;color:rgba(255,255,255,0.75);text-decoration:none;font-size:15px;border-bottom:1px solid rgba(255,255,255,0.05);">Blog <span style="color:rgba(255,255,255,0.3)">›</span></a>
//       <a href="https://zalo.me/0829091871" target="_blank" style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;color:rgba(255,255,255,0.75);text-decoration:none;font-size:15px;border-bottom:1px solid rgba(255,255,255,0.05);">Hỗ trợ <span style="color:rgba(255,255,255,0.3)">›</span></a>
//       <div style="padding:16px 20px 4px;display:flex;flex-direction:column;gap:10px;">
//         <a href="/pricing" style="display:block;text-align:center;padding:12px;border:1px solid rgba(255,255,255,0.2);border-radius:8px;color:rgba(255,255,255,0.8);font-size:14px;text-decoration:none;">🎮 Thiết kế Web Game</a>
//         <a href="/templates" style="display:block;text-align:center;padding:12px;background:white;border-radius:8px;color:black;font-size:14px;font-weight:700;text-decoration:none;">Server Game →</a>
//       </div>
//     </div>
//   </div>
// </nav>`,
//   },
  {
  name: 'Fix nav background',
  fn: (html) => {
    return html.replace(
      /(<nav[^>]*style=["'][^"']*?)background-color:\s*rgba\(0,\s*0,\s*0,\s*0(?:\.0+)?\d*\)([^"']*["'])/gi,
      '$1background-color: rgba(10, 15, 26, 0.95)$2'
    ).replace(
      /(<nav[^>]*style=["'][^"']*?)border-color:\s*rgba\(255,\s*255,\s*255,\s*0(?:\.00\d+)?\)([^"']*["'])/gi,
      '$1border-color: rgba(255, 255, 255, 0.1)$2'
    );
  },
},

];

// ════════════════════════════════════════════════════════════════════════
//  CHẠY PATCHES
// ════════════════════════════════════════════════════════════════════════
function applyPatches(html, filePath) {
  const results = [];

  for (const patch of PATCHES) {
    // Skip nếu điều kiện skipIf thoả
    if (patch.skipIf && patch.skipIf(html)) {
      results.push(`  ⏭  ${patch.name} (bỏ qua)`);
      continue;
    }

    const before = html;

    if (patch.fn) {
      // Patch dùng function tùy chỉnh
      html = patch.fn(html);
    } else if (patch.find) {
      // Patch dùng find/replace
      html = html.replace(patch.find, patch.replace);
    }

    const changed = html !== before;
    results.push(`  ${changed ? '✓' : '–'} ${patch.name}`);
  }

  return { html, results };
}

// ── Main ─────────────────────────────────────────────────────────────────
const files = findHTML(OUT_DIR);
if (files.length === 0) {
  console.error('❌ Không tìm thấy file HTML trong:', OUT_DIR);
  process.exit(1);
}

console.log(`\n🔧 Patching ${files.length} file HTML...\n`);

let totalChanged = 0;

for (const filePath of files) {
  const rel = path.relative(OUT_DIR, filePath);
  const original = fs.readFileSync(filePath, 'utf-8');
  const { html, results } = applyPatches(original, filePath);

  const changed = html !== original;
  if (changed) {
    fs.writeFileSync(filePath, html, 'utf-8');
    totalChanged++;
  }

  console.log(`📄 ${rel} ${changed ? '(đã sửa)' : '(không thay đổi)'}`);
  results.forEach(r => console.log(r));
  console.log('');
}

console.log('═'.repeat(50));
console.log(`✅ Hoàn tất! Đã sửa ${totalChanged}/${files.length} file.`);
console.log('\nMở kết quả: npx serve', OUT_DIR);