<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Glowify Beauty - Daftar Akun Skincare</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Poppins', 'Inter', sans-serif;
            background: linear-gradient(135deg, #ffe4f0 0%, #ffc0dd 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }
        .register-card {
            background: #ffffffdd;
            backdrop-filter: blur(2px);
            border-radius: 2rem;
            box-shadow: 0 25px 45px -12px rgba(219, 39, 119, 0.25);
            width: 100%;
            max-width: 920px;
            margin: 0 auto;
            border: 1px solid #ffb7d2;
            overflow: hidden;
            transition: all 0.2s ease;
        }
        .card-header {
            background: linear-gradient(115deg, #f9a8d4 0%, #f472b6 40%, #ec489a 100%);
            padding: 1.25rem 2rem;
            border-bottom: 1px solid #ffc0dd;
        }
        .input-wrapper { position: relative; width: 100%; }
        .input-field {
            width: 100%;
            border: 1.5px solid #fbcfe8;
            border-radius: 0.75rem;
            padding: 0.7rem 1rem 0.7rem 2.5rem;
            font-size: 0.9rem;
            transition: all 0.2s ease;
            background: white;
            color: #1e293b;
        }
        .input-field:hover { border-color: #f9a8d4; }
        .input-field:focus {
            border-color: #f472b6;
            box-shadow: 0 0 0 3px rgba(244,114,182,.15);
            outline: none;
        }
        .input-field::placeholder { color: #94a3b8; font-size: 0.85rem; }
        .input-field[readonly] { background: #fff0f5; cursor: default; color: #b45f7a; }
        .input-wrapper i:not(.toggle-password) {
            position: absolute;
            left: 0.85rem;
            top: 50%;
            transform: translateY(-50%);
            color: #f472b6;
            font-size: 0.95rem;
            z-index: 10;
            opacity: 0.7;
        }
        .input-wrapper:focus-within i:not(.toggle-password) { opacity: 1; color: #ec489a; }
        select.input-field {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23f472b6' stroke-width='2'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
            background-position: right 0.75rem center;
            background-repeat: no-repeat;
            background-size: 1rem;
            padding-right: 2.5rem;
            background-color: white;
            cursor: pointer;
        }
        .button-container { display: flex; gap: 1rem; padding: 0 2rem 1.5rem 2rem; }
        .btn-primary {
            background: linear-gradient(95deg, #f472b6, #ec489a);
            color: white; font-weight: 600; font-size: 0.95rem;
            padding: 0.75rem 1.5rem; border-radius: 0.75rem; border: none;
            cursor: pointer; transition: all 0.2s ease; flex: 1;
            display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem;
            box-shadow: 0 6px 14px rgba(236,72,153,0.25);
        }
        .btn-primary:hover {
            background: linear-gradient(95deg, #ec489a, #db2777);
            box-shadow: 0 8px 18px rgba(236,72,153,0.35);
            transform: translateY(-2px);
        }
        .btn-secondary {
            background: white; color: #f472b6; font-weight: 600; font-size: 0.95rem;
            padding: 0.75rem 1.5rem; border-radius: 0.75rem; border: 1.5px solid #f472b6;
            cursor: pointer; transition: all 0.2s ease; flex: 1;
            display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem;
        }
        .btn-secondary:hover {
            background: #fff0f7; border-color: #ec489a; color: #ec489a;
            transform: translateY(-2px); box-shadow: 0 6px 12px rgba(244,114,182,.15);
        }
        .form-container { padding: 1.5rem 2rem 0.5rem 2rem; }
        .form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
        .full-width { grid-column: span 2; }
        .region-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin-bottom: 1rem; }
        .password-wrapper { position: relative; }
        .toggle-password {
            position: absolute; right: 1rem; top: 50%; transform: translateY(-50%);
            cursor: pointer; color: #c0849b; z-index: 20; font-size: 1rem;
        }
        .toggle-password:hover { color: #ec489a; }
        .password-hint {
            background: #ffeef5; border-radius: 2rem; padding: 0.4rem 1rem;
            margin: 0rem 2rem 0.8rem 2rem;
            display: inline-flex; align-items: center; gap: 0.5rem;
            border: 1px solid #fbcfe8;
        }
        .password-hint i { color: #f472b6; font-size: 0.8rem; }
        .password-hint span { color: #6b4e5e; font-size: 0.75rem; font-weight: 500; }
        .role-container {
            grid-column: span 2; display: flex; align-items: center; gap: 1rem;
            background: #fff0f8; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid #fbcfe8;
        }
        .role-container label { color: #b45f7a; font-weight: 600; font-size: 0.9rem; min-width: 110px; }
        .role-container select {
            flex: 1; border: 1.5px solid #fbcfe8; border-radius: 0.5rem; padding: 0.5rem;
            font-size: 0.9rem; background: white; cursor: pointer;
            appearance: none; -webkit-appearance: none; pointer-events: none;
        }
        .login-link {
            text-align: center; padding: 1rem 2rem 1.5rem;
            background: #fff0f8; border-top: 1px solid #fbcfe8;
        }
        .login-link p { color: #7e5b6b; font-size: 0.9rem; }
        .login-link a {
            color: #f472b6; font-weight: 600; text-decoration: none;
            transition: all 0.2s ease; display: inline-flex; align-items: center; gap: 0.25rem;
        }
        .login-link a:hover { color: #ec489a; text-decoration: underline; }
        .error-alert {
            margin: 1rem 2rem 0; background: #ffe4e4;
            border-left: 4px solid #f43f5e; border-radius: 0.75rem; padding: 0.75rem 1rem;
        }
        .skincare-icon {
            background: rgba(255,255,255,.25); backdrop-filter: blur(4px);
            border-radius: 9999px; padding: 0.7rem;
            display: inline-flex; align-items: center; justify-content: center;
        }
        .skincare-icon i { font-size: 1.3rem; color: white; }
        textarea.input-field { resize: none; min-height: 80px; }
        #regionSection { grid-column: span 2; }

        /* Geocode status - pink theme */
        .geocode-status {
            display: none;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 0.9rem;
            border-radius: 1.5rem;
            font-size: 0.75rem;
            margin-bottom: 0.75rem;
            font-weight: 500;
        }
        .geocode-status.loading { display: flex; background: #f0e6ff; color: #a45ee5; }
        .geocode-status.success { display: flex; background: #e6faf0; color: #0f7b3a; }
        .geocode-status.error   { display: flex; background: #ffe6e6; color: #e11d48; }
    </style>
</head>
<body>
<div class="register-card">

    {{-- Header dengan sentuhan skincare --}}
    <div class="card-header">
        <div class="flex items-center gap-3">
            <div class="skincare-icon"><i class="fa-regular fa-face-smile"></i></div>
            <div>
                <h1 class="text-xl font-bold text-white tracking-tight">✨ Daftar Akun Glowify</h1>
                <p class="text-xs text-white/80">Skincare & Kecantikan — Rawat kulitmu dari sekarang</p>
            </div>
        </div>
    </div>

    {{-- Error tetap dipertahankan --}}
    @if ($errors->any())
    <div class="error-alert">
        <div class="flex items-start gap-2">
            <i class="fa-regular fa-circle-exclamation text-rose-500 mt-0.5 text-sm"></i>
            <ul class="text-xs text-rose-800 list-disc list-inside">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    </div>
    @endif

    {{-- Form registrasi dengan fungsi penuh --}}
    <form method="POST" action="{{ route('register') }}" id="registerForm">
        @csrf

        <div class="form-container">
            <div class="form-grid">

                {{-- Nama Lengkap --}}
                <div class="input-wrapper full-width">
                    <i class="fa-regular fa-user"></i>
                    <input type="text" name="name" class="input-field"
                        placeholder="Nama Lengkap" value="{{ old('name') }}" required>
                </div>

                {{-- Email --}}
                <div class="input-wrapper full-width">
                    <i class="fa-regular fa-envelope"></i>
                    <input type="email" id="email" name="email" class="input-field"
                        placeholder="Email" value="{{ old('email') }}" required>
                </div>

                {{-- No HP --}}
                <div class="input-wrapper full-width">
                    <i class="fa-solid fa-phone"></i>
                    <input type="text" name="no_hp" class="input-field"
                        placeholder="No HP" value="{{ old('no_hp') }}">
                </div>

                {{-- Wilayah + Koordinat otomatis (fungsi geocoding tetap sama) --}}
                <div id="regionSection" class="full-width">

                    {{-- Wilayah berantai provinsi, kota, kecamatan, desa --}}
                    <div class="region-grid">
                        <div class="input-wrapper">
                            <i class="fa-solid fa-map-pin"></i>
                            <select name="province_code" id="province" class="input-field">
                                <option value="" disabled selected>Provinsi</option>
                                @foreach($provinces as $prov)
                                <option value="{{ $prov->code }}"
                                        data-name="{{ $prov->name }}"
                                        {{ old('province_code') == $prov->code ? 'selected' : '' }}>
                                    {{ $prov->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="input-wrapper">
                            <i class="fa-solid fa-city"></i>
                            <select name="city_code" id="city" class="input-field">
                                <option value="" disabled selected>Kota</option>
                            </select>
                        </div>
                        <div class="input-wrapper">
                            <i class="fa-solid fa-map"></i>
                            <select name="district_code" id="district" class="input-field">
                                <option value="" disabled selected>Kecamatan</option>
                            </select>
                        </div>
                        <div class="input-wrapper">
                            <i class="fa-solid fa-location-dot"></i>
                            <select name="village_code" id="village" class="input-field">
                                <option value="" disabled selected>Desa/Kelurahan</option>
                            </select>
                        </div>
                    </div>

                    {{-- Alamat & Kode Pos --}}
                    <div class="region-grid">
                        <div class="input-wrapper">
                            <i class="fa-regular fa-address-card"></i>
                            <textarea name="alamat_lengkap" rows="2" class="input-field"
                                placeholder="Alamat Lengkap (jalan, rt/rw, dll)">{{ old('alamat_lengkap') }}</textarea>
                        </div>
                        <div class="input-wrapper">
                            <i class="fa-regular fa-note-sticky"></i>
                            <input type="text" name="kode_pos" class="input-field"
                                placeholder="Kode Pos" value="{{ old('kode_pos') }}"
                                inputmode="numeric" pattern="[0-9]*"
                                oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                        </div>
                    </div>

                    {{-- Status geocode --}}
                    <div id="geocodeStatus" class="geocode-status"></div>

                    {{-- Koordinat readonly otomatis --}}
                    <div class="region-grid" style="margin-bottom:0.5rem;">
                        <div class="input-wrapper">
                            <i class="fa-solid fa-crosshairs"></i>
                            <input type="text" name="latitude" id="latitude"
                                   class="input-field" placeholder="Latitude (otomatis)"
                                   value="{{ old('latitude') }}" readonly>
                        </div>
                        <div class="input-wrapper">
                            <i class="fa-solid fa-crosshairs"></i>
                            <input type="text" name="longitude" id="longitude"
                                   class="input-field" placeholder="Longitude (otomatis)"
                                   value="{{ old('longitude') }}" readonly>
                        </div>
                    </div>

                    <p style="font-size:0.7rem; color:#b57c96; text-align:center; margin-bottom:1rem;">
                        <i class="fa-regular fa-heart" style="color:#f472b6;"></i>
                        Koordinat terisi otomatis saat memilih desa/kelurahan (geocoding)
                    </p>

                </div>{{-- end regionSection --}}

                {{-- Password --}}
                <div class="input-wrapper password-wrapper">
                    <i class="fa-solid fa-lock"></i>
                    <input type="password" id="password" name="password" class="input-field"
                        placeholder="Password" required>
                    <i class="fa-regular fa-eye toggle-password" onclick="togglePassword('password', this)"></i>
                </div>

                {{-- Konfirmasi Password --}}
                <div class="input-wrapper password-wrapper">
                    <i class="fa-solid fa-lock"></i>
                    <input type="password" id="password_confirmation" name="password_confirmation"
                        class="input-field" placeholder="Konfirmasi Password" required>
                    <i class="fa-regular fa-eye toggle-password" onclick="togglePassword('password_confirmation', this)"></i>
                </div>

                {{-- Role (hanya user, fungsi tetap) --}}
                <div class="role-container">
                    <label>🌸 Daftar Sebagai</label>
                    <select name="role" required>
                        <option value="user" {{ old('role') == 'user' ? 'selected' : '' }}>Pembeli (Customer)</option>
                    </select>
                </div>

            </div>
        </div>

        <div class="password-hint">
            <i class="fa-regular fa-lightbulb"></i>
            <span>Minimal 8 karakter — jaga kecantikan akunmu</span>
        </div>

        <div class="button-container">
            <a href="{{ route('login') }}" class="btn-secondary"><i class="fa-regular fa-arrow-left"></i> Kembali</a>
            <button type="submit" class="btn-primary"><i class="fa-regular fa-user-plus"></i> Daftar Sekarang</button>
        </div>
    </form>

    <div class="login-link">
        <p>Sudah punya akun Glowify? <a href="{{ route('login') }}">Masuk <i class="fa-regular fa-arrow-right"></i></a></p>
    </div>
</div>

<script>
// ============================================================
// FUNGSI ASLI TIDAK BERUBAH:
// - Toggle password
// - Geocoding nominatim (koordinat otomatis)
// - Chain select provinsi, kota, kecamatan, desa
// - Sembunyikan region jika email admin/penjual
// - Validasi password tidak cocok
// - Restore old values dari Laravel
// ============================================================

const wilayah = { province: '', city: '', district: '', village: '' };

function togglePassword(inputId, icon) {
    const input = document.getElementById(inputId);
    input.type = input.type === 'password' ? 'text' : 'password';
    icon.classList.toggle('fa-eye');
    icon.classList.toggle('fa-eye-slash');
}

async function geocode() {
    const parts = [
        wilayah.village,
        wilayah.district,
        wilayah.city,
        wilayah.province,
        'Indonesia'
    ].filter(Boolean);

    if (parts.length < 3) return;

    const query = parts.join(', ');
    setGeoStatus('loading', '<i class="fa-solid fa-circle-notch fa-spin"></i> Mencari koordinat...');

    try {
        const response = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=1&countrycodes=id`, {
            headers: { 'Accept-Language': 'id,en' }
        });
        const data = await response.json();
        if (data && data.length > 0) {
            setKoordinat(data[0].lat, data[0].lon);
            setGeoStatus('success', '<i class="fa-regular fa-circle-check"></i> Koordinat ditemukan (OpenStreetMap)');
        } else {
            const fallback = [wilayah.city, wilayah.province, 'Indonesia'].filter(Boolean).join(', ');
            const fallbackRes = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(fallback)}&format=json&limit=1&countrycodes=id`);
            const fallbackData = await fallbackRes.json();
            if (fallbackData && fallbackData.length > 0) {
                setKoordinat(fallbackData[0].lat, fallbackData[0].lon);
                setGeoStatus('success', '<i class="fa-regular fa-circle-check"></i> Koordinat perkiraan (kota)');
            } else {
                setGeoStatus('error', '<i class="fa-regular fa-circle-xmark"></i> Koordinat tidak ditemukan');
            }
        }
    } catch (err) {
        setGeoStatus('error', '<i class="fa-regular fa-circle-xmark"></i> Gagal koneksi ke layanan peta');
    }
}

function setKoordinat(lat, lng) {
    document.getElementById('latitude').value  = parseFloat(lat).toFixed(7);
    document.getElementById('longitude').value = parseFloat(lng).toFixed(7);
}

function clearKoordinat() {
    document.getElementById('latitude').value  = '';
    document.getElementById('longitude').value = '';
    document.getElementById('geocodeStatus').className = 'geocode-status';
}

function setGeoStatus(type, html) {
    const el = document.getElementById('geocodeStatus');
    el.className = 'geocode-status ' + type;
    el.innerHTML = html;
}

document.addEventListener('DOMContentLoaded', function () {

    const provinceSelect = document.getElementById('province');
    const citySelect     = document.getElementById('city');
    const districtSelect = document.getElementById('district');
    const villageSelect  = document.getElementById('village');
    const emailInput     = document.getElementById('email');
    const regionSection  = document.getElementById('regionSection');
    const password       = document.getElementById('password');
    const confirmPassword = document.getElementById('password_confirmation');
    const form           = document.getElementById('registerForm');

    async function fetchData(url, targetSelect, placeholder) {
        try {
            const res  = await fetch(url);
            const data = await res.json();
            targetSelect.innerHTML = `<option value="" disabled selected>${placeholder}</option>`;
            data.forEach(item => {
                targetSelect.innerHTML += `<option value="${item.code}" data-name="${item.name}">${item.name}</option>`;
            });
        } catch (e) { console.error('Fetch error:', e); }
    }

    // Fungsi sembunyikan region jika email admin/penjual (tetap)
    function checkEmail() {
        if (!emailInput || !regionSection) return;
        const em = emailInput.value.toLowerCase().trim();
        regionSection.style.display = (em === 'admin@gmail.com' || em === 'penjual@gmail.com') ? 'none' : 'block';
    }
    emailInput?.addEventListener('input', checkEmail);
    checkEmail();

    // Event provinsi
    provinceSelect?.addEventListener('change', function () {
        if (!this.value) return;
        wilayah.province = this.options[this.selectedIndex].dataset.name || this.options[this.selectedIndex].text;
        wilayah.city = wilayah.district = wilayah.village = '';
        clearKoordinat();
        fetchData('/get-cities/' + this.value, citySelect, 'Kota');
        districtSelect.innerHTML = '<option value="" disabled selected>Kecamatan</option>';
        villageSelect.innerHTML  = '<option value="" disabled selected>Desa/Kelurahan</option>';
    });

    citySelect?.addEventListener('change', function () {
        if (!this.value) return;
        wilayah.city = this.options[this.selectedIndex].dataset.name || this.options[this.selectedIndex].text;
        wilayah.district = wilayah.village = '';
        clearKoordinat();
        fetchData('/get-districts/' + this.value, districtSelect, 'Kecamatan');
        villageSelect.innerHTML = '<option value="" disabled selected>Desa/Kelurahan</option>';
    });

    districtSelect?.addEventListener('change', function () {
        if (!this.value) return;
        wilayah.district = this.options[this.selectedIndex].dataset.name || this.options[this.selectedIndex].text;
        wilayah.village = '';
        clearKoordinat();
        fetchData('/get-villages/' + this.value, villageSelect, 'Desa/Kelurahan');
        geocode();
    });

    villageSelect?.addEventListener('change', function () {
        if (!this.value) return;
        wilayah.village = this.options[this.selectedIndex].dataset.name || this.options[this.selectedIndex].text;
        geocode();
    });

    // Validasi password cocok
    form?.addEventListener('submit', function (e) {
        if (password && confirmPassword && password.value !== confirmPassword.value) {
            e.preventDefault();
            const msg = document.createElement('div');
            msg.className = 'fixed top-5 right-5 bg-rose-500 text-white px-5 py-3 rounded-xl shadow-xl z-50 text-sm flex items-center gap-2 font-medium';
            msg.innerHTML = '<i class="fa-solid fa-circle-exclamation"></i>Password tidak cocok!';
            document.body.appendChild(msg);
            password.style.borderColor = confirmPassword.style.borderColor = '#f43f5e';
            setTimeout(() => {
                msg.remove();
                password.style.borderColor = confirmPassword.style.borderColor = '';
            }, 2500);
        }
    });

    // Restore old values setelah validasi gagal (Laravel)
    @if(old('province_code'))
    setTimeout(() => {
        if (provinceSelect) {
            provinceSelect.value = "{{ old('province_code') }}";
            provinceSelect.dispatchEvent(new Event('change'));
            setTimeout(() => {
                if(citySelect) {
                    citySelect.value = "{{ old('city_code') }}";
                    citySelect.dispatchEvent(new Event('change'));
                }
                setTimeout(() => {
                    if(districtSelect) {
                        districtSelect.value = "{{ old('district_code') }}";
                        districtSelect.dispatchEvent(new Event('change'));
                    }
                    setTimeout(() => {
                        if(villageSelect) {
                            villageSelect.value = "{{ old('village_code') }}";
                            villageSelect.dispatchEvent(new Event('change'));
                        }
                    }, 400);
                }, 400);
            }, 400);
        }
    }, 200);
    @endif

});
</script>
</body>
</html>