#!/bin/bash
# Patch vendor JS files to fix Firefox beta parser bugs.
# Re-applied automatically after composer install/update.

set -e

# 1. Copy Livewire JS to public/ for static serving (bypasses PHP which causes Firefox issues)
LIVEWIRE_SRC="vendor/livewire/livewire/dist/livewire.js"
LIVEWIRE_DST="public/livewire-dev.js"

if [ -f "$LIVEWIRE_SRC" ]; then
    cp "$LIVEWIRE_SRC" "$LIVEWIRE_DST"
    echo "  [patch] Copied $LIVEWIRE_SRC -> $LIVEWIRE_DST"
else
    echo "  [patch] WARNING: $LIVEWIRE_SRC not found, skipping"
fi

# 2. Add trailing newline to WireUI JS if missing (Firefox beta requires it)
WIREUI_JS="vendor/wireui/wireui/dist/wireui.js"

if [ -f "$WIREUI_JS" ]; then
    LAST_BYTE=$(tail -c1 "$WIREUI_JS" | xxd -p)
    if [ "$LAST_BYTE" != "0a" ]; then
        echo "" >> "$WIREUI_JS"
        echo "  [patch] Added trailing newline to $WIREUI_JS"
    else
        echo "  [patch] $WIREUI_JS already has trailing newline"
    fi
else
    echo "  [patch] WARNING: $WIREUI_JS not found, skipping"
fi
