// Optimize images
'use strict';

import { dest, src } from 'gulp';
import { config } from '../config.mjs';
import notify from 'gulp-notify';

const optimizeImages = async (callback) => {
  // Dynamically import imagemin and its plugins.
  const imageminModule = await import('gulp-imagemin');
  // gulp-imagemin often has a default export for the main function.
  const imagemin = imageminModule.default;
  // Optimizers like mozjpeg, optipng, svgo are often named exports.
  const { mozjpeg, optipng, svgo } = imageminModule;

  return src(config.images.src, { encoding: false })
    .pipe(imagemin([
      mozjpeg({ optimizationLevel: 2 }),
      optipng({ progressive: true }),
      svgo(
        { removeUselessDefs: false },
        { cleanupIDs: false },
        { removeXMLNS: false },
        { removeViewBox: false },
      ),
    ]))
    .on('error', function (err) {
      notify(err);
      callback();
    })
    .pipe(dest(config.images.dest, { encoding: false }))
    .on('end', () => {
      notify('Images optimized');
    });
};

export const images = optimizeImages;
