

<?php $__env->startSection('title', 'My Profile - ' . \App\Models\Setting::get('site_name', 'KiyoKart')); ?>

<?php $__env->startSection('content'); ?>
<div class="container profile-container">
    <!-- Profile Header -->
    

    <div class="row d-flex justify-content-center">
        <!-- Main Content -->
        <div class="col-lg-6">
            <!-- Profile Information -->
            <div class="profile-card-modern">
                <div class="profile-card-header">
                    <h5>
                        <i class="bi bi-person-gear"></i> Profile Information
                    </h5>
                </div>
                <div class="profile-card-body">
                    <form action="<?php echo e(route('customer.profile.update')); ?>" method="POST" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-person"></i> Full Name
                            </label>
                            <input type="text" 
                                   name="name" 
                                   class="profile-form-control form-control" 
                                   value="<?php echo e(old('name', $user->name)); ?>" 
                                   required
                                   placeholder="Enter your full name">
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-phone"></i> Mobile Number
                            </label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" 
                                       class="profile-form-control form-control" 
                                       value="<?php echo e(preg_replace('/^\+91/', '', $user->mobile)); ?>" 
                                       readonly 
                                       disabled>
                            </div>
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Mobile number cannot be changed for security reasons
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-envelope"></i> Email Address <span class="text-muted">(Optional)</span>
                            </label>
                            <input type="email" 
                                   name="email" 
                                   class="profile-form-control form-control" 
                                   value="<?php echo e(old('email', $user->email)); ?>"
                                   placeholder="Enter your email address">
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Email address is optional but recommended for order updates
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-image"></i> Profile Picture <span class="text-muted">(Optional)</span>
                            </label>
                            <div class="avatar-upload-container">
                                <div class="avatar-preview-wrapper">
                                    <?php if($user->avatar_url): ?>
                                        <img src="<?php echo e($user->avatar_url); ?>" alt="Current avatar" id="avatarPreview" class="avatar-preview-img">
                                    <?php else: ?>
                                        <div class="avatar-preview-placeholder" id="avatarPreview">
                                            <i class="bi bi-person-circle"></i>
                                            <span>No image</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="avatar-upload-controls">
                                    <input type="file" 
                                           name="avatar" 
                                           id="avatarInput" 
                                           class="form-control" 
                                           accept="image/jpeg,image/jpg,image/png,image/gif"
                                           style="display: none;">
                                    <div class="d-flex gap-2 flex-wrap">
                                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="document.getElementById('avatarInput').click();">
                                            <i class="bi bi-upload"></i> Choose Image
                                        </button>
                                        <?php if($user->avatar_url): ?>
                                            <button type="button" class="btn btn-outline-danger btn-sm" id="removeAvatarBtn">
                                                <i class="bi bi-trash"></i> Remove
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                    <input type="hidden" name="remove_avatar" id="removeAvatarFlag" value="0">
                                    <div class="profile-form-help mt-2">
                                        <i class="bi bi-info-circle"></i>
                                        Maximum file size: 2MB. Allowed formats: JPEG, PNG, GIF
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-receipt"></i> GST Number <span class="text-muted">(Optional)</span>
                            </label>
                            <input type="text"
                                   name="gst_number"
                                   class="profile-form-control form-control"
                                   value="<?php echo e(old('gst_number', $user->gst_number)); ?>"
                                   maxlength="15"
                                   pattern="[0-9A-Z]{15}"
                                   placeholder="15-digit GSTIN (e.g., 29ABCDE1234F2Z5)">
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Enter a 15-character GSTIN if you need invoices with GST details.
                            </div>
                        </div>

                        <div class="mt-4 d-flex gap-3 flex-wrap">
                            <button type="submit" class="btn-profile-primary">
                                <i class="bi bi-check-circle"></i> Update Profile
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Change Password -->
            <div class="change-password-card">
                <div class="profile-card-header">
                    <h5>
                        <i class="bi bi-shield-lock"></i> Change Password
                    </h5>
                </div>
                <div class="profile-card-body">
                    <form action="<?php echo e(route('customer.profile.change-password')); ?>" method="POST">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-shield-lock"></i> New Password
                            </label>
                            <input type="password"
                                   name="password"
                                   class="profile-form-control form-control <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                   placeholder="Enter a new password"
                                   required>
                            <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Use at least 8 characters with a mix of letters and numbers.
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-lock-fill"></i> Confirm New Password
                            </label>
                            <input type="password"
                                   name="password_confirmation"
                                   class="profile-form-control form-control"
                                   placeholder="Re-enter your new password"
                                   required>
                        </div>

                        <div class="mt-3">
                            <button type="submit" class="btn-profile-primary">
                                <i class="bi bi-arrow-repeat"></i> Update Password
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Saved Addresses -->
            <div class="profile-card-modern">
                <div class="profile-card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <h5 class="mb-0">
                        <i class="bi bi-geo-alt"></i> Saved Addresses
                    </h5>
                    <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#addAddressModal">
                        <i class="bi bi-plus-circle"></i> Add New Address
                    </button>
                </div>
                <div class="profile-card-body">
                    <?php $__empty_1 = true; $__currentLoopData = $user->addresses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $address): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <div class="address-card">
                            <div class="address-card-header">
                                <div class="address-name">
                                    <i class="bi bi-person"></i>
                                    <?php echo e($address->name); ?>

                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <?php if($address->is_default): ?>
                                        <span class="address-default-badge">
                                            <i class="bi bi-check-circle"></i> Default
                                        </span>
                                    <?php endif; ?>
                    <button type="button"
                            class="btn btn-primary"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editAddressModal"
                                            data-update-action="<?php echo e(route('customer.addresses.update', $address)); ?>"
                                            data-name="<?php echo e($address->name); ?>"
                                            data-mobile="<?php echo e(preg_replace('/^\+91/', '', $address->mobile)); ?>"
                                            data-line1="<?php echo e($address->line1); ?>"
                                            data-line2="<?php echo e($address->line2); ?>"
                                            data-country="<?php echo e($address->country_id); ?>"
                                            data-state="<?php echo e($address->state_id); ?>"
                                            data-city="<?php echo e($address->city_id); ?>"
                                            data-state-name="<?php echo e($address->stateRelation?->name ?? $address->state); ?>"
                                            data-city-name="<?php echo e($address->cityRelation?->name ?? $address->city); ?>"
                                            data-pin="<?php echo e($address->pin); ?>"
                                            data-default="<?php echo e($address->is_default ? '1' : '0'); ?>">
                                        <i class="bi bi-pencil-square"></i>
                                        Edit
                                    </button>
                                </div>
                            </div>
                            <div class="address-details">
                                <div class="address-detail-item">
                                    <i class="bi bi-telephone"></i>
                                    <span><?php echo e($address->mobile); ?></span>
                                </div>
                                <div class="address-detail-item">
                                    <i class="bi bi-geo-alt-fill"></i>
                                    <span><?php echo e($address->full_address); ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="empty-address">
                            <i class="bi bi-inbox"></i>
                            <h6 class="mt-3 mb-2">No Saved Addresses</h6>
                            <p class="text-muted mb-0">You haven't saved any addresses yet. Add one to speed up checkout.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-3">
            <!-- Profile Stats -->
            <?php
                $orderCount = \App\Models\Order::where('user_id', $user->id)->count();
                $addressCount = $user->addresses->count();
            ?>
            <div class="profile-stats-card">
                <div class="profile-stats-grid">
                    <div>
                        <div class="profile-stats-title">Total Orders</div>
                        <div class="profile-stats-value"><?php echo e($orderCount); ?></div>
                    </div>
                    <div>
                        <div class="profile-stats-title">Saved Addresses</div>
                        <div class="profile-stats-value"><?php echo e($addressCount); ?></div>
                    </div>
                </div>
            </div>

            <!-- Quick Links -->
            <div class="quick-links-card">
                <div class="quick-links-header">
                    <h5>
                        <i class="bi bi-link-45deg"></i> Quick Links
                    </h5>
                </div>
                <ul class="quick-links-list">
                    <li class="quick-links-item">
                        <a href="<?php echo e(route('customer.orders.index')); ?>">
                            <i class="bi bi-box-seam"></i>
                            <span>My Orders</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="<?php echo e(route('cart.index')); ?>">
                            <i class="bi bi-cart3"></i>
                            <span>Shopping Cart</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="<?php echo e(route('checkout.index')); ?>">
                            <i class="bi bi-bag-check"></i>
                            <span>Checkout</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="<?php echo e(route('home')); ?>">
                            <i class="bi bi-house"></i>
                            <span>Continue Shopping</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Add Address Modal -->
<div class="modal fade mt-5" id="addAddressModal" tabindex="-1" aria-labelledby="addAddressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content brand-modal">
            <div class="modal-header">
                <h5 class="modal-title" id="addAddressModalLabel">Add New Address</h5>
                <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
            </div>
            <form action="<?php echo e(route('customer.addresses.store')); ?>" method="POST" class="address-form" data-address-form>
                <?php echo csrf_field(); ?>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" value="<?php echo e(old('name', $user->name)); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Mobile *</label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" name="mobile" class="form-control" placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" value="<?php echo e(old('mobile', preg_replace('/^\+91/', '', $user->mobile))); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control" value="<?php echo e(old('line1')); ?>" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 2</label>
                            <input type="text" name="line2" class="form-control" value="<?php echo e(old('line2')); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Country *</label>
                            <select name="country_id" class="form-select" required data-country-select data-selected-country="<?php echo e(old('country_id')); ?>" onchange="onCountryChange(this.form, this.value);">
                                <option value="">Select country</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">State *</label>
                            <select name="state_id" class="form-select" required data-state-select data-selected-state="<?php echo e(old('state_id')); ?>" disabled onchange="onStateChange(this.form, this.value);">
                                <option value="">Select state</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">City *</label>
                            <select name="city_id" class="form-select" required data-city-select data-selected-city="<?php echo e(old('city_id')); ?>" disabled onchange="onCityChange(this.form, this.value);">
                                <option value="">Select city</option>
                            </select>
                        </div>
                        <input type="hidden" name="state" data-state-name value="<?php echo e(old('state')); ?>">
                        <input type="hidden" name="city" data-city-name value="<?php echo e(old('city')); ?>">
                        <div class="col-md-4">
                            <label class="form-label">PIN Code *</label>
                            <input type="text" name="pin" class="form-control" maxlength="6" value="<?php echo e(old('pin')); ?>" required>
                        </div>
                        <div class="col-md-8 d-flex align-items-center mt-4">
                            <div class="form-check">
                                <input type="checkbox" name="is_default" value="1" class="form-check-input" id="addIsDefault">
                                <label class="form-check-label" for="addIsDefault">Set as default address</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Address</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Address Modal -->
<div class="modal fade mt-5" id="editAddressModal" tabindex="-1" aria-labelledby="editAddressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content brand-modal">
            <div class="modal-header">
                <h5 class="modal-title" id="editAddressModalLabel">Edit Address</h5>
                <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
            </div>
            <form id="editAddressForm" method="POST" class="address-form" data-address-form>
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Mobile *</label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" name="mobile" class="form-control" placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" required>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 2</label>
                            <input type="text" name="line2" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Country *</label>
                            <select name="country_id" class="form-select" required data-country-select onchange="onCountryChange(this.form, this.value);">
                                <option value="">Select country</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">State *</label>
                            <select name="state_id" class="form-select" required data-state-select disabled onchange="onStateChange(this.form, this.value);">
                                <option value="">Select state</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">City *</label>
                            <select name="city_id" class="form-select" required data-city-select disabled onchange="onCityChange(this.form, this.value);">
                                <option value="">Select city</option>
                            </select>
                        </div>
                        <input type="hidden" name="state" data-state-name>
                        <input type="hidden" name="city" data-city-name>
                        <div class="col-md-4">
                            <label class="form-label">PIN Code *</label>
                            <input type="text" name="pin" class="form-control" maxlength="6" required>
                        </div>
                        <div class="col-md-8 d-flex align-items-center mt-4">
                            <div class="form-check">
                                <input type="checkbox" name="is_default" value="1" class="form-check-input" id="editIsDefault">
                                <label class="form-check-label" for="editIsDefault">Set as default address</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Address</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
const shippingApiBase = '/api/shipping';

function resetSelect(selectEl, placeholder) {
    if (!selectEl) return;
    selectEl.innerHTML = `<option value="">${placeholder}</option>`;
    selectEl.disabled = true;
}

function populateSelect(selectEl, items, placeholder, selectedId = null) {
    if (!selectEl) return;
    const options = [`<option value=\"\">${placeholder}</option>`];
    items.forEach(item => {
        const selected = selectedId && Number(selectedId) === Number(item.id) ? 'selected' : '';
        options.push(`<option value=\"${item.id}\" ${selected}>${item.name}</option>`);
    });
    selectEl.innerHTML = options.join('');
    selectEl.disabled = items.length === 0;
}

async function fetchJson(url) {
    const response = await fetch(url, { headers: { Accept: 'application/json' } });
    if (!response.ok) throw new Error('Failed to load data');
    return response.json();
}

async function loadCountries(form) {
    const countrySelect = form.querySelector('[data-country-select]');
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    if (!countrySelect) return;

    const data = await fetchJson(`${shippingApiBase}/countries`);
    const countries = data.data || [];
    let selectedCountry = countrySelect.dataset.selectedCountry || '';
    if (!selectedCountry) {
        const india = countries.find(c => c.code === 'IN');
        selectedCountry = india ? india.id : '';
    }

    populateSelect(countrySelect, countries, 'Select country', selectedCountry);

    if (selectedCountry) {
        await loadStates(form, selectedCountry, stateSelect?.dataset.selectedState || '');
    } else {
        resetSelect(stateSelect, 'Select state');
        resetSelect(citySelect, 'Select city');
    }
}

function onCountryChange(form, countryId) {
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');

    resetSelect(stateSelect, 'Loading states...');
    resetSelect(citySelect, 'Select city');
    if (countryId) {
        loadStates(form, countryId);
    }
    syncHiddenLocationNames(form);
}

function onStateChange(form, stateId) {
    const citySelect = form.querySelector('[data-city-select]');
    resetSelect(citySelect, 'Loading cities...');
    // const stateId = stateId;
    if (stateId) {
        loadCities(form, stateId);
    }
    syncHiddenLocationNames(form);
}

function onCityChange(form, cityId) {
    syncHiddenLocationNames(form);
}

async function loadStates(form, countryId, selectedStateId = '') {
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    if (!stateSelect || !countryId) return;
    resetSelect(stateSelect, 'Loading states...');
    resetSelect(citySelect, 'Select city');
    const data = await fetchJson(`${shippingApiBase}/states?country_id=${countryId}`);
    const states = data.data || [];
    populateSelect(stateSelect, states, 'Select state', selectedStateId);
    stateSelect.disabled = false;

    if (selectedStateId) {
        await loadCities(form, selectedStateId, citySelect?.dataset.selectedCity || '');
    }
}

async function loadCities(form, stateId, selectedCityId = '') {
    const citySelect = form.querySelector('[data-city-select]');
    if (!citySelect || !stateId) return;
    resetSelect(citySelect, 'Loading cities...');
    const data = await fetchJson(`${shippingApiBase}/cities?state_id=${stateId}`);
    const cities = data.data || [];
    populateSelect(citySelect, cities, 'Select city', selectedCityId);
    citySelect.disabled = false;
}

function syncHiddenLocationNames(form) {
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    const stateName = form.querySelector('[data-state-name]');
    const cityName = form.querySelector('[data-city-name]');

    if (stateSelect && stateName) {
        const selected = stateSelect.options[stateSelect.selectedIndex];
        stateName.value = selected ? selected.textContent.trim() : '';
    }
    if (citySelect && cityName) {
        const selected = citySelect.options[citySelect.selectedIndex];
        cityName.value = selected ? selected.textContent.trim() : '';
    }
}

function attachAddressFormHandlers(form) {
    const countrySelect = form.querySelector('[data-country-select]');
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');

    if (countrySelect) {
        countrySelect.addEventListener('change', async (e) => {
            resetSelect(stateSelect, 'Loading states...');
            resetSelect(citySelect, 'Select city');
            const countryId = e.target.value;
            countrySelect.dataset.selectedCountry = countryId;
            if (countryId) {
                await loadStates(form, countryId);
            }
        });
    }

    if (stateSelect) {
        stateSelect.addEventListener('change', async (e) => {
            resetSelect(citySelect, 'Loading cities...');
            const stateId = e.target.value;
            stateSelect.dataset.selectedState = stateId;
            if (stateId) {
                await loadCities(form, stateId);
            }
            syncHiddenLocationNames(form);
        });
    }

    if (citySelect) {
        citySelect.addEventListener('change', () => syncHiddenLocationNames(form));
    }

    form.addEventListener('submit', () => syncHiddenLocationNames(form));
}

async function initAddressForm(form) {
    attachAddressFormHandlers(form);
    try {
        await loadCountries(form);
    } catch (error) {
        console.error('Failed to load address dropdowns', error);
    }
}

// Avatar upload and preview functionality
document.addEventListener('DOMContentLoaded', () => {
    const avatarInput = document.getElementById('avatarInput');
    const avatarPreview = document.getElementById('avatarPreview');
    const removeAvatarBtn = document.getElementById('removeAvatarBtn');
    const removeAvatarFlag = document.getElementById('removeAvatarFlag');

    // Handle file selection
    if (avatarInput) {
        avatarInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // Validate file size (2MB)
                if (file.size > 2048 * 1024) {
                    alert('File size must be less than 2MB');
                    this.value = '';
                    return;
                }

                // Validate file type
                const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                if (!validTypes.includes(file.type)) {
                    alert('Please select a valid image file (JPEG, PNG, or GIF)');
                    this.value = '';
                    return;
                }

                // Show preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    if (avatarPreview) {
                        // Check if it's the placeholder div or an img
                        if (avatarPreview.classList.contains('avatar-preview-placeholder')) {
                            // Replace placeholder with img
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            img.className = 'avatar-preview-img';
                            img.alt = 'Avatar preview';
                            img.id = 'avatarPreview';
                            avatarPreview.parentNode.replaceChild(img, avatarPreview);
                        } else {
                            // Update existing img
                            avatarPreview.src = e.target.result;
                        }
                    }
                };
                reader.readAsDataURL(file);
            }
        });
    }

    // Handle remove avatar button
    if (removeAvatarBtn) {
        removeAvatarBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to remove your profile picture?')) {
                // Set remove flag
                if (removeAvatarFlag) {
                    removeAvatarFlag.value = '1';
                }
                
                // Clear file input
                if (avatarInput) {
                    avatarInput.value = '';
                }
                
                // Show placeholder
                if (avatarPreview && avatarPreview.tagName === 'IMG') {
                    const placeholder = document.createElement('div');
                    placeholder.className = 'avatar-preview-placeholder';
                    placeholder.id = 'avatarPreview';
                    placeholder.innerHTML = '<i class="bi bi-person-circle"></i><span>No image</span>';
                    avatarPreview.parentNode.replaceChild(placeholder, avatarPreview);
                }
                
                // Hide remove button
                this.style.display = 'none';
            }
        });
    }

    // Address form initialization
    document.querySelectorAll('[data-address-form]').forEach((form) => {
        initAddressForm(form);
    });

    const editModal = document.getElementById('editAddressModal');
    const editForm = document.getElementById('editAddressForm');

    if (editModal && editForm) {
        editModal.addEventListener('show.bs.modal', async (event) => {
            const button = event.relatedTarget;
            if (!button) return;

            editForm.action = button.dataset.updateAction || '#';
            editForm.querySelector('input[name="name"]').value = button.dataset.name || '';
            editForm.querySelector('input[name="mobile"]').value = button.dataset.mobile || '';
            editForm.querySelector('input[name="line1"]').value = button.dataset.line1 || '';
            editForm.querySelector('input[name="line2"]').value = button.dataset.line2 || '';
            editForm.querySelector('input[name="pin"]').value = button.dataset.pin || '';

            const defaultCheckbox = editForm.querySelector('input[name="is_default"]');
            if (defaultCheckbox) {
                defaultCheckbox.checked = button.dataset.default === '1';
            }

            const countrySelect = editForm.querySelector('[data-country-select]');
            const stateSelect = editForm.querySelector('[data-state-select]');
            const citySelect = editForm.querySelector('[data-city-select]');

            if (countrySelect) countrySelect.dataset.selectedCountry = button.dataset.country || '';
            if (stateSelect) stateSelect.dataset.selectedState = button.dataset.state || '';
            if (citySelect) citySelect.dataset.selectedCity = button.dataset.city || '';

            const stateName = editForm.querySelector('[data-state-name]');
            const cityName = editForm.querySelector('[data-city-name]');
            if (stateName) stateName.value = button.dataset.stateName || '';
            if (cityName) cityName.value = button.dataset.cityName || '';

            try {
                await loadCountries(editForm);
                syncHiddenLocationNames(editForm);
            } catch (error) {
                console.error('Failed to load address data', error);
            }
        });
    }
});
</script>
<?php $__env->stopPush(); ?>
<?php $__env->startPush('styles'); ?>
<style>
/* Avatar Upload Styles */
.avatar-upload-container {
    display: flex;
    gap: 1.5rem;
    align-items: flex-start;
    flex-wrap: wrap;
    align-items: center;
}

.avatar-preview-wrapper {
    flex-shrink: 0;
}

.avatar-preview-img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 50%;
    border: 1px solid var(--color-primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-preview-placeholder {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 3px dashed #dee2e6;
    display: flex;
    flex-direction: column;
    align-items: center;
    /* justify-content: center; */
    background-color: #f8f9fa;
    color: #6c757d;
}

.avatar-preview-placeholder i {
    font-size: 3rem;
    margin-bottom: 0.5rem;
}

.avatar-preview-placeholder span {
    font-size: 0.875rem;
}

.avatar-upload-controls {
    flex: 1;
    min-width: 200px;
}

.profile-avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
}

.brand-modal .modal-header {
    background: linear-gradient(135deg, var(--color-primary), var(--color-secondary));
    color: #ffffff;
    border-bottom: none;
}
.brand-modal .modal-title {
    font-weight: 700;
}
.brand-modal .btn-close {
    filter: invert(1);
}
.brand-modal .modal-content {
    border: none;
    box-shadow: 0 12px 30px rgba(0,0,0,0.12);
    border-radius: 14px;
}
.brand-modal .form-control,
.brand-modal .form-select {
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 0.65rem 0.85rem;
    box-shadow: none;
    transition: var(--transition);
}
.brand-modal .form-control:focus,
.brand-modal .form-select:focus {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 0.2rem rgba(19,35,60,0.1);
}
.brand-modal .form-label {
    color: var(--text-dark);
    font-weight: 600;
}
.brand-modal .modal-footer {
    border-top: 1px solid var(--border-color);
}
.brand-modal .modal-body {
    overflow: visible;
}
.brand-link {
    color: var(--color-primary) !important;
    font-weight: 600;
}
.brand-link:hover {
    color: var(--color-secondary) !important;
    text-decoration: none;
}
.brand-modal select,
.brand-modal .form-select {
    position: relative;
    z-index: 1065;
}
.brand-modal .select2-container {
    z-index: 2000 !important;
}
.select2-dropdown.select2-dropdown--below {
    z-index: 9999;
}
</style>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/shaa_jewels/live/resources/views/customer/profile.blade.php ENDPATH**/ ?>