@extends('layouts.subscriptions')

@push('style')
<style>
  .market-search-card {
    border: 0;
    border-radius: 14px;
    box-shadow: 0 10px 26px rgba(20, 20, 20, 0.06);
  }

  .market-search-input {
    border-radius: 12px;
    border: 1px solid #ececec;
    min-height: 44px;
  }

  .market-card {
    position: relative;
    display: block;
    border-radius: 14px;
    padding: 14px 16px;
    color: #111;
    text-decoration: none;
    background: #f4f3f3;
    min-height: 132px;
    transition: transform 0.15s ease, box-shadow 0.15s ease;
  }

  .market-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 26px rgba(0, 0, 0, 0.08);
    color: #111;
  }

  .market-card:nth-child(3n+1) {
    background: #f3eeee;
  }

  .market-card:nth-child(3n+2) {
    background: #edf2f4;
  }

  .market-card:nth-child(3n+3) {
    background: #f2efef;
  }

  .incentive-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #7b3be2;
    color: #fff;
    font-size: 11px;
    font-weight: 700;
    border-radius: 8px;
    padding: 2px 8px;
    line-height: 1.4;
  }

  .service-logo {
    width: 58px;
    height: 58px;
    border-radius: 18px;
    background: #0d0d10;
    color: #fff;
    font-weight: 700;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-transform: uppercase;
    overflow: hidden;
    position: relative;
    flex-shrink: 0;
  }

  .service-logo img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: absolute;
    inset: 0;
  }

  .service-logo-fallback {
    position: relative;
    z-index: 1;
    letter-spacing: 0.5px;
  }

  .profile-stack {
    display: flex;
    align-items: center;
    margin-left: auto;
  }

  .profile-dot,
  .profile-more {
    width: 26px;
    height: 26px;
    border-radius: 999px;
    border: 2px solid #fff;
    margin-left: -8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    font-weight: 700;
    color: #fff;
  }

  .profile-dot:nth-child(1) { background: #1161c2; }
  .profile-dot:nth-child(2) { background: #1f8f4b; }
  .profile-dot:nth-child(3) { background: #ec6d2b; }
  .profile-dot:nth-child(4) { background: #303f9f; }

  .profile-more {
    background: #ff9800;
  }

  .minimum-text {
    color: #9a9a9a;
    font-size: 13px;
    margin-bottom: 0;
  }

  .minimum-price {
    color: #ff8b00;
    font-size: 35px;
    line-height: 1;
    font-weight: 700;
    margin-top: 4px;
    text-align: right;
  }

  .category-head {
    margin-top: 18px;
    margin-bottom: 14px;
  }

  .category-title {
    font-size: 25px;
    font-weight: 700;
    margin: 0;
  }

  .category-view-all {
    font-size: 14px;
    font-weight: 600;
    color: #222;
    text-decoration: none;
  }

  .category-view-all:hover {
    color: #ff8b00;
  }

  .market-results {
    transition: opacity 0.2s ease;
  }

  .market-results.is-loading {
    opacity: 0.6;
    pointer-events: none;
  }
</style>
@endpush

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="card market-search-card mb-4">
    <div class="card-body">
      <form id="subscription-search-form" method="GET" action="{{ route('subscriptions.index') }}" class="row g-3 align-items-center">
        <div class="col-md-10">
          <input
            id="subscription-search-input"
            type="text"
            class="form-control market-search-input"
            name="q"
            value="{{ $search }}"
            placeholder="Search service, plan, or listing"
          >
          <input
            type="hidden"
            id="subscription-category-id"
            name="category_id"
            value="{{ $selectedCategoryId > 0 ? $selectedCategoryId : '' }}"
          >
        </div>
        <div class="col-md-2 d-grid">
          <button id="subscription-search-submit" class="btn btn-primary">Search</button>
        </div>
      </form>
    </div>
  </div>

  <div id="subscription-search-results" class="market-results">
    @include('subscriptions.partials.results', ['servicesByCategory' => $servicesByCategory])
  </div>
</div>
@endsection

@push('script')
<script>
$(document).ready(function () {
  const $form = $('#subscription-search-form');
  const $input = $('#subscription-search-input');
  const $categoryInput = $('#subscription-category-id');
  const $results = $('#subscription-search-results');

  let debounceTimer = null;
  let activeRequest = null;
  let lastQuery = ($input.val() || '').trim();

  function updateBrowserUrl(query) {
    const baseUrl = '{{ route('subscriptions.index') }}';
    const params = new URLSearchParams();
    const categoryId = ($categoryInput.val() || '').trim();

    if (query) {
      params.set('q', query);
    }
    if (categoryId) {
      params.set('category_id', categoryId);
    }

    const nextUrl = params.toString() ? (baseUrl + '?' + params.toString()) : baseUrl;
    window.history.replaceState({}, '', nextUrl);
  }

  function fetchResults(query) {
    if (activeRequest) {
      activeRequest.abort();
    }

    $results.addClass('is-loading');

    activeRequest = $.ajax({
      url: $form.attr('action'),
      method: 'GET',
      dataType: 'json',
      data: {
        q: query,
        category_id: ($categoryInput.val() || '').trim()
      },
      success: function (response) {
        if (response && response.html !== undefined) {
          $results.html(response.html);
          updateBrowserUrl(query);
        }
      },
      error: function (xhr, status) {
        if (status !== 'abort') {
          $results.removeClass('is-loading');
        }
      },
      complete: function () {
        $results.removeClass('is-loading');
        activeRequest = null;
      }
    });
  }

  function queueLiveSearch() {
    const query = ($input.val() || '').trim();
    if (query === lastQuery) {
      return;
    }

    lastQuery = query;
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(function () {
      fetchResults(query);
    }, 300);
  }

  $input.on('input', queueLiveSearch);

  $form.on('submit', function (event) {
    event.preventDefault();
    clearTimeout(debounceTimer);

    lastQuery = ($input.val() || '').trim();
    fetchResults(lastQuery);
  });
});
</script>
@endpush
