/**
 * Jalpi Page Builder — esbuild script
 *
 * Outputs the same four artefacts as the old @wordpress/scripts build:
 *   build/index.js          — bundled editor JS
 *   build/index.css         — extracted editor CSS
 *   build/index-rtl.css     — RTL variant of the CSS
 *   build/index.asset.php   — WordPress dependency manifest
 *
 * Usage:
 *   node build.js           — production build (minified, no source maps)
 *   node build.js --watch   — development watch (unminified, inline source maps)
 */

'use strict';

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

const isWatch = process.argv.includes('--watch');

// ---------------------------------------------------------------------------
// WordPress global mappings
// React, ReactDOM, and ReactJSXRuntime are loaded by WordPress core.
// We must NOT bundle them — instead we point esbuild at the window globals.
// ---------------------------------------------------------------------------
const WP_GLOBALS = {
  'react':              'React',
  'react-dom':          'ReactDOM',
  'react-dom/client':   'ReactDOM',
  'react/jsx-runtime':  'ReactJSXRuntime',
};

function wpGlobalsPlugin(globals) {
  const escaped = Object.keys(globals).map(k =>
    k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  );
  const filter = new RegExp('^(' + escaped.join('|') + ')$');

  return {
    name: 'wp-globals',
    setup(build) {
      build.onResolve({ filter }, args => ({
        path:      args.path,
        namespace: 'wp-globals',
      }));
      build.onLoad({ filter: /.*/, namespace: 'wp-globals' }, args => ({
        contents: `module.exports = window.${globals[args.path]};`,
        loader:   'js',
      }));
    },
  };
}

// ---------------------------------------------------------------------------
// esbuild options
// ---------------------------------------------------------------------------
const BUILD_OPTIONS = {
  entryPoints: [path.resolve(__dirname, 'src/index.tsx')],
  bundle:      true,
  outfile:     path.resolve(__dirname, 'build/index.js'),
  format:      'iife',
  platform:    'browser',
  target:      ['es2020'],
  jsx:         'automatic',
  plugins:     [wpGlobalsPlugin(WP_GLOBALS)],
  minify:      !isWatch,
  sourcemap:   isWatch ? 'inline' : false,
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function generateAssetFile() {
  const js      = fs.readFileSync(path.resolve(__dirname, 'build/index.js'));
  const version = crypto.createHash('md5').update(js).digest('hex').slice(0, 20);
  // Mirror the dependency list that @wordpress/dependency-extraction-webpack-plugin
  // produced from the same source (confirmed in the existing build/index.asset.php).
  const deps    = ['react', 'react-dom', 'react-jsx-runtime'];
  const php     = `<?php return array('dependencies' => array(${
    deps.map(d => `'${d}'`).join(', ')
  }), 'version' => '${version}');`;
  fs.writeFileSync(path.resolve(__dirname, 'build/index.asset.php'), php);
}

function generateRtlCss() {
  const src = path.resolve(__dirname, 'build/index.css');
  const dst = path.resolve(__dirname, 'build/index-rtl.css');

  if (!fs.existsSync(src)) return;

  try {
    const rtlcss = require('rtlcss');
    const css    = fs.readFileSync(src, 'utf8');
    fs.writeFileSync(dst, rtlcss.process(css));
  } catch {
    // rtlcss unavailable — copy LTR file as fallback so the handle always exists
    fs.copyFileSync(src, dst);
  }
}

// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------

async function runBuild() {
  const start = Date.now();
  await esbuild.build(BUILD_OPTIONS);
  generateAssetFile();
  generateRtlCss();
  console.log(`[jalpi-page-builder] build complete in ${Date.now() - start}ms`);
}

async function runWatch() {
  const ctx = await esbuild.context({
    ...BUILD_OPTIONS,
    plugins: [
      wpGlobalsPlugin(WP_GLOBALS),
      {
        // Regenerate asset file and RTL CSS on every rebuild
        name: 'post-build',
        setup(build) {
          build.onEnd(result => {
            if (result.errors.length === 0) {
              generateAssetFile();
              generateRtlCss();
              console.log(`[jalpi-page-builder] rebuilt — ${new Date().toLocaleTimeString()}`);
            }
          });
        },
      },
    ],
  });
  await ctx.watch();
  console.log('[jalpi-page-builder] watching for changes…  (Ctrl+C to stop)');
}

if (isWatch) {
  runWatch().catch(err => { console.error(err); process.exit(1); });
} else {
  runBuild().catch(err => { console.error(err); process.exit(1); });
}
