<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <!-- 1. Global Order Total Display -->
    <template id="chennora_total_uber_display" inherit_id="website_sale.total" name="Chennora Total Uber Display">
        <xpath expr="//tr[@id='order_total_untaxed']" position="after">
            <t t-set="uber_line" t-value="website_sale_order.order_line.filtered(lambda l: l.product_id.name == 'Uber Delivery Fee')"/>
            <tr t-if="uber_line" id="uber_delivery_row">
                <td class="border-0 pb-2 ps-0 pt-0 text-start text-muted" colspan="2">Uber Delivery Fee</td>
                <td class="text-end border-0 pb-2 pe-0 pt-0">
                    <span t-field="uber_line[0].price_subtotal" t-options='{"widget": "monetary", "display_currency": website_sale_order.currency_id}' class="monetary_field"/>
                </td>
            </tr>
        </xpath>
    </template>

    <!-- 2. Hide Uber fee from cart summary -->
    <template id="chennora_cart_summary_uber_hide" inherit_id="website_sale.checkout_layout" name="Chennora Cart Summary Uber Hide">
        <xpath expr="//table[@id='cart_products']//tr" position="attributes">
            <attribute name="t-if">line.product_id.name != 'Uber Delivery Fee'</attribute>
        </xpath>
    </template>

    <!-- 3. Morphing Address Form (Pickup vs Delivery) -->
    <template id="chennora_address_morphing" inherit_id="website_sale.address" name="Chennora Address Morphing" priority="99">
        <xpath expr="//form" position="before">
            <style>
                .order-type-card { border: 2px solid #eee; border-radius: 12px; cursor: pointer; transition: all 0.3s ease; padding: 20px; text-align: center; height: 100%; }
                .order-type-card.active { border-color: #00A67E; background-color: #f0fffb; }
                .order-type-card i { font-size: 2rem; margin-bottom: 10px; color: #666; }
                .order-type-card.active i { color: #00A67E; }
                .order-type-card h5 { margin-bottom: 5px; font-weight: bold; }
                .order-type-card p { font-size: 0.85rem; color: #888; margin: 0; }
                .section-header { font-weight: bold; margin: 25px 0 15px 0; padding-bottom: 5px; border-bottom: 1px solid #eee; }
            </style>

            <div class="row mb-4 g-3 mt-2">
                <div class="col-6">
                    <div id="card_delivery" class="order-type-card active" onclick="setOrderType('delivery')">
                        <i class="fa fa-truck"></i>
                        <h5>Delivery</h5>
                        <p>Deliver to my address</p>
                    </div>
                </div>
                <div class="col-6">
                    <div id="card_pickup" class="order-type-card" onclick="setOrderType('pickup')">
                        <i class="fa fa-shopping-basket"></i>
                        <h5>Store Pickup</h5>
                        <p>Pick up at the restaurant</p>
                    </div>
                </div>
            </div>
            
            <input type="hidden" name="fulfilment_type" id="hidden_fulfilment_type" value="delivery"/>

            <div class="section-header">Select Time</div>
            <div class="mb-4">
                <input type="datetime-local" name="delivery_time" id="delivery_time_input" class="form-control"/>
                <p class="text-muted small mt-1">Please select your preferred time.</p>
            </div>

            <div id="uber_message" class="alert d-none my-3" role="alert"></div>
            <div id="address_section_label" class="section-header">Delivery Address Details</div>
        </xpath>

        <!-- No wrapper needed, we use JS to target the div_street, div_city, etc. -->

        <xpath expr="//form" position="after">
            <script type="text/javascript">
                (function() {
                    function initAddressLogic() {
                        const hiddenType = document.getElementById('hidden_fulfilment_type');
                        const msgDiv = document.getElementById('uber_message');
                        const addressHeader = document.getElementById('address_section_label');
                        const btn = document.querySelector('button[type="submit"]') || document.querySelector('.btn-primary');
                        
                        // Address fields to toggle
                        const addressDivs = [
                            document.getElementById('div_street'),
                            document.getElementById('div_city'),
                            document.getElementById('div_zip'),
                            document.getElementById('div_country'),
                            document.querySelector('div[id*="div_state"]') // Handle potential different IDs for state
                        ].filter(el => el != null);

                        window.setOrderType = function(type) {
                            hiddenType.value = type;
                            document.getElementById('card_delivery').classList.toggle('active', type === 'delivery');
                            document.getElementById('card_pickup').classList.toggle('active', type === 'pickup');
                            
                            if (type === 'pickup') {
                                addressDivs.forEach(div => div.classList.add('d-none'));
                                if (addressHeader) addressHeader.classList.add('d-none');
                                if (msgDiv) msgDiv.classList.add('d-none');
                                if (btn) btn.disabled = false;
                            } else {
                                addressDivs.forEach(div => div.classList.remove('d-none'));
                                if (addressHeader) addressHeader.classList.remove('d-none');
                                checkUber();
                            }
                        };

                        function checkUber() {
                            if (hiddenType.value !== 'delivery') return;
                            const street = document.querySelector('input[name="street"]')?.value;
                            const zip = document.querySelector('input[name="zip"]')?.value;
                            if (!street || !zip) return;

                            const addressData = {
                                street: street,
                                city: document.querySelector('input[name="city"]')?.value,
                                zip: zip,
                                country: document.querySelector('select[name="country_id"] option:checked')?.text || 'Canada'
                            };

                            fetch('/shop/uber/quote', {
                                method: 'POST', headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({ params: { address_data: addressData } })
                            }).then(r => r.json()).then(data => {
                                if (data.result &amp;&amp; data.result.success) {
                                    msgDiv.classList.remove('d-none', 'alert-danger');
                                    msgDiv.classList.add('alert-success');
                                    msgDiv.innerText = "✓ Uber covers this area! Delivery fee: " + data.result.fee + "$";
                                    if (btn) btn.disabled = false;
                                } else {
                                    msgDiv.classList.remove('d-none', 'alert-success');
                                    msgDiv.classList.add('alert-danger');
                                    msgDiv.innerText = "✕ Not covered: " + (data.result?.error || "Area not supported.");
                                    if (btn) btn.disabled = true;
                                }
                            });
                        }

                        // Event listeners for Uber check
                        const streetInput = document.querySelector('input[name="street"]');
                        const zipInput = document.querySelector('input[name="zip"]');
                        if (streetInput) streetInput.addEventListener('blur', checkUber);
                        if (zipInput) zipInput.addEventListener('blur', checkUber);

                        // Initial state
                        setOrderType('delivery');
                    }
                    
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', initAddressLogic);
                    } else {
                        initAddressLogic();
                    }
                })();
            </script>
        </xpath>
    </template>
</odoo>
