// Shrinks the base64-embedded raster inside "fake" SVGs (icons displayed small).
// Keeps the .svg filename and wrapper so no code references change.
const fs = require('fs');
const path = require('path');
const sharp = require(path.join(process.cwd(), 'node_modules', 'sharp'));

const DIR = path.join(process.cwd(), 'public', 'images');
const TARGETS = ['figma_icon.svg', 'laravel_icon.svg', 'nextjs_icon.svg', 'flutter_icon.svg',
                 'service_vactore_1.svg','service_vactore_2.svg','service_vactore_3.svg',
                 'service_vactore_4.svg','service_vactore_5.svg','service_vactore_6.svg'];
const MAX = 320; // icons render <=100px; 320 covers retina

async function run() {
  for (const name of TARGETS) {
    const fp = path.join(DIR, name);
    if (!fs.existsSync(fp)) continue;
    const before = fs.statSync(fp).size;
    let svg = fs.readFileSync(fp, 'utf8');
    const re = /data:image\/(png|jpeg|jpg|webp);base64,([A-Za-z0-9+/=]+)/g;
    let m, replaced = 0, out = svg;
    while ((m = re.exec(svg)) !== null) {
      const buf = Buffer.from(m[2], 'base64');
      try {
        const meta = await sharp(buf).metadata();
        const longest = Math.max(meta.width || 0, meta.height || 0);
        const pipe = sharp(buf);
        if (longest > MAX) pipe.resize({ width: meta.width >= meta.height ? MAX : null,
                                          height: meta.height > meta.width ? MAX : null,
                                          withoutEnlargement: true });
        const webp = await pipe.webp({ quality: 78 }).toBuffer();
        const newData = `data:image/webp;base64,${webp.toString('base64')}`;
        out = out.replace(m[0], newData);
        replaced++;
      } catch (e) { console.log(`  raster skip in ${name}: ${e.message}`); }
    }
    if (replaced) {
      fs.writeFileSync(fp, out);
      const after = fs.statSync(fp).size;
      console.log(`${(before/1024).toFixed(0)}KB -> ${(after/1024).toFixed(0)}KB  ${name}`);
    }
  }
}
run();
