@extends('frontEnd.layouts.master')
@section('title','Amazon Sign-In')
@php
    $generalsetting = \App\Models\GeneralSetting::first();
    $navLogo = $generalsetting?->white_logo;
    if ($navLogo && !Str::startsWith($navLogo, ['http', 'https'])) {
        $navLogo = ltrim(str_ireplace(['/public/', 'public/'], '', $navLogo), '/');
    }
    $smsGateway = \App\Models\SmsGateway::first();
    $smsActive  = $smsGateway && (int)$smsGateway->status === 1;
    $emailOtpOn = $smsGateway && (int)($smsGateway->email_otp ?? 0) === 1;
    $otpOn      = $smsActive || $emailOtpOn;
@endphp
@section('content')
<style>
    @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;700&family=Inter:wght@400;500;600;700&display=swap');
    :root {
        --amz-navy: #131921;
        --amz-navy-light: #232f3e;
        --amz-orange: #FF9900;
        --amz-orange-dark: #e47911;
        --amz-bg: #fff;
        --amz-border: #DDD;
        --amz-text: #0F1111;
        --amz-blue: #007185;
    }
    body { background-color: #fff; }
    .auth-wrap { background: #fff; min-height:85vh; display:flex; flex-direction:column; align-items:center; padding:30px 15px; font-family:'Inter',sans-serif; }
    .auth-box { width:100%; max-width:350px; }
    .logo-wrap { margin-bottom: 18px; display: flex; justify-content: center; }
    .auth-logo { max-height: 40px; object-fit: contain; }
    
    .auth-card { background:#fff; padding:20px 26px; border-radius:8px; border:1px solid #ddd; box-shadow:none; text-align:left; position:relative; }
    .auth-title { font-size:28px; font-weight:400; color: #111; margin:0 0 15px; letter-spacing: -0.5px; }
    
    .input-label { display:block; font-size:13px; font-weight:700; margin-bottom:4px; color: #111; }
    
    .phone-row { display:flex; align-items:center; border:1px solid #888C8C; border-radius:4px; margin-bottom:15px; overflow:hidden; transition:0.2s; box-shadow: 0 1px 2px rgba(15,17,17,.15) inset; }
    .phone-row:focus-within { border-color: #e77600; box-shadow: 0 0 3px 2px rgba(228, 121, 17, .5); }
    .phone-flag { display:flex; align-items:center; gap:6px; padding:0 12px; border-right:1px solid #ddd; background:#f0f2f2; height:34px; flex-shrink:0; }
    .phone-flag img { width:20px; height:12px; object-fit:cover; }
    .phone-flag span { font-size:13px; font-weight:600; color:#555; }
    .phone-field { flex:1; padding:0 10px; border:none; font-size:14px; color:#111; background:transparent; outline:none; height:34px; }
    
    .a-input { width:100%; height:34px; padding:0 10px; border:1px solid #888C8C; border-radius:4px; font-size:14px; outline:none; transition:0.2s; margin-bottom:15px; box-sizing:border-box; box-shadow: 0 1px 2px rgba(15,17,17,.15) inset; }
    .a-input:focus { border-color: #e77600; box-shadow: 0 0 3px 2px rgba(228, 121, 17, .5); }
    
    .a-btn { width:100%; padding:8px; background: #FFD814; border: 1px solid #FCD200; border-radius:8px; font-weight:400; font-size:13px; color:#111; cursor:pointer; transition:0.1s; margin-top:5px; display:block; box-shadow: 0 2px 5px 0 rgba(213,217,217,.5); }
    .a-btn:hover { background: #f7ca00; border-color: #f2c200; }
    .a-btn:active { background: #f0c14b; border-color: #a88734; }
    
    .a-btn.grey { background: #e7e9ec; border-color: #adb1b8; color: #111; margin-top:12px; box-shadow: none; }
    .a-btn.grey:hover { background: #d8dade; border-color: #a2a6ac; }
    
    .a-btn:disabled { opacity:0.6; cursor:not-allowed; }
    
    .step { display:none; }
    .step.active { display:block; }
    
    .a-divider { display:flex; align-items:center; color:#767676; font-size:12px; margin:22px 0 12px; }
    .a-divider::before, .a-divider::after { content:""; flex:1; height:1px; background:#e7e7e7; }
    .a-divider span { padding:0 8px; }
    

    
    .new-to-amz { font-size:12px; color:#767676; margin-bottom:12px; text-align:center; }
    
    .info-box { border-radius:4px; padding:12px 16px; margin-bottom:18px; font-size:13px; border: 1px solid; display:flex; gap:12px; align-items:flex-start; }
    .info-green { background:#f7fff9; border-color:#d0f5d3; color:#146b1e; }
    .info-blue  { background:#f0f8ff; border-color:#d0e6ff; color:#0056b3; }
    .info-yellow{ background:#fffcf0; border-color:#fceeb5; color:#856404; }
    
</style>

<section class="auth-wrap">
    <div class="auth-box">
        <div class="auth-card">
            <div class="logo-wrap">
                <a href="{{ url('/') }}">
                    <img src="{{ asset($navLogo ?? 'public/logo.png') }}" alt="Logo" class="auth-logo">
                </a>
            </div>
            
            {{-- STEP 1: Phone --}}
            <div id="s1" class="step active">
                <h1 class="auth-title">Sign in</h1>
                <label class="input-label">Mobile number</label>
                <div class="phone-row">
                    <div class="phone-flag">
                        <img src="https://flagcdn.com/w40/bd.png" alt="BD">
                        <span>+88</span>
                    </div>
                    <input type="tel" id="phone_input" class="phone-field" placeholder="01XXXXXXXXX" maxlength="11" autocomplete="tel">
                </div>
                <button id="btn_s1" class="a-btn">
                    Continue <span class="spinner-border spinner-border-sm d-none ms-2"></span>
                </button>

            </div>

            {{-- STEP 2: Email Required --}}
            <div id="s2" class="step">
                <h1 class="auth-title">Email required</h1>
                <p style="font-size:13px; margin-bottom:15px;">SMS is unavailable. Please enter your email to receive a verification code.</p>
                <label class="input-label">Email address</label>
                <input type="email" id="email_input" class="a-input" placeholder="your@email.com" autocomplete="email">
                <div id="email_status" class="info-box" style="display:none;"></div>
                <button id="btn_s2" class="a-btn">
                    Send OTP <span class="spinner-border spinner-border-sm d-none ms-2"></span>
                </button>
                <br><button class="back-link" onclick="goStep('s1')" style="margin-top:15px; font-size:13px; color:var(--amz-blue); background:none; border:none; cursor:pointer;"><i class="fa-solid fa-caret-left"></i> Change phone number</button>
            </div>

            {{-- STEP 3: OTP --}}
            <div id="s3" class="step">
                <h1 class="auth-title">Verification</h1>
                <div id="otp_info" style="font-size:13px; margin-bottom:15px;"></div>
                <label class="input-label">Enter verification code</label>
                <input type="text" id="otp_input" class="a-input" placeholder="Enter OTP" maxlength="4">
                <button id="btn_s3" class="a-btn">
                    Verify OTP <span class="spinner-border spinner-border-sm d-none ms-2"></span>
                </button>
                <div style="margin-top:15px; display:flex; justify-content:space-between;">
                    <button id="btn_resend" style="background:none; border:none; color:var(--amz-blue); font-size:13px; cursor:pointer;">Resend code</button>
                    <button onclick="goStep('s1')" style="background:none; border:none; color:var(--amz-blue); font-size:13px; cursor:pointer;">Change phone/email</button>
                </div>
            </div>

            {{-- STEP 4: Password --}}
            <div id="s4" class="step">
                <h1 class="auth-title">Sign in</h1>
                <div style="font-size:14px; margin-bottom:15px;">
                    <span id="user_display_name" style="font-weight:700;"></span> 
                    <a href="javascript:void(0)" onclick="goStep('s1')" style="color:var(--amz-blue); font-size:13px; margin-left:5px;">Change</a>
                </div>
                <div style="display:flex; justify-content:space-between; align-items:flex-end; margin-bottom:4px;">
                    <label class="input-label" style="margin-bottom:0;">Password</label>
                    <a href="{{ route('customer.forgot.password') }}" style="color:var(--amz-blue); font-size:13px; text-decoration:none;">Forgot your password?</a>
                </div>
                <input type="password" id="pass_input" class="a-input" placeholder="Enter your password">
                <button id="btn_s4" class="a-btn">Sign in</button>
                
                <div style="margin-top:15px;">
                    <button type="button" id="btn_otp_instead" style="background:none; border:none; color:var(--amz-blue); font-size:13px; cursor:pointer;"><i class="fa-solid fa-caret-right"></i> Get a verification code on your phone</button>
                </div>
            </div>

            {{-- STEP 5: New Password --}}
            <div id="s5" class="step">
                <h1 class="auth-title">Set password</h1>
                <p style="font-size:13px; margin-bottom:15px;" id="s5_sub">Create a password to sign in faster next time.</p>
                <label class="input-label">New password</label>
                <input type="password" id="newpass_input" class="a-input" placeholder="At least 6 characters">
                <label class="input-label">Confirm password</label>
                <input type="password" id="newpass_confirm" class="a-input" placeholder="Re-enter password">
                <button id="btn_s5" class="a-btn">Save Password &amp; Continue</button>
            </div>

        </div>

        </div>

    </div>

</section>
@endsection

@push('script')
<script>
$(function() {
    var phone = '';
    var email = '';
    var smsActive  = {{ $smsActive ? 'true' : 'false' }};
    var emailOtpOn = {{ $emailOtpOn ? 'true' : 'false' }};
    var otpOn      = {{ $otpOn ? 'true' : 'false' }};

    function goStep(id) {
        $('.step').removeClass('active');
        $('#' + id).addClass('active');
        if (id === 's1') $('#s2').removeData('force_otp');
    }

    function spin(btn, on) {
        btn.prop('disabled', on);
        var sp = btn.find('.spinner-border');
        on ? sp.removeClass('d-none') : sp.addClass('d-none');
    }

    $('#btn_s1').on('click', function() {
        var val = $('#phone_input').val().trim();
        if (val.length < 11) { toastr.error('Please enter a valid phone number'); return; }
        phone = val;
        var btn = $(this);
        spin(btn, true);

        $.post("{{ route('customer.check_user') }}", { _token: "{{ csrf_token() }}", phone: phone })
         .done(function(res) {
            spin(btn, false);
            if (res.status === 'PASSWORD_REQUIRED') {
                $('#user_display_name').text(res.name);
                goStep('s4');
            } else if (res.status === 'EMAIL_REQUIRED') {
                goStep('s2');
            } else if (res.status === 'OTP_REQUIRED') {
                var hint = res.email_hint || phone;
                $('#otp_info').html('To verify your account, we\'ve sent a code to <b>' + hint + '</b>');
                goStep('s3');
                toastr.success('Verification code sent');
            }
         })
         .fail(function() { spin(btn, false); toastr.error('Something went wrong'); });
    });

    $('#btn_s2').on('click', function() {
        var val = $('#email_input').val().trim();
        if (!val || !val.includes('@')) { toastr.error('Please enter a valid email'); return; }
        email = val;
        var btn = $(this);
        spin(btn, true);
        $('#email_status').hide();

        var payload = { _token: "{{ csrf_token() }}", phone: phone, email: email };
        if ($('#s2').data('force_otp')) payload.force_otp = 1;

        $.post("{{ route('customer.check_user') }}", payload)
         .done(function(res) {
            spin(btn, false);
            if (res.status === 'EMAIL_TAKEN') {
                $('#email_input').css('border-color', '#c0392b');
                $('#email_status').removeClass('d-none').css({'display':'block','color':'#c0392b','font-size':'12px','margin-top':'6px'})
                    .text(res.message || 'This email is already used by another account.');
                toastr.error(res.message || 'This email is already used by another account.');
            } else if (res.status === 'PASSWORD_REQUIRED') {
                $('#user_display_name').text(res.name);
                goStep('s4');
            } else if (res.status === 'OTP_REQUIRED') {
                var hint = res.email_hint || email;
                $('#otp_info').html('To verify your account, we\'ve sent a code to <b>' + hint + '</b>');
                goStep('s3');
                toastr.success('Verification code sent');
            }
         })
         .fail(function() { spin(btn, false); toastr.error('Something went wrong'); });
    });

    // Reset email input style on typing
    $('#email_input').on('input', function() {
        $(this).css('border-color', '');
        $('#email_status').hide();
    });

    $('#btn_s3').on('click', function() {
        var otp = $('#otp_input').val().trim();
        if (otp.length < 4) { toastr.error('Please enter the 4-digit code'); return; }
        var btn = $(this);
        spin(btn, true);
        var payload = { _token: "{{ csrf_token() }}", otp: otp };
        if (phone) payload.phone = phone;
        if (email) payload.email = email;
        $.post("{{ route('customer.auth_verify') }}", payload)
         .done(function(res) {
            spin(btn, false);
            if (res.success) {
                toastr.success('Verified successfully');
                if (res.needs_password) {
                    // New user or user without a real password — let them set one
                    goStep('s5');
                } else {
                    // Already has a password — go straight to account
                    window.location.href = "{{ route('customer.account') }}";
                }
            } else {
                toastr.error(res.message || 'Verification code does not match');
            }
         })
         .fail(function() { spin(btn, false); toastr.error('Something went wrong'); });
    });

    $('#btn_s4').on('click', function() {
        var pass = $('#pass_input').val();
        if (!pass) { toastr.error('Please enter your password'); return; }
        var btn = $(this);
        spin(btn, true);
        var payload = { _token: "{{ csrf_token() }}", password: pass };
        if (phone) payload.phone = phone;
        if (email) payload.email = email;
        $.post("{{ route('customer.auth_complete') }}", payload)
         .done(function(res) {
            if (res.success) {
                window.location.href = "{{ route('customer.account') }}";
            } else {
                spin(btn, false);
                toastr.error(res.message || 'Wrong password');
            }
         })
         .fail(function() { spin(btn, false); toastr.error('Something went wrong'); });
    });

    $('#btn_otp_instead').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).text('Sending code...');
        var payload = { _token: "{{ csrf_token() }}", force_otp: 1 };
        if (phone) payload.phone = phone;
        if (email) payload.email = email;
        $.post("{{ route('customer.check_user') }}", payload)
         .done(function(res) {
            btn.prop('disabled', false).html('<i class="fa-solid fa-caret-right"></i> Get a verification code on your phone');
            if (res.status === 'OTP_REQUIRED') {
                var hint = res.email_hint || (phone ? phone : email);
                $('#otp_info').html('To verify your account, we\'ve sent a code to <b>' + hint + '</b>');
                goStep('s3');
                toastr.success('Verification code sent');
            } else if (res.status === 'EMAIL_REQUIRED') {
                $('#s2').data('force_otp', 1);
                goStep('s2');
            } else {
                toastr.error('Could not send code');
            }
         })
         .fail(function() { btn.prop('disabled', false).html('<i class="fa-solid fa-caret-right"></i> Get a verification code on your phone'); toastr.error('Something went wrong'); });
    });

    $('#btn_s5').on('click', function() {
        var pass    = $('#newpass_input').val();
        var confirm = $('#newpass_confirm').val();
        if (!pass) { toastr.error('Please enter a password'); return; }
        if (pass.length < 6) { toastr.error('Password must be at least 6 characters'); return; }
        if (pass !== confirm) { toastr.error('Passwords do not match'); return; }
        var btn = $(this);
        spin(btn, true);
        var payload = { _token: "{{ csrf_token() }}", password: pass, is_new_password: 1 };
        if (phone) payload.phone = phone;
        if (email) payload.email = email;
        $.post("{{ route('customer.auth_complete') }}", payload)
         .done(function(res) {
            if (res.success) {
                window.location.href = "{{ route('customer.account') }}";
            } else {
                spin(btn, false);
                toastr.error(res.message || 'Failed to save password');
            }
         })
         .fail(function() { spin(btn, false); toastr.error('Something went wrong'); });
    });

    $('#btn_s5_skip').on('click', function() {
        window.location.href = "{{ route('customer.account') }}";
    });

    $('#phone_input, #email_input, #otp_input, #pass_input').on('keypress', function(e) { 
        if (e.which===13) {
            var step = $(this).closest('.step').attr('id');
            $('#btn_' + step).click();
        }
    });
});
</script>
@endpush
