@extends('layout.user')

@section('content')
  @php
    $gs = \App\Models\GeneralSetting::first();
    $g1 = '#2563eb'; // primary blue
    $g2 = '#1d4ed8'; // deep blue
    $ink = $gs->text_color ?? '#0f172a';

    // ✅ popup এ আয় দেখাতে summary থেকে আনি (customer() method এটা পাঠাচ্ছে)
    $popupEarn = isset($summary['earn_total']) ? (float) $summary['earn_total'] : 0;
    $voucherBalance = (float) (auth()->user()->voucher_balance ?? 0);
    $deliveryPaymentType = (int) ($summary['delivery_payment_type'] ?? $product->delivery_payment_type ?? 0);
    $insideDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_DHAKA_CITY);
    $nearDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_SUB_DHAKA);
    $outsideDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_OUT_DHAKA);
    $selectedDeliveryZone = old('delivery_zone');
    $selectedDeliveryCharge = in_array($selectedDeliveryZone, [
      \App\Models\Product::DELIVERY_ZONE_DHAKA_CITY,
      \App\Models\Product::DELIVERY_ZONE_SUB_DHAKA,
      \App\Models\Product::DELIVERY_ZONE_OUT_DHAKA,
    ], true) ? $product->deliveryChargeForZone($selectedDeliveryZone) : null;
    $initialPayableTotal = $selectedDeliveryCharge !== null
      ? (float) $summary['grand_total'] + ($deliveryPaymentType === 1 ? 0 : $selectedDeliveryCharge)
      : ($deliveryPaymentType === 1 ? (float) $summary['grand_total'] : null);

    if ($deliveryPaymentType === 1) {
      if ($selectedDeliveryCharge === null) {
        $voucherHintText = 'ডেলিভারি জোন সিলেক্ট করলে ভাউচার থেকে কত কাটা হবে দেখাবে।';
        $voucherHintColors = ['border' => '#0ea5e955', 'background' => '#0ea5e91a', 'color' => '#0c4a6e'];
      } elseif ($voucherBalance < $selectedDeliveryCharge) {
        $voucherHintText = 'পর্যাপ্ত ভাউচার ব্যালেন্স নেই। ডেলিভারির জন্য ৳' . number_format($selectedDeliveryCharge, 2) . ' লাগবে।';
        $voucherHintColors = ['border' => '#f43f5e55', 'background' => '#f43f5e1a', 'color' => '#9f1239'];
      } else {
        $voucherHintText = 'নির্বাচিত জায়গার জন্য আপনার ভাউচার ব্যালেন্স যথেষ্ট আছে।';
        $voucherHintColors = ['border' => '#10b98155', 'background' => '#10b9811a', 'color' => '#065f46'];
      }
    } else {
      if ($selectedDeliveryCharge === null) {
        $voucherHintText = 'ডেলিভারি জোন সিলেক্ট করলে চার্জ যোগ হয়ে মোট দেখাবে।';
        $voucherHintColors = ['border' => '#0ea5e955', 'background' => '#0ea5e91a', 'color' => '#0c4a6e'];
      } else {
        $voucherHintText = 'এই চার্জ ভাউচার থেকে কাটা হবে না। ডেলিভারির সময় অতিরিক্ত ৳' . number_format($selectedDeliveryCharge, 2) . ' দিতে হবে।';
        $voucherHintColors = ['border' => '#f59e0b55', 'background' => '#f59e0b1a', 'color' => '#92400e'];
      }
    }
  @endphp

  <style>
    /* ===== ALL BOXES BLUE BORDER ===== */

    /* Main cards */
    .cardish,
    .soft-card,
    .wd-card {
      border: 1.5px solid #2563eb !important;
    }

    /* Summary small boxes */
    .soft-card .rounded-lg,
    .soft-card .p-2,
    .soft-card .p-3 {
      border: 1.5px solid rgba(37, 99, 235, .55) !important;
    }

    /* Input / Select / Textarea */
    .field,
    input,
    select,
    textarea {
      border: 1.5px solid rgba(37, 99, 235, .65) !important;
    }

    /* Focus state */
    .field:focus,
    input:focus,
    select:focus,
    textarea:focus {
      border-color: #1d4ed8 !important;
      box-shadow: 0 0 0 3px rgba(37, 99, 235, .25) !important;
    }

    /* Info notice boxes */
    .rounded-lg,
    .rounded-xl {
      border: 1.5px solid rgba(37, 99, 235, .45) !important;
    }

    /* Popup inner white sections */
    .wd-box,
    .wd-earn {
      border: 1.5px solid rgba(255, 255, 255, .35) !important;
    }

    /* ===== Global tidy ===== */
    #orderFlow a,
    #orderFlow a:hover,
    #orderFlow a:active,
    #orderFlow a:visited {
      text-decoration: none !important;
      -webkit-tap-highlight-color: transparent;
    }

    #orderFlow a:focus {
      outline: none;
    }

    .cardish {
      border-radius: 18px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, .06);
    }

    .soft-card {
      border-radius: 14px;
      box-shadow: 0 6px 18px rgba(0, 0, 0, .05);
    }

    /* ✅ UPDATED: সব ইনপুট/সিলেক্ট/টেক্সটএরিয়াতে নীল বর্ডার */
    .field {
      border: 1.5px solid rgba(37, 99, 235, .55) !important;
      border-radius: 12px;
      padding: .55rem .75rem;
      transition: .15s ease;
      background: #fff;
    }

    .field:focus {
      outline: none;
      border-color:
        {{ $g2 }}
        !important;
      box-shadow: 0 0 0 3px
        {{ $g2 }}
        33;
    }

    .btn-thick {
      border-radius: 12px;
      padding: .6rem .9rem;
      font-weight: 700;
      transition: .15s ease;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: .45rem;
      box-shadow: 0 4px 12px rgba(0, 0, 0, .06);
    }

    .btn-plain {
      background: #fff;
      border: 1px solid #e5e7eb;
      color: #334155;
    }

    .btn-thick:hover {
      filter: brightness(1.06);
      transform: translateY(-1px);
    }

    .btn-thick:active {
      transform: translateY(0);
    }

    /* ===== Modal Animations ===== */
    @keyframes neo-in {
      0% {
        opacity: 0;
        transform: translateY(14px) scale(.98)
      }

      100% {
        opacity: 1;
        transform: translateY(0) scale(1)
      }
    }

    @keyframes neo-out {
      0% {
        opacity: 1;
        transform: translateY(0) scale(1)
      }

      100% {
        opacity: 0;
        transform: translateY(14px) scale(.98)
      }
    }

    .animate-neo-in {
      animation: neo-in .22s ease-out
    }

    .animate-neo-out {
      animation: neo-out .22s ease-in forwards
    }

    /* ===== Centered modal ===== */
    .wd-backdrop {
      position: fixed;
      inset: 0;
      z-index: 999999;
      background: rgba(0, 0, 0, .55);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 18px 14px;
    }

    .wd-wrap {
      width: 100%;
      max-width: 390px;
    }

    .wd-card {
      background: #fff;
      border-radius: 18px;
      box-shadow: 0 22px 48px rgba(0, 0, 0, .18);
      overflow: visible;
      border: 1px solid rgba(0, 0, 0, .06);
    }

    /* ===== Tick icon ===== */
    .ok-badge {
      width: 52px;
      height: 52px;
      border-radius: 999px;
      background: linear-gradient(135deg,
          {{ $g1 }}
          ,
          {{ $g2 }}
        );
      display: grid;
      place-items: center;
      box-shadow: 0 14px 26px rgba(37, 99, 235, .24);
    }

    .ok-badge svg {
      width: 26px;
      height: 26px;
      color: #fff;
    }

    /* ===== Blue info boxes ===== */
    .wd-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      margin-top: 12px
    }

    .wd-box {
      border-radius: 14px;
      padding: 14px 10px;
      text-align: center;
      min-height: 86px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: linear-gradient(135deg,
          {{ $g1 }}
          ,
          {{ $g2 }}
        );
      color: #fff;
      border: 1px solid rgba(255, 255, 255, .18);
      box-shadow: 0 12px 22px rgba(37, 99, 235, .18);
    }

    .wd-lbl {
      font-size: 12px;
      font-weight: 900;
      color: rgba(255, 255, 255, .82);
      margin-bottom: 6px
    }

    .wd-val {
      font-size: 15px;
      font-weight: 1000;
      color: #fff;
      word-break: break-word
    }

    /* ✅ NEW: Earn box (full width) */
    .wd-earn {
      margin-top: 12px;
      border-radius: 14px;
      padding: 14px 12px;
      background: linear-gradient(135deg,
          {{ $g2 }}
          ,
          {{ $g1 }}
        );
      color: #fff;
      border: 1px solid rgba(255, 255, 255, .18);
      box-shadow: 0 12px 22px rgba(37, 99, 235, .18);
      text-align: center;
    }

    .wd-earn .lbl {
      font-size: 12px;
      font-weight: 900;
      color: rgba(255, 255, 255, .85)
    }

    .wd-earn .val {
      font-size: 22px;
      font-weight: 1000;
      line-height: 1.1;
      margin-top: 4px
    }

    /* ===== Dashboard button ===== */
    .btn-blue {
      width: 100%;
      border: none;
      background: linear-gradient(135deg,
          {{ $g1 }}
          ,
          {{ $g2 }}
        );
      color: #fff;
      font-weight: 1000;
      font-size: 18px;
      padding: 14px 12px;
      border-radius: 12px;
      box-shadow: 0 14px 26px rgba(37, 99, 235, .22);
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      text-decoration: none !important;
    }
  </style>

  <div id="orderFlow" class="mx-auto max-w-[1100px] px-3 sm:px-4 md:px-6 mt-2 pb-10">

    {{-- ===== Success Popup (order_success) ===== --}}
    @if(session('order_success'))
      @php $data = session('order_success'); @endphp

      <div id="successModal" class="wd-backdrop" role="dialog" aria-modal="true">
        <div class="wd-wrap">
          <div class="wd-card animate-neo-in relative">

            {{-- Header (Blue only) --}}
            <div class="relative h-36 sm:h-40 rounded-t-[18px]"
              style="background:linear-gradient(135deg,{{ $g1 }} 0%, {{ $g2 }} 100%);">

              {{-- Floating product --}}
              <div class="absolute left-1/2 -bottom-16 -translate-x-1/2">
                <div class="h-28 w-28 sm:h-32 sm:w-32 rounded-2xl bg-white overflow-hidden
                                                                                          shadow-xl ring-8 ring-white/90">
                  <img
                    src="{{ $data['banner_photo'] ?? ($product->banner_photo_url ?? 'https://dummyimage.com/600x600/e5e7eb/9ca3af&text=No+Image') }}"
                    alt="Product Banner" class="w-full h-full object-cover">
                </div>
              </div>

              {{-- Close icon --}}
              <button type="button" onclick="closeOrderModal()"
                class="grid place-items-center absolute top-3 right-3 size-9
                                                                                           rounded-full bg-white/90 text-slate-700 shadow hover:bg-white hover:shadow-md active:scale-95 transition"
                aria-label="Close">
                <i class="fa-solid fa-xmark text-lg"></i>
              </button>
            </div>

            {{-- Body --}}
            <div class="pt-20 px-4 sm:px-6 text-center pb-4">

              {{-- Tick --}}
              <div class="mx-auto mb-2 grid place-items-center">
                <div class="ok-badge">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                  </svg>
                </div>
              </div>

              <h2 class="text-[15px] sm:text-base font-semibold" style="color:{{ $ink }}">
                {{ $data['title'] ?? $product->title }}
              </h2>

              <p class="mt-1.5 text-[15px] sm:text-[17px] font-extrabold leading-snug" style="color:{{ $ink }}">
                অভিনন্দন!
              </p>
              <p class="-mt-0.5 text-[15px] sm:text-[17px] font-extrabold leading-snug" style="color:{{ $ink }}">
                <span style="color:{{ $g1 }}">অর্ডার সফলভাবে সম্পন্ন হয়েছে</span>
              </p>

              <p class="mt-2 text-[12px] sm:text-[13px] text-slate-600">
                আপনার ড্যাশবোর্ডে বিস্তারিত দেখা যাবে।
              </p>

              {{-- ✅ NEW: আপনার আয় --}}
              <div class="wd-earn">
                <div class="lbl">আমার প্রফিট</div>
                <div class="val">৳ {{ number_format($popupEarn, 2) }}</div>
              </div>

              {{-- Blue boxes --}}
              <div class="wd-grid">
                <div class="wd-box">
                  <div class="wd-lbl">প্রোডাক্ট</div>
                  <div class="wd-val">{{ \Illuminate\Support\Str::limit(($data['title'] ?? $product->title), 28) }}</div>
                </div>
                <div class="wd-box">
                  <div class="wd-lbl">অর্ডার আইডি</div>
                  <div class="wd-val">{{ $data['id'] }}</div>
                </div>
              </div>

              {{-- Dashboard button --}}
              <div class="mt-3">
                <a href="{{ route('reseller.dashboard') ?? url('/dashboard') }}" class="btn-blue">
                  <i class="fa-solid fa-gauge text-[12px]"></i> ড্যাশবোর্ডে যান
                </a>
              </div>
            </div>

          </div>
        </div>
      </div>

      <script>
        function closeOrderModal() {
          const root = document.getElementById('successModal');
          const card = root?.querySelector('.wd-card');
          card?.classList.add('animate-neo-out');
          setTimeout(() => root?.remove(), 260);
        }

        document.getElementById('successModal')?.addEventListener('click', function (e) {
          if (e.target === this) closeOrderModal();
        });

        document.addEventListener('keydown', function (e) {
          if (e.key === 'Escape') closeOrderModal();
        }, { once: true });
      </script>
    @endif

    {{-- ===== Header (clean) ===== --}}
    <div class="flex items-center justify-between gap-2 mb-2">
      <h1 class="text-lg font-extrabold" style="color:{{ $ink }}">গ্রাহকের তথ্য</h1>
      <a href="{{ route('order.create', $product->slug) }}" class="btn-thick btn-plain">
        <i class="fa-solid fa-arrow-left text-[12px]"></i> আগের ধাপে ফিরুন
      </a>
    </div>

    {{-- ===== Errors ===== --}}
    @if($errors->any())
      <div class="mb-2 rounded-lg border px-3 py-2 text-sm"
        style="border-color:#f43f5e33;background:#f43f5e22;color:#7f1d1d;">
        <ul class="list-disc pl-4 space-y-0.5">
          @foreach ($errors->all() as $e)<li>{{ $e }}</li>@endforeach
        </ul>
      </div>
    @endif

    {{-- ===== Main Card ===== --}}
    <div class="cardish border bg-white p-3 sm:p-4 grid gap-3" style="border-color:#e5e7eb">
      {{-- ===== Order Summary (unchanged) ===== --}}
      <div class="soft-card ring-1 p-3" style="background:linear-gradient(180deg,#f8fafc,#ffffff); ring-color:#e2e8f0;">
        <div class="flex items-center justify-between">
          <div class="text-[13px] font-medium line-clamp-2" style="color:{{ $ink }}">{{ $product->title }}</div>
        </div>

        <div class="mt-2 grid grid-cols-2 gap-2">
          <div class="rounded-lg p-2 text-[12px]" style="border:1px solid #38bdf855;background:#38bdf81a;color:#075985;">
            পরিমাণ: <span class="font-semibold">{{ $summary['qty'] }}</span>
          </div>
          <div class="rounded-lg p-2 text-[12px]" style="border:1px solid #10b98155;background:#10b9811a;color:#065f46;">
            বিক্রয় মূল্য/পিস: <span class="font-semibold">৳{{ number_format($summary['sale_price'], 2) }}</span>
          </div>
          <div class="rounded-lg p-2 text-[12px]" style="border:1px solid #a78bfa55;background:#a78bfa1a;color:#5b21b6;">
            Size: <span class="font-semibold">{{ ($summary['size'] ?? '') !== '' ? $summary['size'] : '-' }}</span>
          </div>
        </div>

        <div class="mt-2 grid grid-cols-1 xs:grid-cols-3 sm:grid-cols-3 gap-2">
          <div class="rounded-lg p-2" style="border:1px solid #e5e7eb;">
            <div class="text-[11px] text-slate-500">মোট পাইকারি</div>
            <div class="text-[14px] font-bold" style="color:{{ $ink }}">
              ৳{{ number_format($summary['wholesale_total'], 2) }}</div>
          </div>
          <div class="rounded-lg p-2" style="border:1px solid #10b98155;background:#10b9811a;">
            <div class="text-[11px]" style="color:#065f46">আপনার আয়</div>
            <div class="text-[14px] font-bold" style="color:#065f46">৳{{ number_format($summary['earn_total'], 2) }}</div>
          </div>
          <div class="rounded-lg p-2" style="border:1px solid {{ $g2 }}55;background:{{ $g2 }}1a;">
            <div class="text-[11px]" style="color:{{ $g2 }}">সর্বমোট</div>
            <div class="text-[14px] font-bold" style="color:{{ $g2 }}">৳{{ number_format($summary['grand_total'], 2) }}
            </div>
          </div>
        </div>

        <div class="mt-2 text-[12px]">
          <div class="rounded-lg p-2" style="border:1px solid #f59e0b55;background:#f59e0b1a;color:#92400e;">
            জোন অনুযায়ী চার্জ নির্ধারিত:
            <b>ঢাকা সিটি = ৳{{ number_format($insideDhakaCharge, 2) }}</b>,
            <b>সাব ঢাকা = ৳{{ number_format($nearDhakaCharge, 2) }}</b>,
            <b>আউট ঢাকা = ৳{{ number_format($outsideDhakaCharge, 2) }}</b>।
          </div>
        </div>
      </div>

      {{-- ===== Customer Form (fixed IDs + blue borders) ===== --}}
      <form action="{{ route('order.confirm', $product->id) }}" method="POST" class="grid gap-3">
        @csrf

        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div class="grid gap-1.5">
            <label class="text-sm font-semibold" style="color:{{ $ink }}">গ্রাহকের নাম <span
                style="color:#ef4444">*</span></label>
            <input type="text" name="customer_name" value="{{ old('customer_name') }}" class="field" required>
          </div>
          <div class="grid gap-1.5">
            <label class="text-sm font-semibold" style="color:{{ $ink }}">গ্রাহকের ফোন নাম্বার <span
                style="color:#ef4444">*</span></label>
            <input type="text" name="customer_phone" value="{{ old('customer_phone') }}" class="field" required>
          </div>
        </div>

        <div class="grid gap-1.5">
          <label class="text-sm font-semibold" style="color:{{ $ink }}">বিকল্প ফোন নাম্বার</label>
          <input type="text" name="alt_phone" value="{{ old('alt_phone') }}" class="field">
        </div>

        <div class="grid gap-3">
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div class="grid gap-1.5">
              <label class="text-sm font-semibold" style="color:{{ $ink }}">ডেলিভারি জোন <span
                  style="color:#ef4444">*</span></label>
              <select id="delivery_zone" name="delivery_zone" class="field" required>
                <option value="">জোন সিলেক্ট করুন</option>
                <option value="dhaka_city" @selected(old('delivery_zone') === 'dhaka_city')>ঢাকা সিটি</option>
                <option value="sub_dhaka" @selected(old('delivery_zone') === 'sub_dhaka')>সাব ঢাকা</option>
                <option value="out_dhaka" @selected(old('delivery_zone') === 'out_dhaka')>আউট ঢাকা</option>
              </select>
            </div>
          </div>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div class="grid gap-1.5">
              <label class="text-sm font-semibold" style="color:{{ $ink }}">জেলা <span
                  style="color:#ef4444">*</span></label>
              <select id="district_id" name="district_id" class="field" required disabled>
                <option value="">আগে জোন সিলেক্ট করুন</option>
              </select>
            </div>
          </div>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div class="grid gap-1.5">
              <label class="text-sm font-semibold" style="color:{{ $ink }}">থানা/উপজেলা <span
                  style="color:#ef4444">*</span></label>
              <select id="upazila_id" name="upazila_id" class="field" required disabled>
                <option value="">আগে জেলা সিলেক্ট করুন</option>
              </select>
            </div>
            <div></div>
          </div>
        </div>

        <div class="grid gap-1.5">
          <label class="text-sm font-semibold" style="color:{{ $ink }}">সম্পূর্ণ ঠিকানা <span
              style="color:#ef4444">*</span></label>
          <textarea name="address" rows="3" class="field" required>{{ old('address') }}</textarea>
        </div>

        <div class="rounded-lg p-2 text-[12px]" style="border:1px solid #0ea5e955;background:#0ea5e91a;color:#0c4a6e;">
          <!-- <div>ডেলিভারি চার্জ নীতি: <b>ঢাকা সিটি = ৳{{ number_format($insideDhakaCharge, 2) }}</b>, <b>সাব ঢাকা =
                      ৳{{ number_format($nearDhakaCharge, 2) }}</b>, <b>আউট ঢাকা =
                      ৳{{ number_format($outsideDhakaCharge, 2) }}</b>।
                  </div> -->

          <!-- @if($deliveryPaymentType === 1)
                    <div>ভাউচার ব্যালেন্স: <b>৳{{ number_format($voucherBalance, 2) }}</b></div>
                  @endif -->


          <div class="mt-1">ডেলিভারি চার্জ: <b
              id="deliveryChargeText">{{ $selectedDeliveryCharge !== null ? '৳' . number_format($selectedDeliveryCharge, 2) : 'জোন সিলেক্ট করুন' }}</b>
          </div>
          <div class="mt-1">ডেলিভারি ম্যান এলে মোট দিতে হবে: <b
              id="payableTotalText">{{ $initialPayableTotal !== null ? '৳' . number_format($initialPayableTotal, 2) : 'জোন সিলেক্ট করুন' }}</b>
          </div>
          <div id="voucherHint" class="mt-1 rounded-lg p-2 font-semibold"
            style="border:1px solid {{ $voucherHintColors['border'] }};background:{{ $voucherHintColors['background'] }};color:{{ $voucherHintColors['color'] }};">
            {{ $voucherHintText }}
          </div>
        </div>
        <div class="pt-1">
          <button class="btn-thick" style="background:linear-gradient(90deg,{{ $g1 }},{{ $g2 }});color:#fff;">
            কনফার্ম করুন <i class="fa-solid fa-check text-[12px]"></i>
          </button>
        </div>
      </form>
    </div>
  </div>
@endsection

@push('scripts')
  <script>
    /* global Map */
    (function () {
      const upazilaCache = new Map();
      const zoneSel = document.getElementById('delivery_zone');
      const disSel = document.getElementById('district_id');
      const upaSel = document.getElementById('upazila_id');
      if (!zoneSel || !disSel || !upaSel) return;

      const routes = {
        districtsAll: "{{ route('location.districts.all') }}",
        upazilas: (id) => "{{ url('/location/upazilas') }}/" + id,
      };

      const oldZone = "{{ old('delivery_zone') }}";
      const oldDistrictId = "{{ old('district_id') }}";
      const oldUpazilaId = "{{ old('upazila_id') }}";

      const deliveryChargeText = document.getElementById('deliveryChargeText');
      const payableTotalText = document.getElementById('payableTotalText');
      const voucherHint = document.getElementById('voucherHint');

      const insideDhakaCharge = Number("{{ $insideDhakaCharge }}");
      const nearDhakaCharge = Number("{{ $nearDhakaCharge }}");
      const outsideDhakaCharge = Number("{{ $outsideDhakaCharge }}");
      const voucherBalance = Number("{{ $voucherBalance }}");
      const baseGrandTotal = Number("{{ (float) $summary['grand_total'] }}");
      const deliveryPaymentType = Number("{{ $deliveryPaymentType }}");

      const zones = {
        dhakaCity: 'dhaka_city',
        subDhaka: 'sub_dhaka',
        outDhaka: 'out_dhaka',
      };

      let districtsCache = [];

      function isDhakaDistrictName(name) {
        const txt = (name || '').trim().toLowerCase();
        return txt.includes('dhaka') || /\u09A2\u09BE\u0995\u09BE/u.test(name || '');
      }

      function isGazipurDistrictName(name) {
        const txt = (name || '').trim().toLowerCase();
        return txt.includes('gazipur')
          || /\u0997\u09BE\u099C\u09C0\u09AA\u09C1\u09B0/u.test(name || '')
          || /\u0997\u09BE\u099C\u09BF\u09AA\u09C1\u09B0/u.test(name || '');
      }

      function isSavarThanaName(name) {
        const txt = (name || '').trim().toLowerCase();
        return txt.includes('savar') || /\u09B8\u09BE\u09AD\u09BE\u09B0/u.test(name || '');
      }

      function resolveDeliveryZone(districtName, upazilaName) {
        if (isGazipurDistrictName(districtName) || isSavarThanaName(upazilaName)) return zones.subDhaka;
        if (isDhakaDistrictName(districtName)) return zones.dhakaCity;
        return zones.outDhaka;
      }

      function isDistrictAllowedByZone(zone, districtName) {
        if (zone === zones.dhakaCity) {
          return isDhakaDistrictName(districtName);
        }

        if (zone === zones.subDhaka) {
          return isDhakaDistrictName(districtName) || isGazipurDistrictName(districtName);
        }

        if (zone === zones.outDhaka) {
          return !isDhakaDistrictName(districtName) && !isGazipurDistrictName(districtName);
        }

        return false;
      }

      function deliveryChargeByZone(zone) {
        if (zone === zones.dhakaCity) return insideDhakaCharge;
        if (zone === zones.subDhaka) return nearDhakaCharge;
        return outsideDhakaCharge;
      }

      function renderDeliveryCharge() {
        const zone = zoneSel.value;
        if (!zone) {
          if (deliveryChargeText) {
            deliveryChargeText.textContent = 'জোন সিলেক্ট করুন';
          }

          if (payableTotalText) {
            payableTotalText.textContent = deliveryPaymentType === 1
              ? `৳${baseGrandTotal.toFixed(2)}`
              : 'জোন সিলেক্ট করুন';
          }

          if (voucherHint) {
            voucherHint.textContent = deliveryPaymentType === 1
              ? 'ডেলিভারি চার্জ ভাউচার থেকে কাটা হবে ।'
              : 'ডেলিভারি জোন সিলেক্ট করলে চার্জ যোগ হয়ে মোট দেখাবে।';
            voucherHint.style.border = '1px solid #0ea5e955';
            voucherHint.style.background = '#0ea5e91a';
            voucherHint.style.color = '#0c4a6e';
          }
          return;
        }

        const charge = deliveryChargeByZone(zone);
        const payable = deliveryPaymentType === 1 ? baseGrandTotal : baseGrandTotal + charge;

        if (deliveryChargeText) {
          deliveryChargeText.textContent = `৳${charge.toFixed(2)}`;
        }

        if (payableTotalText) {
          payableTotalText.textContent = `৳${payable.toFixed(2)}`;
        }

        if (voucherHint) {
          if (deliveryPaymentType === 1) {
            if (voucherBalance < charge) {
              voucherHint.textContent = `পর্যাপ্ত ভাউচার ব্যালেন্স নেই। ডেলিভারির জন্য ৳${charge.toFixed(2)} লাগবে।`;
              voucherHint.style.border = '1px solid #f43f5e55';
              voucherHint.style.background = '#f43f5e1a';
              voucherHint.style.color = '#9f1239';
            } else {
              voucherHint.textContent = 'নির্বাচিত জায়গার জন্য আপনার ভাউচার ব্যালেন্স যথেষ্ট আছে।';
              voucherHint.style.border = '1px solid #10b98155';
              voucherHint.style.background = '#10b9811a';
              voucherHint.style.color = '#065f46';
            }
          } else {
            voucherHint.textContent = `এই চার্জ ভাউচার থেকে কাটা হবে না। ডেলিভারির সময় অতিরিক্ত ৳${charge.toFixed(2)} দিতে হবে।`;
            voucherHint.style.border = '1px solid #f59e0b55';
            voucherHint.style.background = '#f59e0b1a';
            voucherHint.style.color = '#92400e';
          }
        }
      }

      function enable(sel) { sel.disabled = false; }

      function disable(sel, placeholder) {
        sel.disabled = true;
        sel.innerHTML = `<option value="">${placeholder}</option>`;
      }

      function loadOptions(selectEl, list, placeholder, keep, keepIfExists = true) {
        const prev = keep ?? '';
        selectEl.innerHTML = '';

        const first = document.createElement('option');
        first.value = '';
        first.textContent = placeholder;
        selectEl.appendChild(first);

        list.forEach((row) => {
          const o = document.createElement('option');
          o.value = row.id;
          o.textContent = row.name;
          if (keepIfExists && String(prev) === String(row.id)) o.selected = true;
          selectEl.appendChild(o);
        });

        if (list.length > 0) {
          enable(selectEl);
          return;
        }

        disable(selectEl, placeholder);
      }

      async function safeJson(url) {
        const r = await fetch(url, { headers: { Accept: 'application/json' } });
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
      }

      async function districtUpazilas(districtId) {
        const key = String(districtId);
        if (upazilaCache.has(key)) {
          return upazilaCache.get(key);
        }

        const rows = await safeJson(routes.upazilas(districtId));
        upazilaCache.set(key, rows);
        return rows;
      }

      function filteredDistricts(zone) {
        return districtsCache.filter((d) => isDistrictAllowedByZone(zone, d.name));
      }

      async function loadDistrictsByZone(zone, keepDistrictId = '') {
        if (!zone) {
          disable(disSel, 'আগে জোন সিলেক্ট করুন');
          disable(upaSel, 'আগে জেলা সিলেক্ট করুন');
          return;
        }

        const rows = filteredDistricts(zone);
        loadOptions(disSel, rows, 'জেলা সিলেক্ট করুন', keepDistrictId, true);

        if (!disSel.value) {
          disable(upaSel, rows.length ? 'আগে জেলা সিলেক্ট করুন' : 'এই জোনে জেলা নেই');
          return;
        }

        await loadUpazilasByDistrict(zone, disSel.value, oldZone === zone ? oldUpazilaId : '');
      }

      async function loadUpazilasByDistrict(zone, districtId, keepUpazilaId = '') {
        if (!zone || !districtId) {
          disable(upaSel, 'আগে জেলা সিলেক্ট করুন');
          return;
        }

        disable(upaSel, 'লোড হচ্ছে...');

        const district = districtsCache.find((d) => String(d.id) === String(districtId));
        const districtName = district?.name || '';

        try {
          const rows = await districtUpazilas(districtId);
          const filtered = rows.filter((u) => resolveDeliveryZone(districtName, u.name) === zone);

          if (!filtered.length) {
            disable(upaSel, 'এই জোনে থানা নেই');
            return;
          }

          loadOptions(upaSel, filtered, 'থানা/উপজেলা সিলেক্ট করুন', keepUpazilaId, true);
        } catch (e) {
          console.error(e);
          disable(upaSel, 'লোড ব্যর্থ');
        }
      }

      (async () => {
        try {
          districtsCache = await safeJson(routes.districtsAll);
          zoneSel.value = oldZone || '';
          await loadDistrictsByZone(zoneSel.value, oldDistrictId);
          renderDeliveryCharge();
        } catch (e) {
          console.error('Location preload failed:', e);
          disable(disSel, 'ডাটা লোড হয়নি');
          disable(upaSel, 'ডাটা লোড হয়নি');
        }
      })();

      zoneSel.addEventListener('change', async () => {
        await loadDistrictsByZone(zoneSel.value);
        renderDeliveryCharge();
      });

      disSel.addEventListener('change', async (e) => {
        const districtId = e.target.value;
        if (!districtId) {
          disable(upaSel, 'আগে জেলা সিলেক্ট করুন');
          renderDeliveryCharge();
          return;
        }

        await loadUpazilasByDistrict(zoneSel.value, districtId);
        renderDeliveryCharge();
      });

      upaSel.addEventListener('change', renderDeliveryCharge);

      renderDeliveryCharge();
    })();

    function closeOrderModal() {
      const root = document.getElementById('successModal');
      const card = root?.querySelector('.wd-card');
      card?.classList.add('animate-neo-out');
      setTimeout(() => root?.remove(), 260);
    }

    document.getElementById('successModal')?.addEventListener('click', function (e) {
      if (e.target === this) closeOrderModal();
    });

    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') closeOrderModal();
    }, { once: true });
  </script>
@endpush