const url = require('url');
const path = require('path');
const { fileURLToPath, pathToFileURL } = url;
const fs = require('fs');

const colors = require('tailwindcss/colors');
const Color = require('color');

function appendForwardSlash(path) {
  return path.endsWith('/') ? path : path + '/';
}

const root = pathToFileURL(path.resolve(process.cwd(), '../..'));
// Append forward slash to compute relative paths
root.href = appendForwardSlash(root.href);

let hasTWConfig = false;

try {
  if (fs.existsSync(fileURLToPath(new URL('./tailwind.config.cjs', root)))) {
    console.log('tailwind.config.cjs found');
    hasTWConfig = true;
  }
} catch {
  console.error('tailwind.config.cjs not found');
}

const parentTWConfig = hasTWConfig
  ? require(fileURLToPath(new URL('./tailwind.config.cjs', root)))
  : false;

function createColorObject(defaultColor) {
  const weights = [
    10, 20, 30, 40, 50, 100, 200, 300, 400, 500, 600, 700, 800, 850, 900, 950,
  ];
  const lightnessWeights = weights.map((w) => 100 - w * 0.1);

  let colorObj = {
    DEFAULT: defaultColor,
  };

  for (let i = 0; i < weights.length; ++i) {
    let hsl = Color(defaultColor).hsl();
    hsl.color[2] = lightnessWeights[i];
    colorObj[weights[i]] = Color(hsl).hex().toString();
  }

  return colorObj;
}

const ePrimary = createColorObject('#2563EB');
const eSecondary = createColorObject('#6CA7EE');
const eGray = createColorObject('#e6e9ec');

/** @type {import('tailwindcss').Config} */
module.exports = {
  ...parentTWConfig,
  darkMode: 'media',
  content: [
    './index.html',
    './src/**/*.{js,ts,jsx,tsx}',
    '../src/**/*.{js,ts,jsx,tsx,astro}',
  ],
  theme: {
    ...(parentTWConfig ? parentTWConfig.theme : {}),
    extend: {
      ...(parentTWConfig ? parentTWConfig.theme.extend : {}),
      fontFamily: {
        ...(parentTWConfig ? parentTWConfig.theme.extend.fontFamily : {}),
        editor: ['Inter', 'sans-serif'],
        brand: ['Lexend', 'sans-serif'],
      },
      colors: {
        ...(parentTWConfig ? parentTWConfig.theme.extend.colors : {}),
        gray: colors.gray,
        ePrimary,
        eSecondary,
        eGray,
      },
      borderWidth: {
        ...(parentTWConfig ? parentTWConfig.theme.extend.borderWidth : {}),
        1.5: '1.5px',
      },
      fontSize: {
        ...(parentTWConfig ? parentTWConfig.theme.extend.fontSize : {}),
        '2xs': '0.625rem',
      },
    },
  },
  plugins: [
    ...(parentTWConfig ? parentTWConfig.plugins : []),
    require('@tailwindcss/forms'),
  ],
};
