const gulp = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const cleanCSS = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const fileInclude = require('gulp-file-include');
const esbuild = require('esbuild');

// Пути
const paths = {
  scss: {
    src: 'src/scss/**/*.scss',
    dest: 'dist/css/'
  },
  js: {
    src: 'src/js/**/*.js',
    entry: 'src/js/index.js',
    dest: 'dist/js/'
  },
  html: {
    src: 'src/html/*.html',
    dest: 'dist/'
  }
};

// SCSS -> CSS
function styles() {
  return gulp.src('src/scss/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.scss.dest))
    .pipe(browserSync.stream());
}

// JS -> esbuild bundle + minify + sourcemap
function scripts(cb) {
  esbuild.build({
    entryPoints: [paths.js.entry], // только entry файл
    bundle: true,
    minify: true,
    sourcemap: true,
    outfile: paths.js.dest + 'main.js',
    target: ['es2015'],
    platform: 'browser'
  }).then(() => {
    browserSync.reload();
    cb();
  }).catch((err) => {
    console.error(err);
    cb(err);
  });
}

// HTML + partials
function html() {
  return gulp.src(paths.html.src)
    .pipe(fileInclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest(paths.html.dest))
    .pipe(browserSync.stream());
}

// Слежение и сервер
function serve() {
  browserSync.init({
    server: {
      baseDir: 'dist/'
    }
  });

  watch();
}

function watch() {
  gulp.watch(paths.scss.src, styles);
  gulp.watch('src/js/**/*.js', scripts); // следим за всеми js
  // gulp.watch('src/html/**/*.html', html);
}

// Экспорт задач
exports.default = gulp.series(
  // gulp.parallel(styles, scripts, html),
  gulp.parallel(styles, scripts),
  watch
  // serve
);
