#!/usr/bin/env bash
# Consolidate the formerly-WordPress/Elementor vendor CSS into one purged, renamed file.
# - Concatenates the load-bearing CSS in the SAME order they were <link>-ed (cascade-preserving).
# - Normalizes relative ../../fonts and ../../images url() refs to absolute (location-independent).
# - PurgeCSS strips selectors not present in the rendered HTML or component source.
set -euo pipefail
cd "$(dirname "$0")/.."

OUT="public/css/site.css"
PURGED_DIR="public/css/.purged"

# Exact <link> order from the old layout.tsx <head> (cascade matters).
FILES=(
  "public/css/vendor/vendor-elementor-generated-globals.css"
  "public/css/vendor/vendor-elementor-base.css"
  "public/css/vendor/vendor-elementor-custom.min.css"
  "public/css/vendor/vendor-theme-core.css"
  "public/css/vendor/vendor-global-overrides.css"
  "public/css/vendor/vendor-layout-main.css"
  "public/css/vendor/vendor-responsive-laptops.css"
  "public/css/vendor/vendor-elementor-hfe.css"
  "public/css/vendor/vendor-icons-fontello-load.css"
  "public/css/vendor/vendor-icons-fontello.css"
  "public/css/custom-frontend.min.css"
  "public/css/all-inlined-head-styles.css"
)

: > "$OUT"
for f in "${FILES[@]}"; do
  printf '\n/* === %s === */\n' "$f" >> "$OUT"
  cat "$f" >> "$OUT"
done

# Normalize relative asset paths so the combined file works from any location.
sed -i '' -E 's#\.\./\.\./fonts/#/fonts/#g; s#\.\./\.\./images/#/images/#g' "$OUT"

RAW_BYTES=$(wc -c < "$OUT" | tr -d ' ')

# Purge (config points css: ['public/css/site.css']); output keeps the basename.
rm -rf "$PURGED_DIR"
npx purgecss --config purgecss.config.cjs --output "$PURGED_DIR"
mv "$PURGED_DIR/site.css" "$OUT"
rm -rf "$PURGED_DIR"

PURGED_BYTES=$(wc -c < "$OUT" | tr -d ' ')
echo "---"
echo "Raw combined:  $RAW_BYTES bytes"
echo "After purge:   $PURGED_BYTES bytes -> $OUT"
