import { Link, useParams } from 'react-router-dom'
import PublicLayout from '../../components/PublicLayout.jsx'
import PageHeader from '../../components/PageHeader.jsx'
import { Loading, ErrorState, EmptyState } from '../../components/PageState.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { api } from '../../api/client.js'

// One player vendor: where to find it and everything it is selling.
//
// The page a search result points at. Two states it has to render honestly and
// which the search list cannot (docs/link/v3.md §8):
//
//   • `truncated` — the shop holds more than the shard publishes per frame. A
//     commodity reseller with thousands of stacks is a real thing, and showing
//     250 of 3,104 as if it were the whole shop would be a lie about the shard.
//   • a gated `location` — an admin may put vendor whereabouts behind a rung, in
//     which case there is nothing to render and the page says so rather than
//     showing an empty coordinate.

const num = (v) => (Number.isFinite(Number(v)) ? Number(v).toLocaleString() : '—')

const itemLabel = (i) => i.displayName || i.name || `id ${i.itemId}`

export default function MarketVendor() {
  const { serial } = useParams()
  const { loading, error, data } = useAsync(() => api.shard.marketVendor(serial), [serial])

  if (loading) {
    return (
      <PublicLayout section="website">
        <div className="shell-narrow page-body"><Loading /></div>
      </PublicLayout>
    )
  }

  if (error || !data) {
    return (
      <PublicLayout section="website">
        <div className="shell-narrow page-body">
          <ErrorState message="That shop is not in the index — it may have been dismissed or hidden." />
          <p style={{ marginTop: 16 }}>
            <Link to="/site/market" className="sans">← Back to the marketplace</Link>
          </p>
        </div>
      </PublicLayout>
    )
  }

  const loc = data.location || null
  const items = data.items || []

  return (
    <PublicLayout section="website">
      <div className="shell-narrow page-body">
        <PageHeader
          eyebrow={data.ownerName ? `Run by ${data.ownerName}` : 'Player vendor'}
          title={data.shopName || 'An unnamed shop'}
          lead={
            loc
              ? [loc.house, loc.region, loc.map].filter(Boolean).join(' · ') +
                (Number.isFinite(loc.x) ? ` — ${loc.x}, ${loc.y}` : '')
              : 'This shard does not publish vendor locations.'
          }
        />

        <p className="sans dim" style={{ fontSize: '0.78rem', margin: '-12px 0 18px' }}>
          {data.truncated
            ? `Showing ${num(data.count)} of ${num(data.total)} listings — this shop holds more than the shard publishes.`
            : `${num(data.total)} listing${data.total === 1 ? '' : 's'}`}
          {data.updatedAt ? ` · last seen ${new Date(data.updatedAt).toLocaleString()}` : ''}
        </p>

        {items.length === 0 ? (
          <EmptyState>This shop has nothing priced for sale.</EmptyState>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {items.map((i) => (
              <div
                key={i.serial}
                className="panel"
                style={{ padding: '10px 14px', display: 'flex', gap: 12, alignItems: 'baseline' }}
              >
                <span className="sans" style={{ flex: 1, minWidth: 0, color: 'var(--head)', fontSize: '0.88rem' }}>
                  {i.amount > 1 ? `${num(i.amount)} × ` : ''}
                  {itemLabel(i)}
                  {i.child ? <span className="dim"> · sold with its container</span> : null}
                </span>
                <span className="sans" style={{ flex: 'none', color: 'var(--head)', fontSize: '0.88rem' }}>
                  {num(i.price)}
                </span>
              </div>
            ))}
          </div>
        )}

        <p style={{ marginTop: 20 }}>
          <Link to="/site/market" className="sans">← Back to the marketplace</Link>
        </p>
      </div>
    </PublicLayout>
  )
}
