// Search results page — §5
// Live mode: hits /api/v1/public/search?q= with pagination + brand facets.
// Mock mode: falls back to client-side PRODUCTS filter (unchanged behaviour).

const SEARCH_PAGE_SIZE = 24;

function SearchPage({ route, onCompareToggle, compareSet }) {
  const [filterBrand, setFilterBrand] = React.useState(new Set());
  const [filterStock, setFilterStock] = React.useState(false);
  const [sort, setSort] = React.useState('relevance');

  // live-search state
  const [liveResults, setLiveResults] = React.useState(null); // null = not yet fetched
  const [liveLoading, setLiveLoading] = React.useState(false);
  const [liveError, setLiveError] = React.useState(null);
  const [livePage, setLivePage] = React.useState(0);

  const api = window.kolaymarinApi;
  const isLive = api?.isLive;
  const q = (route.q || '').trim();

  // Reset facets + page whenever the query changes
  React.useEffect(() => {
    setFilterBrand(new Set());
    setFilterStock(false);
    setSort('relevance');
    setLivePage(0);
    setLiveResults(null);
    setLiveError(null);
  }, [q]);

  // Live fetch
  React.useEffect(() => {
    if (!isLive) return;
    if (q.length < 2) {
      setLiveResults({ items: [], total: 0, hasMore: false });
      return;
    }
    setLiveLoading(true);
    setLiveError(null);
    api
      .search(q, SEARCH_PAGE_SIZE, livePage * SEARCH_PAGE_SIZE)
      .then((data) => {
        setLiveResults((prev) => {
          if (livePage === 0 || !prev) return data;
          // append for "load more"
          return { ...data, items: [...prev.items, ...data.items] };
        });
      })
      .catch((err) => {
        if (err.status === 400) {
          setLiveResults({ items: [], total: 0, hasMore: false });
        } else {
          setLiveError('Arama şu an kullanılamıyor. Lütfen tekrar deneyin.');
        }
      })
      .finally(() => setLiveLoading(false));
  }, [q, livePage, isLive]);

  // ---- data source: live vs mock ----
  let matches;
  let total;
  let hasMore = false;

  if (isLive) {
    matches = liveResults?.items || [];
    total = liveResults?.total ?? 0;
    hasMore = liveResults?.hasMore ?? false;
  } else {
    // mock path — unchanged client-side filter
    const qLow = q.toLowerCase();
    matches = !q
      ? PRODUCTS
      : PRODUCTS.filter(
          (p) =>
            p.h1?.toLowerCase().includes(qLow) ||
            p.brand?.toLowerCase().includes(qLow) ||
            p.category?.toLowerCase().includes(qLow) ||
            p.model?.toLowerCase().includes(qLow) ||
            p.sku?.toLowerCase().includes(qLow),
        );
    total = matches.length;
  }

  // ---- brand facet (built from current result set) ----
  const brandFacet = {};
  matches.forEach((p) => {
    if (p.brand) brandFacet[p.brand] = (brandFacet[p.brand] || 0) + 1;
  });
  const brandList = Object.entries(brandFacet).sort((a, b) => b[1] - a[1]);

  // ---- client-side filters (applied after live fetch) ----
  let displayed = matches;
  if (filterBrand.size) displayed = displayed.filter((p) => filterBrand.has(p.brand));
  if (filterStock)
    displayed = displayed.filter((p) =>
      (p.offers || []).some(
        (o) => o.stockStatus === 'IN_STOCK' || o.stockStatus === 'LOW_STOCK',
      ),
    );

  // ---- client-side sort (relevance = backend order, others: client) ----
  displayed = [...displayed];
  if (sort === 'price-asc')
    displayed.sort((a, b) => (a.lowestPrice ?? Infinity) - (b.lowestPrice ?? Infinity));
  if (sort === 'merchants')
    displayed.sort((a, b) => (b.merchantCount ?? 0) - (a.merchantCount ?? 0));

  const showLoading = isLive ? liveLoading && !liveResults : false;

  return (
    <main id="main" data-screen-label="Search">
      <div className="container">
        <div className="breadcrumbs">
          <a href="#/">Anasayfa</a>
          <span className="breadcrumbs__sep">/</span>
          <span className="breadcrumbs__current">Arama: "{route.q}"</span>
        </div>

        <div className="search-layout">
          <aside>
            <div style={{ position: 'sticky', top: 76 }}>
              <h3
                style={{
                  fontSize: 12,
                  letterSpacing: '0.06em',
                  textTransform: 'uppercase',
                  color: 'var(--km-ink-500)',
                  marginBottom: 16,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <Icon name="filter" size={14} stroke={2} /> Filtreler
              </h3>

              <div className="facet">
                <div className="facet__head">Stok</div>
                <label className="facet__opt">
                  <input
                    type="checkbox"
                    checked={filterStock}
                    onChange={(e) => setFilterStock(e.target.checked)}
                  />
                  Sadece stokta olanlar
                </label>
              </div>

              {brandList.length > 0 && (
                <div className="facet">
                  <div className="facet__head">Marka</div>
                  {brandList.map(([brand, count]) => (
                    <label className="facet__opt" key={brand}>
                      <input
                        type="checkbox"
                        checked={filterBrand.has(brand)}
                        onChange={(e) => {
                          const next = new Set(filterBrand);
                          if (e.target.checked) next.add(brand);
                          else next.delete(brand);
                          setFilterBrand(next);
                        }}
                      />
                      {brand}
                      <small className="tabular">{count}</small>
                    </label>
                  ))}
                </div>
              )}

              <div className="facet">
                <div className="facet__head">Fiyat aralığı</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input
                    type="number"
                    placeholder="Min ₺"
                    className="search-bar"
                    style={{ height: 36, padding: '0 10px', fontSize: 13 }}
                  />
                  <input
                    type="number"
                    placeholder="Maks ₺"
                    className="search-bar"
                    style={{ height: 36, padding: '0 10px', fontSize: 13 }}
                  />
                </div>
              </div>
            </div>
          </aside>

          <div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                flexWrap: 'wrap',
                gap: 12,
                marginBottom: 16,
              }}
            >
              <div>
                <h1 style={{ fontSize: 22, fontWeight: 600 }}>"{route.q}" için sonuçlar</h1>
                <p style={{ fontSize: 13, color: 'var(--km-ink-500)', marginTop: 4 }}>
                  {showLoading
                    ? 'Aranıyor...'
                    : liveError
                    ? liveError
                    : `${total} ürün bulundu`}
                </p>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, color: 'var(--km-ink-500)' }}>Sırala:</span>
                <select
                  value={sort}
                  onChange={(e) => setSort(e.target.value)}
                  style={{
                    height: 36,
                    padding: '0 12px',
                    borderRadius: 8,
                    border: '1px solid var(--km-line)',
                    background: 'white',
                    fontSize: 13,
                  }}
                >
                  <option value="relevance">İlgili (varsayılan)</option>
                  <option value="price-asc">Fiyat (artan)</option>
                  <option value="merchants">Satıcı sayısı</option>
                </select>
              </div>
            </div>

            <div
              style={{
                background: 'white',
                border: '1px solid var(--km-line)',
                borderRadius: 12,
                overflow: 'hidden',
              }}
            >
              {showLoading ? (
                <>
                  {[0, 1, 2, 3].map((i) => (
                    <div key={i} className="search-result">
                      <div className="skel" style={{ width: 96, aspectRatio: '1', borderRadius: 8 }} />
                      <div style={{ flex: 1 }}>
                        <div className="skel" style={{ height: 12, width: 80, marginBottom: 8 }} />
                        <div className="skel" style={{ height: 18, width: '70%', marginBottom: 8 }} />
                        <div className="skel" style={{ height: 12, width: 160 }} />
                      </div>
                      <div className="skel" style={{ height: 28, width: 100 }} />
                    </div>
                  ))}
                </>
              ) : liveError ? (
                <div style={{ padding: 64, textAlign: 'center', color: 'var(--km-ink-500)' }}>
                  <Icon name="alert-circle" size={32} stroke={1.5} />
                  <p style={{ marginTop: 12, fontWeight: 600, color: 'var(--km-ink-700)' }}>{liveError}</p>
                </div>
              ) : displayed.length === 0 ? (
                <div style={{ padding: 64, textAlign: 'center', color: 'var(--km-ink-500)' }}>
                  <Icon name="search" size={32} stroke={1.5} />
                  <p style={{ marginTop: 12, fontWeight: 600, color: 'var(--km-ink-700)' }}>
                    "{route.q}" için sonuç bulamadık
                  </p>
                  <p style={{ fontSize: 13 }}>
                    Daha genel bir terim deneyin veya kategorilerden devam edin.
                  </p>
                </div>
              ) : (
                displayed.map((p) => {
                  const low = p.lowestPrice ?? productLowest(p);
                  const inStock = p.inStockCount ?? p.offers.filter((o) => o.stockStatus === 'IN_STOCK').length;
                  const offerCount = p.totalOfferCount ?? p.offers.length;
                  const lastSeen =
                    p.offers?.length > 0
                      ? p.offers.reduce((a, b) =>
                          new Date(a.lastSeenAt) > new Date(b.lastSeenAt) ? a : b,
                        )
                      : null;
                  return (
                    <a href={urlForProduct(p)} className="search-result" key={p.shortSlug}>
                      <div
                        className="search-result__img"
                        style={
                          p.imageUrl
                            ? {
                                backgroundImage: `url(${p.imageUrl})`,
                                backgroundSize: 'cover',
                                backgroundPosition: 'center',
                              }
                            : undefined
                        }
                      />
                      <div>
                        <div className="search-result__brand">{p.brand}</div>
                        <div className="search-result__name">{p.h1}</div>
                        <div className="search-result__meta">
                          <span className="chip chip--good" style={{ fontSize: 11 }}>
                            <Icon name="check-circle" size={11} stroke={2.2} />
                            {inStock}/{offerCount} satıcı stokta
                          </span>
                          <span>· {p.category}</span>
                          {lastSeen && <span>· {timeAgoTr(lastSeen.lastSeenAt)} güncel</span>}
                        </div>
                      </div>
                      <div className="search-result__price-block">
                        <div className="search-result__price-from">başlangıç</div>
                        <div className="search-result__price tabular">{formatPrice(low)}</div>
                        <div className="search-result__merchants">{offerCount} satıcıdan</div>
                      </div>
                    </a>
                  );
                })
              )}
            </div>

            {/* Load more — live mode only */}
            {isLive && hasMore && !liveLoading && (
              <div style={{ textAlign: 'center', marginTop: 24 }}>
                <button
                  className="btn btn--ghost"
                  onClick={() => setLivePage((p) => p + 1)}
                >
                  Daha fazla göster
                  {liveResults && ` (${total - displayed.length} ürün daha)`}
                </button>
              </div>
            )}
            {isLive && liveLoading && liveResults && (
              <div style={{ textAlign: 'center', marginTop: 16, color: 'var(--km-ink-400)', fontSize: 13 }}>
                Yükleniyor…
              </div>
            )}

            <p
              style={{
                fontSize: 11,
                color: 'var(--km-ink-400)',
                marginTop: 16,
                textAlign: 'center',
              }}
            >
              Arama sayfaları noindex,follow · KVKK Aydınlatma · Sonuçlar 60sn Redis cache ile servis edilir
            </p>
          </div>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { SearchPage });
