# install_mantine
# ---------------
# Instala dependencias de Mantine UI en un proyecto frontend.
# Detecta package manager por lockfile (pnpm > yarn > npm).
# Genera postcss.config.cjs si no existe.
# Idempotente: no reinstala si ya estan presentes.
#
# USO (sourced):
#   source install_mantine.sh
#   install_mantine /path/to/frontend
#
# USO (directo):
#   bash install_mantine.sh /path/to/frontend

install_mantine() {
    local project_dir="$1"

    if [ -z "$project_dir" ]; then
        echo "install_mantine: se requiere project_dir" >&2
        return 1
    fi

    if [ ! -f "$project_dir/package.json" ]; then
        echo "install_mantine: no existe package.json en $project_dir" >&2
        return 1
    fi

    # Detectar package manager
    local pm="npm"
    local add_cmd="install"
    local add_dev_flag="--save-dev"
    if [ -f "$project_dir/pnpm-lock.yaml" ] || [ -f "$project_dir/pnpm-workspace.yaml" ]; then
        pm="pnpm"
        add_cmd="add"
        add_dev_flag="-D"
    elif [ -f "$project_dir/yarn.lock" ]; then
        pm="yarn"
        add_cmd="add"
        add_dev_flag="--dev"
    elif [ -f "$project_dir/package-lock.json" ]; then
        pm="npm"
        add_cmd="install"
        add_dev_flag="--save-dev"
    fi

    echo "Detectado package manager: $pm"

    # Dependencias runtime
    local runtime_deps="@mantine/core @mantine/hooks @mantine/charts @mantine/notifications @mantine/form"
    echo "Instalando dependencias Mantine..."
    (cd "$project_dir" && $pm $add_cmd $runtime_deps 2>&1)

    if [ $? -ne 0 ]; then
        echo "install_mantine: fallo instalando dependencias runtime" >&2
        return 1
    fi

    # Dependencias PostCSS (dev)
    local dev_deps="postcss postcss-preset-mantine postcss-simple-vars"
    echo "Instalando dependencias PostCSS..."
    (cd "$project_dir" && $pm $add_cmd $add_dev_flag $dev_deps 2>&1)

    if [ $? -ne 0 ]; then
        echo "install_mantine: fallo instalando dependencias PostCSS" >&2
        return 1
    fi

    # Generar postcss.config.cjs si no existe
    if [ ! -f "$project_dir/postcss.config.cjs" ]; then
        echo "Generando postcss.config.cjs..."
        cat > "$project_dir/postcss.config.cjs" << 'POSTCSS'
module.exports = {
  plugins: {
    'postcss-preset-mantine': {},
    'postcss-simple-vars': {
      variables: {
        'mantine-breakpoint-xs': '36em',
        'mantine-breakpoint-sm': '48em',
        'mantine-breakpoint-md': '62em',
        'mantine-breakpoint-lg': '75em',
        'mantine-breakpoint-xl': '88em',
      },
    },
  },
};
POSTCSS
        echo "postcss.config.cjs creado"
    else
        echo "postcss.config.cjs ya existe, no se sobreescribe"
    fi

    echo "Mantine instalado correctamente en $project_dir"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    install_mantine "$@"
fi
