$env:Path += ";C:\MAMP\bin\php\php8.1.0"
php -v

php artisan route:clear
php artisan config:clear
php artisan cache:clear
npm run dev

@extends('layouts.clivax')

@section('title', $method === 'PUT' ? 'Edit Shipment' : 'Create New Shipment')

@section('content')
<form id="shipmentForm" action="{{ $action }}" method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
    @csrf
    @if($method === 'PUT') @method('PUT') @endif
    <input type="hidden" id="currencyRates" value="{{ json_encode($currencyRates) }}">
    
    <!-- Loading Indicator -->
    <div id="routeLoading" class="d-none text-center my-3">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <span class="ms-2">Checking route rates...</span>
    </div>

    <!-- CUSTOMER INFO -->
    <div class="card mb-4 card-section">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>Customer Information</span>
            <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#customerHelpModal">
                <i class="ri-information-line"></i> Help
            </button>
        </div>
        <div class="card-body row">
            <div class="col-md-6 mb-3">
                <label for="customer_id" class="form-label">Customer <span class="text-danger">*</span></label>
                <select class="form-select" id="customer_id" name="customer_id" required>
                    <option value="">-- Select Customer --</option>
                    @foreach($customers as $customer)
                        <option value="{{ $customer->id }}" 
                                data-customer-number="{{ $customer->customer_number }}"
                                data-phone="{{ $customer->phone }}"
                                data-email="{{ $customer->email }}"
                                data-address="{{ $customer->address }}"
                                {{ old('customer_id', optional($shipment?->customer)->id) == $customer->id ? 'selected' : '' }}>
                            {{ $customer->name }} ({{ $customer->phone }})
                        </option>
                    @endforeach
                </select>
                <div class="customer-details mt-2 d-none" id="customerDetails">
                    <small class="text-muted">
                        <div><strong>Phone:</strong> <span id="customerPhone"></span></div>
                        <div><strong>Email:</strong> <span id="customerEmail"></span></div>
                        <div><strong>Address:</strong> <span id="customerAddress"></span></div>
                    </small>
                </div>
            </div>
            
            <div class="col-md-6 mb-3">
                <label for="origin_tracking" class="form-label">Origin Tracking Number</label>
                <input type="text" class="form-control" id="origin_tracking" name="origin_tracking" 
                       value="{{ old('origin_tracking', $shipment?->origin_tracking) }}">
                <small class="text-muted">Optional reference number from origin</small>
            </div>
        </div>
    </div>

    <!-- SHIPMENT DETAILS -->
    <div class="card mb-4 card-section">
        <div class="card-header">Basic Information</div>
        <div class="card-body">
            <h5 class="section-title">Shipment Details</h5>
            <div class="row">
                <input type="hidden" name="shipment_route_id" id="shipment_route_id">

                <div class="col-md-4 mb-3">
                    <label for="shipmentType" class="form-label">Shipment Type <span class="text-danger">*</span></label>
                    <select id="shipmentType" name="shipment_mode_id" class="form-select" required>
                        
                        <option value="">-- Select Mode --</option>
                        @foreach($shipmentModes as $mode)
                            <option value="{{ $mode->id }}"
                                    data-divisor="{{ $mode->volumetric_divisor }}"
                                    data-code="{{ $mode->code }}"
                                    {{ old('shipment_mode_id', $shipment?->shipment_mode_id) == $mode->id ? 'selected' : '' }}>
                                {{ $mode->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label for="numPieces" class="form-label">Number of Pieces <span class="text-danger">*</span></label>
                    <input type="number" id="numPieces" name="package_count" class="form-control" min="1" 
                           value="{{ old('package_count', $shipment?->package_count ?? 1) }}" required>
                </div>

                <div class="col-md-4 mb-3">
                    <label for="tracking" class="form-label">Tracking Number</label>
                    <div class="input-group">
                        <input type="text" id="tracking" name="tracking_number" class="form-control readonly-field" 
                               value="{{ old('tracking_number', $shipment?->tracking_number) }}" readonly>
                        <button class="btn btn-outline-secondary" type="button" id="validateTrackingBtn">
                            <i class="ri-check-line"></i> Validate
                        </button>
                    </div>
                </div>
            </div>

            <div class="row">
                <x-form.select name="origin_country_id" label="Origin Country" wrapperClass="col-md-4 mb-3" 
                              :options="$countries" :selected="old('origin_country_id', $shipment?->origin_country_id)" required />
                
                <x-form.select name="destination_country_id" label="Destination Country" wrapperClass="col-md-4 mb-3" 
                              :options="$countries" :selected="old('destination_country_id', $shipment?->destination_country_id)" required />
                
                <x-form.select name="category_id" label="Goods Category" wrapperClass="col-md-4 mb-3" 
                              :options="$cargoCategories" :selected="old('category_id', $shipment?->category_id)" required />
            </div>
        </div>
        <div id="routeRateContainer" class="alert alert-info d-none mt-2">
            <strong>Route Rate:</strong>
            <span id="routeRateValue">--</span> (<span id="routeCurrency">--</span>) |
            <strong>Type:</strong> <span id="routeRateType">--</span> |
            <strong>Unit:</strong> <span id="routeUnitType">--</span> |
            <strong>Weight Basis:</strong> <span id="routeWeightBasis">--</span>
        </div>

    </div>

    <!-- PACKAGE DETAILS -->
    <div class="card mb-4 card-section">
        <div class="card-header">Package Details</div>
        <div class="card-body">
            <h5 class="section-title">Package Information</h5>
            <div id="packageContainer"></div>
        </div>
    </div>

    <!-- CHARGEABLE WEIGHT & RATES -->
    <div class="card mb-4 card-section">
        <div class="card-header">Chargeable Weight & Rates</div>
        <div class="card-body">
            <h5 class="section-title">Weight & Pricing</h5>
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label for="chargeableWeight" class="form-label">Total Chargeable Weight/Volume</label>
                    <input type="text" id="chargeableWeight" class="form-control readonly-field" readonly>
                    <div class="mt-2">
                        <span id="rateSourceBadge" class="badge badge-rate-source d-none"></span>
                        <small id="rateInfo" class="text-muted"></small>
                    </div>
                </div>
            </div>

            <div id="stdRateWrap" class="row d-none">
                <div class="col-md-6 mb-3">
                    <label>Freight Rate <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <input type="number" id="stdRateInput" name="freight_rate" class="form-control" 
                            placeholder="Rate" step="0.01" value="{{ old('freight_rate', $shipment?->freight_rate) }}" required>
                        <select id="stdCurrencyInput" name="freight_currency" class="form-select currency-selector" required>
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->code }}" {{ old('freight_currency', $shipment?->freight_currency ?? 'KES') == $currency->code ? 'selected' : '' }}>
                                    {{ $currency->code }}
                                </option>
                            @endforeach
                        </select>
                        <button type="button" id="editRateBtn" class="btn btn-outline-primary">
                            <i class="ri-edit-line"></i> Edit
                        </button>
                        <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#rateEditorModal">
                            <i class="ri-file-list-line"></i> Rate Options
                        </button>
                    </div>
                </div>
            </div>
            <div class="mb-3">
    <label for="freight_charge">Freight Charge (auto-calculated)</label>
    <input type="number" step="0.01" class="form-control" id="freight_charge" name="freight_charge" required>
    <small id="freightPreview" class="text-info mt-1 d-block">Route-based freight will be calculated automatically.</small>
</div>


            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="billingRate" class="form-label">Billing Rate</label>
                    <input type="text" id="billingRate" class="form-control readonly-field" readonly>
                </div>
                <div class="col-md-4 mb-3">
                    <label for="billingAmount" class="form-label">Billing Amount</label>
                    <input type="text" id="billingAmount" class="form-control readonly-field" readonly>
                </div>
                <div class="col-md-4 mb-3">
                    <label for="insuranceValue" class="form-label">Insurance Value</label>
                    <div class="input-group">
                        <input type="number" id="insuranceValue" name="insurance_value" class="form-control" 
                               step="0.01" value="{{ old('insurance_value', $shipment?->insurance_value) }}">
                        <select id="insuranceCurrency" name="insurance_currency" class="form-select currency-selector">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->code }}" {{ old('insurance_currency', $shipment?->insurance_currency ?? 'KES') == $currency->code ? 'selected' : '' }}>
                                    {{ $currency->code }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- EXTRA SERVICES -->
    <div class="card mb-4 card-section">
        <div class="card-header">Extra Services</div>
        <div class="card-body">
            <h5 class="section-title">Additional Services</h5>
            <div class="row g-2 mb-3">
                <div class="col-md-3">
                    <select id="serviceSelect" class="form-select">
                        <option value="">-- Select Service --</option>
                        @foreach($services as $service)
                            <option value="{{ $service->id }}" 
                                    data-description="{{ $service->description }}"
                                    data-default-cost="{{ $service->default_cost }}"
                                    data-default-charge="{{ $service->default_charge }}">
                                {{ $service->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <input type="number" step="0.01" id="serviceCost" class="form-control" placeholder="Cost">
                </div>
                <div class="col-md-2">
                    <input type="number" step="0.01" id="serviceCharge" class="form-control" placeholder="Charge">
                </div>
                <div class="col-md-2">
                    <select id="serviceCurrency" class="form-select currency-selector">
                        @foreach($currencies as $currency)
                            <option value="{{ $currency->code }}">{{ $currency->code }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="button" id="addServiceBtn" class="btn btn-primary">
                        <i class="ri-add-line"></i> Add Service
                    </button>
                    <button type="button" id="clearServicesBtn" class="btn btn-outline-danger ms-2">
                        <i class="ri-close-line"></i> Clear All
                    </button>
                </div>
            </div>
            <div class="service-description mb-3 d-none" id="serviceDescription"></div>

            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead class="table-light">
                        <tr>
                            <th>Service</th>
                            <th>Currency</th>
                            <th>Cost</th>
                            <th>Charge</th>
                            <th>Buy Rate</th>
                            <th>Sell Rate</th>
                            <th>Cost KES</th>
                            <th>Charge KES</th>
                            <th>Profit</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="servicesTable">
                        @if($shipment && $shipment->services->count())
                            @foreach($shipment->services as $service)
                                <tr data-service-id="{{ $service->id }}">
                                    <td class="service-name">{{ $service->name }}</td>
                                    <td class="currency">{{ $service->currency }}</td>
                                    <td class="cost">{{ number_format($service->cost, 2) }}</td>
                                    <td class="charge">{{ number_format($service->charge, 2) }}</td>
                                    <td class="buy">{{ number_format($service->buy_rate, 4) }}</td>
                                    <td class="sell">{{ number_format($service->sell_rate, 4) }}</td>
                                    <td class="cost-kes">{{ number_format($service->cost_kes, 2) }}</td>
                                    <td class="charge-kes">{{ number_format($service->charge_kes, 2) }}</td>
                                    <td class="profit">{{ number_format($service->profit, 2) }}</td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-danger remove-service">
                                            <i class="ri-delete-bin-line"></i>
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        @else
                            <tr id="noServicesRow">
                                <td colspan="10" class="text-center">No services added yet</td>
                            </tr>
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- TOTALS SECTION -->
    <div class="card mb-4 card-section">
        <div class="card-header">Totals</div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="freightCharges" class="form-label">Freight Charges</label>
                    <div class="input-group">
                        <input type="text" id="freightCharges" class="form-control readonly-field" readonly>
                        <select id="freightCurrency" class="form-select currency-selector">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->code }}" {{ old('charge_currency_id', $shipment?->charge_currency_id ?? 'KES') == $currency->id ? 'selected' : '' }}>
                                    {{ $currency->code }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
                
                <div class="col-md-4 mb-3">
                    <label for="serviceCharges" class="form-label">Service Charges</label>
                    <div class="input-group">
                        <input type="text" id="servicesTotalEl" class="form-control readonly-field" readonly>
                        <select id="serviceTotalCurrency" class="form-select currency-selector">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->code }}">{{ $currency->code }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                
                <div class="col-md-4 mb-3">
                    <label for="totalCharges" class="form-label">Total Amount</label>
                    <div class="input-group">
                        <input type="text" id="totalCharges" class="form-control readonly-field fw-bold" readonly>
                        <select id="totalCurrency" class="form-select currency-selector">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->code }}" {{ $currency->code === 'KES' ? 'selected' : '' }}>
                                    {{ $currency->code }}
                                </option>
                            @endforeach
                        </select>
                        <button type="button" class="btn btn-outline-success" id="copyTotal">
                            <i class="ri-file-copy-line"></i> Copy
                        </button>
                    </div>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-12">
                    <div class="alert alert-info">
                        <strong>Note:</strong> All amounts are converted to KES using current exchange rates for calculation
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- LABEL PREVIEW -->
    <div class="card mb-4">
        <div class="card-header">Label Preview</div>
        <div class="card-body">
            <div id="labelPreview" class="row mt-4"></div>
            <div class="text-center mt-3">
                <button type="button" id="refreshPreviewBtn" class="btn btn-sm btn-outline-secondary">
                    <i class="ri-refresh-line"></i> Refresh Preview
                </button>
            </div>
        </div>
    </div>

    <!-- FORM ACTIONS -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between">
                <div>
                    <button type="button" id="generateLabels" class="btn btn-secondary me-2">
                        <i class="ri-printer-line"></i> Generate Labels
                    </button>
                    <button type="button" id="saveDraftBtn" class="btn btn-outline-primary">
                        <i class="ri-save-line"></i> Save Draft
                    </button>
                </div>
                <button type="submit" class="btn btn-primary">
                    <i class="ri-save-line"></i> {{ $method === 'PUT' ? 'Update Shipment' : 'Create Shipment' }}
                </button>
            </div>
        </div>
    </div>
</form>

<!-- Rate Editor Modal -->
<div class="modal fade" id="rateEditorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Freight Rate Editor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-4">
                    <div class="col-md-6">
                        <h6>Standard Rates for This Route</h6>
                        <div class="table-responsive rate-history-table">
                            <table class="table table-sm">
                                <thead class="table-light">
                                    <tr>
                                        <th>Weight Range</th>
                                        <th>Rate</th>
                                        <th>Unit</th>
                                    </tr>
                                </thead>
                                <tbody id="rateBreakdownTable">
                                    <tr><td colspan="3" class="text-center">No standard rates found</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6>Rate History</h6>
                        <div class="table-responsive rate-history-table">
                            <table class="table table-sm">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Rate</th>
                                        <th>Changed By</th>
                                    </tr>
                                </thead>
                                <tbody id="rateHistoryTable">
                                    <tr><td colspan="3" class="text-center">No history available</td></tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <h6 class="mt-4">Custom Rate</h6>
                        <div class="mb-3">
                            <label class="form-label">Rate Value <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" id="customRateInput" class="form-control" placeholder="Enter rate" required>
                            <div class="invalid-feedback">Please enter a valid rate</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Currency <span class="text-danger">*</span></label>
                            <select id="customCurrencySelect" class="form-select" required>
                                @foreach($currencies as $currency)
                                    <option value="{{ $currency->code }}">{{ $currency->code }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="useStandardRateBtn" class="btn btn-outline-primary">Use Standard Rate</button>
                <button type="button" id="applyCustomRateBtn" class="btn btn-primary">Apply Custom Rate</button>
            </div>
        </div>
    </div>
</div>

<!-- Customer Help Modal -->
<div class="modal fade" id="customerHelpModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Customer Information Help</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Select an existing customer from the dropdown list. The system will automatically display the customer's contact information.</p>
                <p>If you need to add a new customer, please use the customer management section before creating a shipment.</p>
                <p>The origin tracking number is an optional field for your reference.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <strong class="me-auto" id="toastTitle">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>



@endsection

@push('styles')
<style>
    .card-section {
        margin-bottom: 1.5rem;
        border: 1px solid rgba(0,0,0,.125);
        border-radius: 0.5rem;
    }
    .card-header {
        background-color: #f8f9fa;
        font-weight: 600;
    }
    .section-title {
        border-bottom: 1px solid #dee2e6;
        padding-bottom: 0.5rem;
        margin-bottom: 1rem;
        font-weight: 600;
        color: #495057;
    }
    .readonly-field {
        background-color: #f8f9fa;
        cursor: not-allowed;
    }
    .currency-selector {
        min-width: 100px;
    }
    .badge-rate-source {
        font-size: 0.75rem;
    }
    .box-entry {
        background-color: #f8f9fa;
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 0.25rem;
        border: 1px solid #dee2e6;
    }
    .image-preview-container {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.5rem;
    }
    .image-preview {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
    }
    .rate-history-table {
        max-height: 300px;
        overflow-y: auto;
    }
    .toast {
        max-width: 350px;
    }
    .customer-details {
        padding: 0.5rem;
        background-color: #f8f9fa;
        border-radius: 0.25rem;
        border: 1px solid #dee2e6;
    }
    .service-description {
        padding: 0.75rem;
        background-color: #f8f9fa;
        border-radius: 0.25rem;
        border-left: 3px solid #0d6efd;
    }
</style>
@endpush

@push('scripts')
<script>
    window.shipmentData = {
        services: @json($services),
        currencies: @json($currencies),
        countries: @json($countries),
        categories: @json($cargoCategories),
        customers: @json($customers),
        shipmentTypes: @json($shipmentModes->keyBy('code')),
        existingShipment: @json($shipment),
        mode: "{{ $method }}",
        baseCurrency: 'KES',
        currentUser: @json(auth()->user()->only(['name', 'email']))
    };

    // Initialize toast
    const toastEl = document.getElementById('liveToast');
    const toast = new bootstrap.Toast(toastEl);
    
    function showToast(title, message, type = 'info') {
        document.getElementById('toastTitle').textContent = title;
        document.getElementById('toastMessage').textContent = message;
        toast.show();
    }
    
</script>

<script type="module" src="{{ asset('js/shipment.js') }}"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
<!-- Bootstrap JS Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
@endpush







/**
 * PackageManager - Manages shipment packages, calculations, and rates
 * 
 * Features:
 * - Package management (add/remove/update)
 * - Weight/volume calculations
 * - Rate management (automatic and manual)
 * - Pricing calculations
 * - Error handling and validation
 */
class PackageManager {
    constructor(routeService) {
        if (!routeService) {
            throw new Error('RouteService dependency is required');
        }

        this.routeService = routeService;
        this.state = this.initializeState();
        this.elements = this.initializeElements();
        this.packageCount = this.calculateInitialPackageCount();
        
        this.bindEvents();
        this.init();
    }

    // ======================
    // Initialization Methods
    // ======================

    /**
     * Initialize the manager state with default values
     */
    initializeState() {
        return {
            currentRate: 0,
            currentCurrency: 'KES',
            volumetricDivisor: 6000,
            cbmDivisor: 1000000,
            cuftDivisor: 28316.8466,
            isManualRate: false,
            isLoading: false,
            rateType: 'per_unit',
            minChargeableWeight: 0,
            flatRateAmount: 0,
            weightBasis: 'higher',
            unitType: 'kg'
        };
    }

    /**
     * Cache DOM elements for better performance
     */
    initializeElements() {
        const elements = {
            packageContainer: document.getElementById('packageContainer'),
            numPiecesInput: document.getElementById('numPieces'),
            shipmentModeSelect: document.getElementById('shipment_mode_select'),
            originCountry: document.getElementById('origin_country_id'),
            destinationCountry: document.getElementById('destination_country_id'),
            cargoCategory: document.getElementById('cargo_category_id'),
            rateDisplay: document.getElementById('rateDisplay'),
            freightCurrency: document.getElementById('freightCurrency'),
            totalGrossWeight: document.getElementById('totalGrossWeight'),
            totalVolumeWeight: document.getElementById('totalVolumeWeight'),
            totalChargeableWeight: document.getElementById('totalChargeableWeight'),
            finalChargeableWeight: document.getElementById('finalChargeableWeight'),
            totalFreightCharges: document.getElementById('totalFreightCharges'),
            volumetricDivisorDisplay: document.getElementById('volumetricDivisorDisplay'),
            currencyDisplay: document.getElementById('currencyDisplay'),
            setManualRateBtn: document.getElementById('setManualRateBtn'),
            manualRateModal: document.getElementById('manualRateModal'),
            manualRateValue: document.getElementById('manualRateValue'),
            manualRateCurrency: document.getElementById('manualRateCurrency'),
            manualRateType: document.getElementById('manualRateType'),
            minWeightInfo: document.getElementById('minWeightInfo'),
            weightBasisInfo: document.getElementById('weightBasisInfo'),
            chargeableInfo: document.getElementById('chargeableInfo'),
            freightInfo: document.getElementById('freightInfo'),
            resetManualRateBtn: document.getElementById('resetManualRateBtn'),
            addPackageBtn: document.getElementById('addPackageBtn'),
            removePackageBtn: document.getElementById('removePackageBtn')
        };

        // Validate critical elements
        if (!elements.packageContainer) {
            console.error('Package container element not found');
        }

        return elements;
    }

    calculateInitialPackageCount() {
        return this.elements.packageContainer 
            ? this.elements.packageContainer.querySelectorAll('.package-row').length 
            : 1;
    }

    // =================
    // Core Functionality
    // =================

    /**
     * Initialize the package manager
     */
    init() {
        try {
            this.state.unitType = this.getCurrentUnitType();
            this.updateAllCalculations();
            this.fetchRouteRate();
            this.updateRemoveButtonState();
            
            // Initialize calculations for existing packages
            this.initializeExistingPackages();
        } catch (error) {
            console.error('PackageManager initialization failed:', error);
            this.showRateError('Initialization failed. Please refresh the page.');
        }
    }

    initializeExistingPackages() {
        const rows = this.elements.packageContainer?.querySelectorAll('.package-row') || [];
        rows.forEach(row => {
            this.showCalculations(row);
        });
    }

    // =====================
    // Package CRUD Operations
    // =====================

    addPackage(index) {
        try {
            const unitType = this.getCurrentUnitType();
            const row = document.createElement('div');
            row.className = 'package-row mb-3 p-3 border rounded';
            row.dataset.index = index;
            
            row.innerHTML = this.generatePackageHTML(index, unitType);
            
            this.setupPackageEventListeners(row);
            this.elements.packageContainer.appendChild(row);
        } catch (error) {
            console.error('Failed to add package:', error);
            alert('Failed to add new package. Please try again.');
        }
    }

    generatePackageHTML(index, unitType) {
        return `
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0">Package ${index + 1}</h6>
                <button type="button" class="btn btn-sm btn-outline-danger remove-single-package" title="Remove this package">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
            <div class="row">
                <div class="col-md-3 mb-2">
                    <label>Length (cm)</label>
                    <input name="packages[${index}][length]" class="form-control length" required>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Width (cm)</label>
                    <input name="packages[${index}][width]" class="form-control width" required>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Height (cm)</label>
                    <input name="packages[${index}][height]" class="form-control height" required>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Weight (kg)</label>
                    <input name="packages[${index}][weight]" class="form-control weight" required>
                </div>
            </div>
            <div class="calculation-section d-none">
                <div class="row mt-2">
                    <div class="col-md-6">
                        <div class="alert alert-info p-2 mb-0">
                            <small>
                                Volume: <span class="volume-display">0</span> cm³<br>
                                Vol. Weight: <span class="vol-weight-display">0</span> kg<br>
                                Chargeable: <span class="chargeable-weight-display">0 ${unitType === 'CBM' ? 'CBM' : unitType === 'CUFT' ? 'CUFT' : 'kg'}</span>
                            </small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <input type="file" name="packages[${index}][images][]" multiple class="form-control form-control-sm" accept="image/*">
                    </div>
                </div>
            </div>
        `;
    }

    setupPackageEventListeners(row) {
        const inputs = row.querySelectorAll('.length, .width, .height, .weight');
        inputs.forEach(input => {
            input.addEventListener('input', () => {
                try {
                    this.updatePackageCalculations(row);
                    this.showCalculations(row);
                    this.updateTotals();
                } catch (error) {
                    console.error('Package calculation error:', error);
                }
            });
        });
    }

    removePackage(index) {
        if (this.packageCount <= 1) return;

        try {
            const rows = this.elements.packageContainer.querySelectorAll('.package-row');
            rows[index].remove();
            this.packageCount--;
            this.elements.numPiecesInput.value = this.packageCount;
            this.updateRemoveButtonState();
            this.updateAllCalculations();
            this.renumberPackages();
        } catch (error) {
            console.error('Failed to remove package:', error);
            alert('Failed to remove package. Please try again.');
        }
    }

    updatePackageRows(count) {
        try {
            const currentCount = this.elements.packageContainer?.querySelectorAll('.package-row').length || 0;
            
            if (count > currentCount) {
                // Add new packages
                for (let i = currentCount; i < count; i++) {
                    this.addPackage(i);
                }
            } else if (count < currentCount) {
                // Remove packages (keep at least one)
                const rows = this.elements.packageContainer?.querySelectorAll('.package-row') || [];
                for (let i = currentCount - 1; i >= count && i > 0; i--) {
                    rows[i].remove();
                }
            }
            
            this.packageCount = count;
            this.updateRemoveButtonState();
            this.updateAllCalculations();
            this.renumberPackages();
        } catch (error) {
            console.error('Failed to update package rows:', error);
            alert('Failed to update packages. Please try again.');
        }
    }

    // =====================
    // Calculation Methods
    // =====================

    updatePackageCalculations(row) {
        try {
            const length = parseFloat(row.querySelector('.length').value) || 0;
            const width = parseFloat(row.querySelector('.width').value) || 0;
            const height = parseFloat(row.querySelector('.height').value) || 0;
            const weight = parseFloat(row.querySelector('.weight').value) || 0;
            const unitType = this.getCurrentUnitType();
            
            const volume = length * width * height;
            const volWeight = volume / this.state.volumetricDivisor;
            
            const { chargeable, display } = this.calculateChargeableWeight(
                unitType, weight, volWeight, volume
            );
            
            this.updatePackageDisplay(row, volume, volWeight, display);
        } catch (error) {
            console.error('Package calculation error:', error);
        }
    }

    calculateChargeableWeight(unitType, weight, volWeight, volume) {
        let chargeable, display;
        
        if (unitType === 'CBM') {
            chargeable = volume / this.state.cbmDivisor;
            display = `${chargeable.toFixed(4)} CBM`;
        } else if (unitType === 'CUFT') {
            chargeable = volume / this.state.cuftDivisor;
            display = `${chargeable.toFixed(4)} CUFT`;
        } else {
            switch(this.state.weightBasis) {
                case 'gross':
                    chargeable = weight;
                    break;
                case 'volumetric':
                    chargeable = volWeight;
                    break;
                case 'higher':
                default:
                    chargeable = Math.max(volWeight, weight);
                    break;
            }
            display = `${chargeable.toFixed(2)} kg`;
        }
        
        return { chargeable, display };
    }

    updatePackageDisplay(row, volume, volWeight, display) {
        if (row.querySelector('.volume-display')) {
            row.querySelector('.volume-display').textContent = volume.toFixed(2);
            row.querySelector('.vol-weight-display').textContent = volWeight.toFixed(2);
            row.querySelector('.chargeable-weight-display').textContent = display;
        }
    }

updateTotals() {
    try {
        const { totalGross, totalVolWeight, totalChargeable } = this.calculatePackageTotals();
        const { finalChargeable, appliedFlatRate } = this.applyMinimumWeightRules(totalChargeable);
        
        this.updateTotalDisplays(totalGross, totalVolWeight, totalChargeable, finalChargeable, appliedFlatRate);
        
        const totalFreight = this.calculateTotalFreight(finalChargeable, appliedFlatRate);
        this.updateFreightDisplay(totalFreight, finalChargeable, appliedFlatRate);
        
        this.updatePricingSummary(totalFreight);
    } catch (error) {
        console.error('Failed to update totals:', error);
    }
}

    calculatePackageTotals() {
        let totalGross = 0;
        let totalVolWeight = 0;
        let totalChargeable = 0;
        const unitType = this.getCurrentUnitType();
        
        this.elements.packageContainer?.querySelectorAll('.package-row').forEach(row => {
            const weight = parseFloat(row.querySelector('.weight').value) || 0;
            totalGross += weight;
            
            const length = parseFloat(row.querySelector('.length').value) || 0;
            const width = parseFloat(row.querySelector('.width').value) || 0;
            const height = parseFloat(row.querySelector('.height').value) || 0;
            
            const volume = length * width * height;
            const volWeight = volume / this.state.volumetricDivisor;
            totalVolWeight += volWeight;
            
            if (unitType === 'CBM') {
                totalChargeable += volume / this.state.cbmDivisor;
            } else if (unitType === 'CUFT') {
                totalChargeable += volume / this.state.cuftDivisor;
            } else {
                switch(this.state.weightBasis) {
                    case 'gross':
                        totalChargeable += weight;
                        break;
                    case 'volumetric':
                        totalChargeable += volWeight;
                        break;
                    case 'higher':
                    default:
                        totalChargeable += Math.max(volWeight, weight);
                        break;
                }
            }
        });
        
        return { totalGross, totalVolWeight, totalChargeable };
    }

//applying minimums rules

applyMinimumWeightRules(totalChargeable) {
    let finalChargeable = totalChargeable;
    let appliedFlatRate = false;
    
    // For KG measurements
    if ((this.state.unitType === 'KG' || this.state.unitType === 'KGS') && 
        this.state.minChargeableWeight > 0) {
        if (totalChargeable <= this.state.minChargeableWeight) {
            finalChargeable = this.state.minChargeableWeight;
            appliedFlatRate = true;
            console.log(`Applying KG flat rate (${this.state.flatRateAmount} ${this.state.currentCurrency}) because chargeable weight (${totalChargeable}) <= minimum weight (${this.state.minChargeableWeight})`);
        }
    }
    // For CBM measurements
    else if (this.state.unitType === 'CBM' && this.state.minChargeableWeight > 0) {
        if (totalChargeable <= this.state.minChargeableWeight) {
            finalChargeable = this.state.minChargeableWeight;
            appliedFlatRate = true;
            console.log(`Applying CBM flat rate (${this.state.flatRateAmount} ${this.state.currentCurrency}) because chargeable volume (${totalChargeable}) <= minimum volume (${this.state.minChargeableWeight})`);
        }
    }
    
    return { finalChargeable, appliedFlatRate };
}
///////
  

        updateTotalDisplays(totalGross, totalVolWeight, totalChargeable, finalChargeable, appliedFlatRate) {
        const unitType = this.getCurrentUnitType();
        
        if (this.elements.totalGrossWeight) {
            this.elements.totalGrossWeight.value = `${totalGross.toFixed(2)} kg`;
        }
        
        if (this.elements.totalVolumeWeight) {
            this.elements.totalVolumeWeight.value = `${totalVolWeight.toFixed(2)} kg`;
        }

        let chargeableDisplay;
        if (unitType === 'CBM') {
            chargeableDisplay = `${totalChargeable.toFixed(4)} CBM`;
        } else if (unitType === 'CUFT') {
            chargeableDisplay = `${totalChargeable.toFixed(4)} CUFT`;
        } else {
            chargeableDisplay = `${totalChargeable.toFixed(2)} kg`;
            
            // Show if flat rate was applied
            if (this.elements.minWeightInfo) {
                this.elements.minWeightInfo.textContent = this.getMinWeightText(appliedFlatRate);
            }
        }

        if (this.elements.totalChargeableWeight) {
            this.elements.totalChargeableWeight.value = chargeableDisplay;
        }
        
        if (this.elements.finalChargeableWeight) {
            this.elements.finalChargeableWeight.value = chargeableDisplay;
        }
    }


    getMinWeightText(appliedFlatRate) {
        let text = `Minimum chargeable weight: ${this.state.minChargeableWeight} kg`;
        if (appliedFlatRate && this.state.flatRateAmount > 0) {
            text += ` (Flat rate: ${this.state.flatRateAmount} ${this.state.currentCurrency} applied)`;
        }
        return text;
    }

///calculating minimu freights

    calculateTotalFreight(finalChargeable, appliedFlatRate) {
        let totalFreight = 0;
        
        if (appliedFlatRate) {
            // Apply flat rate when chargeable is <= minimum (for both KG and CBM)
            totalFreight = this.state.flatRateAmount;
        } 
        else if (this.state.rateType === 'flat_rate') {
            // Use flat rate if that's the only rate available
            totalFreight = this.state.flatRateAmount;
        } 
        else {
            // Normal per-unit calculation
            totalFreight = finalChargeable * this.state.currentRate;
        }
        
        console.log(`Calculating freight: 
            Unit Type: ${this.state.unitType}
            Chargeable: ${finalChargeable} ${this.state.unitType}
            Rate: ${this.state.currentRate} ${this.state.currentCurrency}/${this.state.unitType}
            Flat Rate: ${this.state.flatRateAmount} ${this.state.currentCurrency}
            Applied Flat: ${appliedFlatRate}
            Total: ${totalFreight} ${this.state.currentCurrency}`);
        
        return totalFreight;
    }
        
        
    ///updaing freight display

        updateFreightDisplay(totalFreight, finalChargeable, appliedFlatRate) {
            if (!this.elements.totalFreightCharges) return;
            
            // Format the total with currency
            this.elements.totalFreightCharges.value = totalFreight.toFixed(2);
            this.elements.freightCurrency.textContent = this.state.currentCurrency;
            
            // Show calculation details
            if (appliedFlatRate) {
                this.elements.totalFreightCharges.title = 
                    `Flat rate of ${this.state.flatRateAmount} ${this.state.currentCurrency} applied (chargeable weight ${finalChargeable} ${this.state.unitType} ≤ minimum ${this.state.minChargeableWeight} ${this.state.unitType})`;
            } else if (this.state.rateType === 'flat_rate') {
                this.elements.totalFreightCharges.title = 
                    `Flat rate of ${this.state.flatRateAmount} ${this.state.currentCurrency} applied`;
            } else {
                this.elements.totalFreightCharges.title = 
                    `Calculated as ${finalChargeable.toFixed(2)} ${this.state.unitType} × ${this.state.currentRate} ${this.state.currentCurrency}/${this.state.unitType}`;
            }
        }

    updatePricingSummary(totalFreight) {
        if (typeof window.updatePricingSummary === 'function') {
            window.updatePricingSummary({
                freight: totalFreight,
                currency: this.state.currentCurrency
            });
        }
    }

    // =====================
    // Rate Management
    // =====================

    async fetchRouteRate() {
        // Don't fetch if manual rate is set or already loading
        if (this.state.isManualRate || this.state.isLoading) return;

        // Get route parameters
        const origin = this.elements.originCountry?.value;
        const destination = this.elements.destinationCountry?.value;
        const mode = this.elements.shipmentModeSelect?.value;
        const category = this.elements.cargoCategory?.value;

        // Validate required fields
        if (!origin || !destination || !mode || !category) {
            this.showRateError('Please complete all route details');
            return;
        }

        // Set loading state
        this.state.isLoading = true;
        this.showLoadingState();

        try {
            const data = await this.routeService.findRoute({
                origin_country_id: origin,
                destination_country_id: destination,
                mode: mode,
                category_id: category
            });
            
            if (!data.success) {
                this.handleNoRouteFound(data.message || 'No active route found');
                return;
            }

            this.updateRouteData(data);
            this.updateRateDisplay(data);
            this.updateTotals();
            this.updateWeightInfo();

        } catch (error) {
            console.error('Error fetching route rates:', error);
            this.handleNoRouteFound(error.message || 'Failed to fetch route rates');
        } finally {
            this.state.isLoading = false;
        }
    }

////updaing route data
updateRouteData(data) {
    // Convert string values to numbers
    this.state.currentRate = parseFloat(data.rate_per_unit) || 0;
    this.state.flatRateAmount = parseFloat(data.flat_rate) || 0;
    this.state.minChargeableWeight = parseFloat(data.minimum_weight) || 0;
    
    this.state.currentCurrency = data.currency || 'KES';
    this.state.volumetricDivisor = parseFloat(data.volumetric_divisor) || 6000;
    this.state.cbmDivisor = parseFloat(data.cbm_divisor) || 1000000;
    this.state.cuftDivisor = parseFloat(data.cuft_divisor) || 28316.8466;
    this.state.weightBasis = data.weight_basis || 'higher';
    
    // Normalize unit type
    this.state.unitType = data.unit_type === 'KGS' ? 'KG' : data.unit_type;
    
    this.state.isManualRate = false;
    this.state.rateType = data.rate_per_unit ? 'per_unit' : 'flat_rate';
    
    console.log('Route data updated:', {
        ...this.state,
        // Don't log the entire state object to avoid circular references
        unitType: this.state.unitType,
        minChargeable: this.state.minChargeableWeight
    });
    
    this.updateWeightInfo();
    this.updateTotals();
}


///update weight info

updateWeightInfo() {
    if (this.elements.weightBasisInfo) {
        let basisText = '';
        switch(this.state.weightBasis) {
            case 'gross':
                basisText = 'Charged on gross weight';
                break;
            case 'volumetric':
                basisText = 'Charged on volumetric weight';
                break;
            case 'higher':
            default:
                basisText = this.state.unitType === 'CBM' 
                    ? 'Charged on volume' 
                    : 'Charged on higher of gross/volumetric';
                break;
        }
        this.elements.weightBasisInfo.textContent = basisText;
    }

    if (this.elements.minWeightInfo) {
        let minText = `Minimum chargeable ${this.state.unitType === 'CBM' ? 'volume' : 'weight'}: `;
        minText += `${this.state.minChargeableWeight} ${this.state.unitType}`;
        
        if (this.state.flatRateAmount > 0) {
            minText += ` (Flat rate: ${this.state.flatRateAmount} ${this.state.currentCurrency} when not met)`;
        }
        this.elements.minWeightInfo.textContent = minText;
    }
}
///end of updating weight info

    handleNoRouteFound(message) {
        this.showRateError(message);
        
        // Reset to default values
        this.state.currentRate = 0;
        this.state.currentCurrency = 'KES';
        this.state.volumetricDivisor = 6000;
        this.state.cbmDivisor = 1000000;
        this.state.cuftDivisor = 28316.8466;
        this.state.isManualRate = false;
        this.state.rateType = 'per_unit';
        this.state.weightBasis = 'higher';
        
        // Enable manual rate button
        if (this.elements.setManualRateBtn) {
            this.elements.setManualRateBtn.disabled = false;
        }
        
        // Update calculations
        this.updateTotals();
    }

    setManualRate(rate, currency, type = 'per_unit') {
        // Validate inputs
        if (isNaN(rate) || rate <= 0) {
            throw new Error('Invalid rate value');
        }
        if (!currency || currency.length !== 3) {
            throw new Error('Invalid currency code');
        }

        // Update internal state
        this.state.currentRate = rate;
        this.state.currentCurrency = currency;
        this.state.isManualRate = true;
        this.state.rateType = type;

        // Update UI
        this.updateRateUI(rate, currency, type);
        this.updateTotals();
    }

    updateRateUI(rate, currency, type) {
        if (this.elements.rateDisplay) {
            if (type === 'per_unit') {
                const unitType = this.getCurrentUnitType();
                this.elements.rateDisplay.innerHTML = `
                    <p class="mb-1"><strong>${rate} ${currency}/${unitType}</strong></p>
                    <small class="text-success">Manual rate applied</small>
                `;
            } else {
                this.elements.rateDisplay.innerHTML = `
                    <p class="mb-1"><strong>${rate} ${currency}</strong></p>
                    <small class="text-success">Manual flat rate applied</small>
                `;
            }
        }

        if (this.elements.freightCurrency) {
            this.elements.freightCurrency.textContent = currency;
        }

        if (this.elements.currencyDisplay) {
            this.elements.currencyDisplay.innerHTML = `<p class="mb-0">${currency}</p>`;
        }

        // Disable manual rate button and enable reset
        if (this.elements.setManualRateBtn) {
            this.elements.setManualRateBtn.disabled = true;
        }
        if (this.elements.resetManualRateBtn) {
            this.elements.resetManualRateBtn.disabled = false;
        }
    }

    // =====================
    // UI Helper Methods
    // =====================

    showRateError(message = 'Failed to load rates') {
        if (!this.elements.rateDisplay) return;

        this.elements.rateDisplay.innerHTML = `
            <div>
                <p class="mb-1 text-danger"><strong>${message}</strong></p>
                <small class="text-warning">Using default values (0 ${this.state.currentCurrency})</small>
            </div>
            <button class="btn btn-sm btn-outline-primary mt-2" id="manualRatePromptBtn">
                Set Manual Rate
            </button>
        `;
        
        // Add click handler to the manual rate prompt button
        document.getElementById('manualRatePromptBtn')?.addEventListener('click', () => {
            this.showManualRateModal();
        });
    }

    showLoadingState() {
        if (this.elements.rateDisplay) {
            this.elements.rateDisplay.innerHTML = `
                <p class="mb-1"><i class="ri-loader-4-line spin"></i> Loading rates...</p>
            `;
        }
    }

    updateRateDisplay(data) {
        if (!this.elements.rateDisplay) return;

        if (data.rate_per_unit) {
            this.elements.rateDisplay.innerHTML = `
                <p class="mb-1"><strong>${data.rate_per_unit} ${data.currency}/${data.unit_type || 'kg'}</strong></p>
                <small class="text-muted">Standard rate</small>
            `;
        } else if (data.flat_rate) {
            this.elements.rateDisplay.innerHTML = `
                <p class="mb-1"><strong>${data.flat_rate} ${data.currency}</strong></p>
                <small class="text-muted">Flat rate</small>
            `;
        }

        // Update other displays
        if (this.elements.freightCurrency) {
            this.elements.freightCurrency.textContent = data.currency || 'KES';
        }
        
        if (this.elements.volumetricDivisorDisplay) {
            this.elements.volumetricDivisorDisplay.innerHTML = `
                <p class="mb-0">${data.volumetric_divisor || 6000}</p>
            `;
        }
        
        if (this.elements.currencyDisplay) {
            this.elements.currencyDisplay.innerHTML = `
                <p class="mb-0">${data.currency || 'KES'}</p>
            `;
        }
    }

    showManualRateModal() {
        try {
            const modal = new bootstrap.Modal(this.elements.manualRateModal);
            
            // Pre-fill with current values if manual rate was already set
            if (this.state.isManualRate) {
                this.elements.manualRateValue.value = this.state.currentRate;
                this.elements.manualRateCurrency.value = this.state.currentCurrency;
                this.elements.manualRateType.value = this.state.rateType;
            } else {
                // Set defaults
                this.elements.manualRateValue.value = '';
                this.elements.manualRateCurrency.value = 'KES';
                this.elements.manualRateType.value = 'per_unit';
            }
            
            modal.show();
        } catch (error) {
            console.error('Failed to show manual rate modal:', error);
            alert('Failed to open rate settings. Please try again.');
        }
    }

    applyManualRate() {
        const rateValueEl = this.elements.manualRateValue;
        const rate = parseFloat(rateValueEl.value);
        const currency = this.elements.manualRateCurrency.value;
        const rateType = this.elements.manualRateType.value;
        const errorEl = document.getElementById('rateError');
        
        // Reset error state
        if (errorEl) {
            errorEl.classList.add('d-none');
            rateValueEl.classList.remove('is-invalid');
        }
        
        // Validate rate input
        if (isNaN(rate) || rate <= 0) {
            if (errorEl) {
                errorEl.textContent = 'Please enter a valid rate greater than 0';
                errorEl.classList.remove('d-none');
                rateValueEl.classList.add('is-invalid');
            } else {
                alert('Please enter a valid rate greater than 0.');
            }
            return;
        }
        
        try {
            // Set the manual rate
            this.setManualRate(rate, currency, rateType);
            
            // Close the modal
            const modal = bootstrap.Modal.getInstance(this.elements.manualRateModal);
            modal.hide();
        } catch (error) {
            console.error('Failed to apply manual rate:', error);
            if (errorEl) {
                errorEl.textContent = error.message;
                errorEl.classList.remove('d-none');
                rateValueEl.classList.add('is-invalid');
            } else {
                alert(error.message);
            }
        }
    }

    resetManualRate() {
        this.state.isManualRate = false;
        this.fetchRouteRate();
        
        // Show success message
        if (this.elements.setManualRateBtn) {
            const toast = new bootstrap.Toast(document.getElementById('manualRateResetToast'));
            toast.show();
        }
    }

    // =====================
    // Utility Methods
    // =====================

    getCurrentUnitType() {
        if (!this.elements.shipmentModeSelect) return 'kg';
        const selected = this.elements.shipmentModeSelect.selectedOptions[0];
        return selected?.dataset.measure || 'kg';
    }

    updateRemoveButtonState() {
        if (this.elements.removePackageBtn) {
            this.elements.removePackageBtn.disabled = this.packageCount <= 1;
        }
    }

    renumberPackages() {
        const rows = this.elements.packageContainer?.querySelectorAll('.package-row') || [];
        rows.forEach((row, index) => {
            const title = row.querySelector('h6');
            if (title) {
                title.textContent = `Package ${index + 1}`;
            }
            
            // Update all name attributes with new index
            const inputs = row.querySelectorAll('[name^="packages["]');
            inputs.forEach(input => {
                const name = input.name.replace(/packages\[\d+\]/, `packages[${index}]`);
                input.name = name;
            });
            
            row.dataset.index = index;
        });
    }

    showCalculations(row) {
        const hasValues = Array.from(row.querySelectorAll('.length, .width, .height, .weight'))
            .some(input => input.value.trim() !== '');
        
        const calcSection = row.querySelector('.calculation-section');
        
        if (calcSection) {
            calcSection.classList.toggle('d-none', !hasValues);
        }
    }

    updateAllCalculations() {
        const rows = this.elements.packageContainer?.querySelectorAll('.package-row') || [];
        rows.forEach(row => {
            this.updatePackageCalculations(row);
            this.showCalculations(row);
        });
        this.updateTotals();
    }

    handlePackageCountChange() {
        const count = parseInt(this.elements.numPiecesInput.value);
        if (!isNaN(count) && count > 0) {
            this.updatePackageRows(count);
        }
    }

    // =====================
    // Event Binding
    // =====================

    bindEvents() {
        // Package count changes
        this.elements.numPiecesInput?.addEventListener('change', () => this.handlePackageCountChange());

        // Add package button
        this.elements.addPackageBtn?.addEventListener('click', () => {
            this.addPackage(this.packageCount);
            this.packageCount++;
            this.elements.numPiecesInput.value = this.packageCount;
            this.updateRemoveButtonState();
        });

        // Remove package button
        this.elements.removePackageBtn?.addEventListener('click', () => {
            if (this.packageCount > 1) {
                this.removePackage(this.packageCount - 1);
            }
        });

        // Delegate event for single package removal
        this.elements.packageContainer?.addEventListener('click', (e) => {
            if (e.target.closest('.remove-single-package')) {
                const row = e.target.closest('.package-row');
                if (this.packageCount > 1) {
                    row.remove();
                    this.packageCount--;
                    this.elements.numPiecesInput.value = this.packageCount;
                    this.updateRemoveButtonState();
                    this.updateAllCalculations();
                    this.renumberPackages();
                }
            }
        });

        // Shipment mode changes
        this.elements.shipmentModeSelect?.addEventListener('change', () => {
            this.state.unitType = this.getCurrentUnitType();
            this.updateAllCalculations();
            this.fetchRouteRate();
        });

        // Package input changes
        this.elements.packageContainer?.addEventListener('input', (e) => {
            if (e.target.classList.contains('length') || 
                e.target.classList.contains('width') || 
                e.target.classList.contains('height') || 
                e.target.classList.contains('weight')) {
                const row = e.target.closest('.package-row');
                this.updatePackageCalculations(row);
                this.showCalculations(row);
                this.updateTotals();
            }
        });

        // Route changes
        ['origin_country_id', 'destination_country_id', 'cargo_category_id'].forEach(id => {
            document.getElementById(id)?.addEventListener('change', () => this.fetchRouteRate());
        });

        // Manual rate button
        this.elements.setManualRateBtn?.addEventListener('click', () => this.showManualRateModal());

        // Reset manual rate button
        this.elements.resetManualRateBtn?.addEventListener('click', () => this.resetManualRate());

        // Apply manual rate form submission
        document.getElementById('manualRateForm')?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.applyManualRate();
        });
    }
}

// Register globally
if (typeof window !== 'undefined') {
    window.PackageManager = PackageManager;
}