---
// Search: poets/writers by name and books/chapters by title (first page), then the content results, paged
import Base from '../layouts/Base.astro';
import Icon from '../components/Icon.astro';
import Seg from '../components/Seg.astro';
import Tags from '../components/Tags.astro';
import { api } from '../lib/api';
import { ud, years, highlighter, parts, excerpt } from '../lib/urdu';
const q = Astro.url.searchParams.get('q')?.trim() ?? '';
// one or more poets/writers to search within (?poet=1&poet=2, or ?poet=1,2)
const poetIds = [...new Set(Astro.url.searchParams.getAll('poet').flatMap((v) => v.split(',')).map(Number).filter((n) => n > 0))];
const pageNo = Math.max(1, Number(Astro.url.searchParams.get('page')) || 1);
const res = q ? await api(`/api/search?q=${encodeURIComponent(q)}&page=${pageNo}${poetIds.length ? `&poet=${poetIds.join(',')}` : ''}`) : null;
// every poet/writer for the name box (382; filtered in the browser)
const allPoets = res ? ((await api('/api/poets')) ?? []).map((p: any) => ({ id: p.id, name: p.nickname })) : [];
const pages = res ? Math.ceil(res.total / res.pageSize) : 0;
const re = highlighter(q);
const hl = (t: string) => parts(t, re).map((s, i): [string, string] => [s, i % 2 ? 'mark' : '']);
const open = (url: string) => `${url}?hl=${encodeURIComponent(q)}`;
const link = (n: number, poets: number[] = poetIds) => `/search?q=${encodeURIComponent(q)}${poets.length ? `&poet=${poets.join(',')}` : ''}${n > 1 ? `&page=${n}` : ''}`;
// author chips: the selected ones first, then the authors the results come from
const chips = res ? [...res.selected.map((p: any) => ({ ...p, n: res.authors.find((a: any) => a.id === p.id)?.n ?? 0 })),
...res.authors.filter((a: any) => !poetIds.includes(a.id))] : [];
// numbered pages: first, last, and two either side of the current one; gaps shown as …
const numbers = (() => {
const keep = new Set([1, pages, pageNo - 2, pageNo - 1, pageNo, pageNo + 1, pageNo + 2].filter((n) => n >= 1 && n <= pages));
const sorted = [...keep].sort((a, b) => a - b), out: (number | null)[] = [];
sorted.forEach((n, i) => { if (i && n - sorted[i - 1] > 1) out.push(null); out.push(n); });
return out;
})();
const from = res ? (pageNo - 1) * res.pageSize + 1 : 0, to = res ? Math.min(res.total, pageNo * res.pageSize) : 0;
---
اوپر کے خانے میں شاعر کا نام، شعر، لفظ یا عبارت لکھیں۔ پوری عبارت کے لیے اسے "…" میں لکھیں۔ کسی ٹیگ والا کلام: ٹیگ:عشق (نام میں فاصلہ ہو تو ٹیگ:"حب الوطنی")۔ تمام ٹیگ
} {res && ( <>{res.total ? (pages > 1 ? `نتائج ${ud(from)}–${ud(to)} از ${ud(res.total)}` : `${ud(res.total)} نتائج`) : 'کلام میں کوئی نتیجہ نہیں ملا۔ کم الفاظ یا کلیدی لفظ آزمائیں۔'}
{res.results.map((r: any) => ( ))} {pages > 1 && ( )}