<style>
.olx-header { background: #002f34; border-bottom: 1px solid rgba(255,255,255,.08); }
.olx-brand { color: #fff !important; font-weight: 700; letter-spacing: .3px; }
.olx-header .nav-link { color: rgba(255,255,255,.9) !important; }
.header-wide { max-width: 100%; }
.location-pill { background: #fff; border: 1px solid #e5e7eb; border-radius: 999px; padding: 6px 12px; height: 44px; position: relative; flex: 0 0 auto; width: auto; }
.location-pill-input { border: 0; outline: none; width: 140px; background: transparent; }
.search-pill { background: #fff; border: 1px solid #e5e7eb; border-radius: 999px; padding: 6px 12px; height: 44px; position: relative; }
.search-pill-input { border: 0; outline: none; width: 100%; background: transparent; }
.search-pill-btn { height: 44px; width: 44px; border-radius: 999px; border: 0; background: #0b74ff; color: #fff; }
.search-dyn-placeholder { position: absolute; left: 12px; right: 12px; top: 50%; transform: translateY(-50%); color: #6c757d; pointer-events: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; opacity: .7; transition: transform .25s ease, opacity .25s ease; }
.ui-autocomplete { z-index: 2000; max-height: 280px; overflow-y: auto; overflow-x: hidden; border-radius: 10px; border: 1px solid #e9ecef; box-shadow: 0 10px 30px rgba(0,0,0,.12); background: #fff; list-style: none; margin: 0; padding: 6px 0; }
.ui-autocomplete .ui-menu-item { list-style: none; }
.ui-menu-item-wrapper { padding: 10px 12px; font-size: 14px; }
.ui-state-active, .ui-widget-content .ui-state-active { background: rgba(0,47,52,.08); border: 0; color: #002f34; margin: 0; }
.city-suggest-dropdown { position: absolute; top: 48px; left: 0; width: 100%; max-width: 90vw; background: #fff; border: 1px solid #e9ecef; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,.12); z-index: 2001; overflow: hidden; }
.city-suggest-item { display: flex; align-items: center; padding: 10px 12px; cursor: pointer; }
.city-suggest-item:hover { background: rgba(0,47,52,.06); }
.city-suggest-item .icon { width: 22px; height: 22px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; color: #0b74ff; }
.city-suggest-item .text { color: #002f34; }
.city-suggest-sub { font-size: 12px; color: #6c757d; }
.city-suggest-header { padding: 8px 12px; font-size: 12px; color: #6c757d; border-top: 1px solid #e9ecef; }
.spinwheel-icon { width: 18px; height: 18px; object-fit: cover; border-radius: 50%; vertical-align: -3px; }
@media (min-width: 768px) {
  .rm-logo-img {
    background: #fff;
    padding: 4px 6px;
    border-radius: 10px;
  }
}
</style>
<nav class="main-header navbar navbar-expand olx-header" style="width:100%;">
  <div class="header-wide d-flex align-items-center w-100 px-3">
    <a href="<?php echo url('/') ?>" class="navbar-brand olx-brand mr-3">
      <?php if (setting('company_logo_type')): ?>
        <img class="rm-logo-img" src="<?php echo urlUpload('company/logo.' . setting('company_logo_type'), true) ?>" alt="<?php echo esc(setting('company_name')) ?>" style="height:42px;vertical-align:middle;">
      <?php endif ?>
      <span style="margin-left:8px;"><?php echo setting('company_name') ?></span>
    </a>
    <form method="get" action="<?php echo url('/') ?>" class="d-none d-md-flex flex-grow-1 align-items-center header-search-form">
      <input type="hidden" id="city_id" name="city_id" value="<?php echo (int) ($cityId ?? 0) ?>">
      <?php if (!empty($page) && (int) $page > 1): ?>
        <input type="hidden" name="page" value="<?php echo (int) $page ?>">
      <?php endif ?>
      <div class="location-pill d-flex align-items-center mr-2">
        <i class="fas fa-map-marker-alt mr-2"></i>
        <input type="text" id="city_search" name="city" class="location-pill-input" placeholder="India" value="<?php echo esc($selectedCityLabel ?? '') ?>">
        <i class="fas fa-chevron-right ml-2"></i>
        <div class="city-suggest-dropdown d-none" id="citySuggest">
          <div class="city-suggest-item" id="useCurrentLocation">
            <span class="icon"><i class="fas fa-location-arrow"></i></span>
            <div>
              <div class="text">Use current location</div>
              <div class="city-suggest-sub d-none" id="locFetching">Fetching Location</div>
            </div>
          </div>
          <div class="city-suggest-header">POPULAR LOCATIONS</div>
          <?php foreach (($popularCities ?? []) as $pc): ?>
            <div class="city-suggest-item city-suggest-pop" data-id="<?php echo (int)$pc->id ?>" data-label="<?php echo esc($pc->label) ?>">
              <span class="icon" style="color:#6c757d;"><i class="fas fa-map-marker-alt"></i></span>
              <div class="text"><?php echo esc($pc->label) ?></div>
            </div>
          <?php endforeach ?>
        </div>
      </div>
      <div class="search-pill d-flex flex-grow-1 align-items-center">
        <input type="text" class="search-pill-input" name="q" placeholder="" value="<?php echo esc($qText ?? '') ?>">
        <span class="search-dyn-placeholder"></span>
      </div>
      <button class="search-pill-btn ml-2" type="submit"><i class="fas fa-search"></i></button>
    </form>
    <ul class="navbar-nav ml-3 d-none d-md-flex">
      <li class="nav-item mr-3">
        <a href="<?php echo url('/') ?>" class="nav-link"><i class="fas fa-heart mr-1"></i>Wishlist</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link js-spin-wheel" aria-label="Spin Wheel" title="Spin Wheel" id="spinWheelMenu">
          <video class="spinwheel-icon" src="<?php echo url('assets/spinwheel.mp4') ?>" autoplay muted loop playsinline></video>
          <span class="ml-1"><?php echo (function_exists('is_logged') && is_logged()) ? (int) logged('total_reward_point') : 0; ?></span>
        </a>
      </li>
      <?php if (function_exists('is_logged') && is_logged()): ?>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarProfile" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="fas fa-user mr-1"></i>Profile
          </a>
          <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarProfile">
            <h6 class="dropdown-header">My Profile</h6>
            <a class="dropdown-item" href="<?php echo url('user/profile') ?>">My Profile</a>
            <a class="dropdown-item" href="<?php echo url('user/orders') ?>">My Paid Bills</a>
            <a class="dropdown-item" href="<?php echo url('user/wallet') ?>">My Reward Points</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="<?php echo url('auth/logout') . '?redirect=' . urlencode(url('/')) ?>">Logout</a>
          </div>
        </li>
      <?php else: ?>
        <li class="nav-item">
          <a href="<?php echo url('auth/otp') ?>" class="nav-link"><i class="fas fa-user mr-1"></i>Login</a>
        </li>
      <?php endif ?>
    </ul>
  </div>
</nav>
<div class="modal fade" id="spinWheelModal" tabindex="-1" role="dialog" aria-labelledby="spinWheelModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header py-2">
        <h6 class="modal-title" id="spinWheelModalLabel">Spin Wheel</h6>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body p-0" id="spinWheelContent">
        <div class="text-center p-4">Loading...</div>
      </div>
    </div>
  </div>
 </div>
<script>
  $(document).ready(function() {
    var appBasePath = '<?php echo rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') ?>';
    if (appBasePath === '/') appBasePath = '';
    function appUrl(path) {
      path = String(path || '').replace(/^\/+/, '');
      return appBasePath ? (appBasePath + '/' + path) : ('/' + path);
    }
    window.appUrl = appUrl;
    var cities = <?php echo json_encode(array_values(array_map(static function($c) { return ['id' => (int) ($c->id ?? 0), 'label' => (string) ($c->label ?? ''), 'city' => (string) ($c->city ?? ''), 'state' => (string) ($c->state ?? '')]; }, ($cities ?? []))), JSON_UNESCAPED_UNICODE); ?>;
    var categories = <?php echo json_encode(array_values(($categories ?? [])), JSON_UNESCAPED_UNICODE); ?>;
    var isLogged = <?php echo (function_exists('is_logged') && is_logged()) ? 'true' : 'false'; ?>;
    var csrfHeader = '<?php echo esc(config('Security')->headerName) ?>';
    var csrfToken = '<?php echo esc(csrf_hash()) ?>';
    function savePreferredCity(id, label) {
      if (!isLogged) return;
      try {
        fetch('<?php echo url('user/preferred-city') ?>', { method: 'POST', headers: (function(){ var h = { 'Content-Type': 'application/json' }; h[csrfHeader] = csrfToken; return h; })(), body: JSON.stringify({ city_id: parseInt(id || 0, 10) || 0 }) }).catch(function(){});
      } catch(e) {}
    }
    function wireCitySearch(inputSelector, hiddenSelector) {
      var $input = $(inputSelector);
      var $hidden = $(hiddenSelector);
      if (!$input.length) return;
      $input.on('input', function() { $hidden.val(''); });
      $input.autocomplete({
        minLength: 1,
        delay: 80,
        appendTo: 'body',
        position: { my: 'left top', at: 'left bottom', of: $input },
        source: function(request, response) {
          var term = (request.term || '').toLowerCase();
          var out = [];
          for (var i = 0; i < cities.length; i++) {
            var it = cities[i];
            var city = (it.city || '').toLowerCase();
            var state = (it.state || '').toLowerCase();
            var combined = (it.city || '') + (it.state ? (', ' + it.state) : '');
            if (!it.city) continue;
            if (city.indexOf(term) !== -1 || state.indexOf(term) !== -1) {
              out.push({ label: combined, value: combined, id: it.id, city: it.city, state: it.state, term: term });
              if (out.length >= 12) break;
            }
          }
          response(out);
        },
        select: function(event, ui) { $hidden.val(ui.item.id); $input.val(ui.item.label); savePreferredCity(ui.item.id, ui.item.label); return false; }
      }).autocomplete('instance')._renderItem = function(ul, item) {
        var city = item.city || '';
        var state = item.state || '';
        var term = item.term || '';
        var cityDisp = city;
        if (term) {
          var idx = city.toLowerCase().indexOf(term);
          if (idx !== -1) { cityDisp = city.substring(0, idx) + '<strong>' + city.substring(idx, idx + term.length) + '</strong>' + city.substring(idx + term.length); }
        }
        var html = '<div class="city-suggest-item"><span class="icon" style="color:#6c757d;"><i class="fas fa-map-marker-alt"></i></span><div class="text">' + cityDisp + (state ? (', ' + state) : '') + '</div></div>';
        return $('<li>').append('<div class="ui-menu-item-wrapper">' + html + '</div>').appendTo(ul);
      };
      function positionAuto() {
        var $widget = $input.autocomplete('widget');
        var $pill = $input.closest('.location-pill');
        if ($pill.length) {
          $widget.css({ width: $pill.outerWidth(), 'z-index': 2002 });
          try {
            $widget.position({ my: 'left top', at: 'left bottom+6', of: $pill, collision: 'fit' });
          } catch(e) {}
          return;
        }
        $widget.css({ width: $input.outerWidth(), 'z-index': 2002 });
        try {
          $widget.position({ my: 'left top', at: 'left bottom', of: $input, collision: 'fit' });
        } catch(e) {}
      }
      $input.on('autocompleteopen', positionAuto);
      $(window).on('resize scroll', positionAuto);
    }
    wireCitySearch('#city_search', '#city_id');
    wireCitySearch('#city_search_mobile', '#city_id_mobile');
    $(document).on('click', '.js-spin-wheel', function(e){
      e.preventDefault();
      if (!isLogged) {
        window.location.href = appUrl('auth/otp');
        return;
      }
      var $body = $('#spinWheelContent');
      $body.html('<div class="text-center p-4">Loading...</div>');
      $('#spinWheelModal').modal('show');
      fetch(appUrl('spin/list'), { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(function(r){
          if (r.status === 401) {
            window.location.href = appUrl('auth/otp');
            return '';
          }
          return r.text();
        })
        .then(function(html){
          if (!html) return;
          $body.html(html);
        })
        .catch(function(){ $body.html('<div class="alert alert-danger m-0">Failed to load spin wheels.</div>'); });
    });

    $(document).off('click.spin', '#spinWheelContent .spin-open-wheel').on('click.spin', '#spinWheelContent .spin-open-wheel', function(){
      var $btn = $(this);
      var id = $btn.data('id');
      var $body = $('#spinWheelContent');
      if (!id) return;
      if ($btn.data('loading')) return;
      $btn.data('loading', 1).prop('disabled', true);
      $body.html('<div class="text-center p-4">Loading...</div>');
      fetch(appUrl('spin/view/' + id), { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(function(r){
          if (r.status === 401) {
            window.location.href = appUrl('auth/otp');
            return '';
          }
          return r.text();
        })
        .then(function(html){
          if (!html) return;
          $body.html(html);
          try { $('#spinWheelModal .modal-body').scrollTop(0); } catch(e) {}
        })
        .catch(function(){
          $body.html('<div class="alert alert-danger m-0">Failed to load wheel.</div>');
        })
        .then(function(){
          $btn.data('loading', 0).prop('disabled', false);
        });
    });
    (function rotateSearchPlaceholder() {
      var $input = $('.search-pill-input');
      var $ph = $('.search-dyn-placeholder');
      if (!$ph.length) return;
      var idx = 0;
      function show(text) {
        $ph.css({ transform: 'translateY(20%)', opacity: 0 });
        setTimeout(function() { $ph.text('Search \"' + text + '\"'); $ph.css({ transform: 'translateY(-120%)', opacity: 0 }); setTimeout(function() { $ph.css({ transform: 'translateY(-50%)', opacity: .7 }); }, 20); }, 200);
      }
      function tick() {
        if (!categories || !categories.length) return;
        if ($input.is(':focus') || ($input.val() || '').length) return;
        idx = (idx + 1) % categories.length;
        show(categories[idx]);
      }
      if (categories && categories.length) { $ph.text('Search \"' + categories[0] + '\"'); } else { $ph.text('Search \"Pharmacy\"'); }
      function togglePh() {
        var hasVal = ($input.val() || '').length > 0;
        if ($input.is(':focus') || hasVal) { $ph.hide(); } else { $ph.show(); }
      }
      $input.on('focus blur input', togglePh);
      togglePh();
      setInterval(tick, 2000);
    })();
    (function citySuggest() {
      var $pill = $('.location-pill');
      var $input = $('#city_search');
      var $hidden = $('#city_id');
      var $dropdown = $('#citySuggest');
      var $locFetch = $('#locFetching');
      var citiesSmall = <?php echo json_encode(array_values(array_map(static function($c) { return ['id' => (int) ($c->id ?? 0), 'label' => (string) ($c->label ?? '')]; }, ($cities ?? []))), JSON_UNESCAPED_UNICODE); ?>;
      if (!$pill.length || !$dropdown.length) return;
      function showDropdown() { if (($input.val() || '').length) return; $dropdown.removeClass('d-none'); }
      function hideDropdown() { $dropdown.addClass('d-none'); }
      $pill.on('click', function() { showDropdown(); });
      $input.on('focus', function() { showDropdown(); });
      $input.on('input', function() { hideDropdown(); });
      $(document).on('click', function(e) { if (!$(e.target).closest('.location-pill').length) hideDropdown(); });
      $('.city-suggest-pop').on('click', function() { var id = $(this).data('id'); var label = $(this).data('label'); $hidden.val(id); $input.val(label); savePreferredCity(id, label); hideDropdown(); });
      $('#useCurrentLocation').on('click', function() {
        $locFetch.removeClass('d-none');
        if (!navigator.geolocation) { $locFetch.text('Geolocation not supported'); return; }
        navigator.geolocation.getCurrentPosition(function(pos) {
          var lat = pos.coords.latitude, lon = pos.coords.longitude;
          fetch('https://nominatim.openstreetmap.org/reverse?format=json&lat=' + lat + '&lon=' + lon + '&zoom=10')
            .then(function(r){ return r.json(); })
            .then(function(data){
              var addr = data && data.address ? data.address : {};
              var guess = (addr.city || addr.town || addr.village || addr.suburb || '') + '';
              if (!guess) { $locFetch.text('Location not found'); return; }
              var guessLower = guess.toLowerCase();
              var match = null;
              for (var i=0;i<citiesSmall.length;i++){ var lab = (citiesSmall[i].label || '').toLowerCase(); if (lab.indexOf(guessLower) !== -1) { match = citiesSmall[i]; break; } }
              if (match) { $hidden.val(match.id); $input.val(match.label); savePreferredCity(match.id, match.label); } else { $hidden.val(''); $input.val(guess); savePreferredCity(0, guess); }
              hideDropdown();
            })
            .catch(function(){ $locFetch.text('Location fetch failed'); });
        }, function(){ $locFetch.text('Permission denied'); }, { enableHighAccuracy: false, timeout: 8000, maximumAge: 600000 });
      });
    })();
  });
</script>
