/** FEAT-2: Becken-Liste — Gridify-Namenssuche + Infinite Scroll, Link auf Detailseite. */
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { de } from '../strings/de'
import { listEnclosuresPaged } from '../api/enclosures'
import { condition } from '../api/gridify'
import { useInfiniteList, useInfiniteSentinel } from '../hooks/useInfiniteList'

const PAGE_SIZE = 20

export default function BeckenPage() {
  const t = de.pages.becken
  const [search, setSearch] = useState('')

  const filter = search.trim()
    ? condition({ field: 'name', op: 'contains', value: search.trim() })
    : undefined
  // Infinite scroll; trailing `id` keeps OFFSET pagination stable (no repeats/omits).
  const list = useInfiniteList(
    (page) => listEnclosuresPaged({ filter, orderBy: 'name,id', page, pageSize: PAGE_SIZE }),
    `${filter ?? ''}`,
    'becken',
  )
  const sentinelRef = useInfiniteSentinel(list)
  const { items, total, loading } = list

  return (
    <section className="page">
      <header className="page-head">
        <div>
          <h2>{t.title}</h2>
          {!loading && (
            <p className="muted">
              {total} {t.countLabel}
            </p>
          )}
        </div>
        <Link to="/gehege/neu" className="btn btn--primary">
          + {t.newButton}
        </Link>
      </header>

      <div className="filters">
        <input
          type="search"
          className="input"
          placeholder={t.searchPlaceholder}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          aria-label={t.fields.name}
        />
      </div>

      {loading && <p className="muted">{de.common.loading}</p>}
      {list.error && (
        <div className="alert alert--error">
          <span>{list.error}</span>
          <button type="button" className="btn" onClick={list.reload}>
            {de.common.retry}
          </button>
        </div>
      )}

      {!loading && !list.error && items.length === 0 && <p className="muted">{t.empty}</p>}

      {items.length > 0 && (
        <ul className="card-list">
          {items.map((e) => (
            <li key={e.id}>
              <Link to={`/gehege/${e.id}`} className="gerbil-card">
                <span className="gerbil-card__name">{e.name}</span>
                <span className="gerbil-card__meta">{e.notes ?? ''}</span>
              </Link>
            </li>
          ))}
        </ul>
      )}

      {/* Infinite-scroll sentinel + "loading more" indicator. */}
      {list.hasMore && <div ref={sentinelRef} aria-hidden="true" style={{ height: 1 }} />}
      {list.loadingMore && (
        <p className="muted" style={{ textAlign: 'center', padding: '0.75rem 0' }}>
          {de.common.loading}
        </p>
      )}
    </section>
  )
}
