import { useCallback, useEffect, useRef, useState } from "react"; import { API_V1, CREDENTIALS } from "../../apiContract"; import "../../viz/DashboardView.css"; import "../../styles/sdlc79/ranking-diagnostic.css"; import { ActionCadence } from "../actions/ActionCadence"; import { ActionList } from "../actions/ActionList"; import { SkuActions } from "../actions/SkuActions"; import type { SkuAction } from "../actions/actionsApi"; import Benchmark from "./Benchmark"; import Dashboard, { AppTabs, SourceTrend } from "./Dashboard"; // S79-T20 (C2, C4, R18): the Ranking diagnostic App screen. The dispatcher draws the App frame, so this // view draws only the week, the status tabs, the drop list, the ASIN list and the item drawer. No chat panel. export interface RankingDiagnosticApplication { id: string; name?: string; capabilities?: Record; } const DEFAULT_STATUSES = ["Open", "In progress", "Fixed", "Ignored"]; const DROPS = "Drops"; const ASINS = "All ASINs"; const BENCHMARK = "Benchmark"; const DASHBOARD = "dashboard"; const tabLabel = (id: string) => id === DASHBOARD ? "Dashboard" : id; /** The one empty sentence per tab. */ const EMPTY: Record = { [DROPS]: "No drops this week", Open: "No open drops", "In progress": "No drops in progress", Fixed: "No fixed drops", Ignored: "No ignored drops", [ASINS]: "No ASINs this week", }; type SignalKey = "sessions" | "buyBox" | "units" | "salesRank" | "searchShare" | "adSpend"; /** The six weekly signals, in card order. Rank is better when it is lower. */ const SIGNALS: { key: SignalKey; label: string; short: string }[] = [ { key: "sessions", label: "Sessions", short: "Sessions" }, { key: "buyBox", label: "Buy Box", short: "Buy Box" }, { key: "units", label: "Units", short: "Units" }, { key: "salesRank", label: "Sales rank", short: "Rank" }, { key: "searchShare", label: "Search-term share", short: "Search share" }, { key: "adSpend", label: "Ad spend", short: "Ad spend" }, ]; interface Drop { id: string; week: string; asin: string; sku: string; productTitle: string; causeKey: string; cause: string; fix: string; reason: string; signals: string[]; status: string; owner: string; due: string; rankNow: number | null; rankChange: number | null; rankTrend: { week: string; rank: number | null }[]; } /** Weekly points held against the two the diagnostic compares, and the day the next one can land. */ interface Readiness { held: number; needed: number; nextSync: string } interface Screen { canEdit: boolean; week: string; weeks: string[]; counts: Record; items: Drop[]; cursor: string | null; problems: string[]; statuses: string[]; total: number; summedAsins: number | null; readiness: Readiness | null; } interface AsinRow { asin: string; title: string; skus: string[]; units: number | null; sales: number | null; causeLabel: string; itemId: string; } interface AsinPage { asins: AsinRow[]; cursor: string | null; total: number } type Point = { week: string } & Record; interface HistoryEvent { at: string; by: string; status: string; owner: string; due: string; note: string } interface Detail { item: Drop; history: HistoryEvent[] } interface ContentChange { id: string; day: string; sku: string; field: string; label: string; before: string; after: string; rankDrop: { day: string; before: number; after: number } | null; } interface ContentPage { changes: ContentChange[]; cursor: string | null } /** What the drawer is open on: an ASIN, with its drop item when it has one. */ interface Opened { asin: string; title: string; itemId: string; week: string } type Row = Record; type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; const text = (value: unknown) => (typeof value === "string" ? value : typeof value === "number" ? String(value) : ""); const num = (value: unknown) => { if (typeof value === "number" && Number.isFinite(value)) return value; if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value); return null; }; const rows = (raw: unknown): Row[] => (Array.isArray(raw) ? raw : []) .filter((row): row is Row => !!row && typeof row === "object" && !Array.isArray(row)); const strings = (raw: unknown) => (Array.isArray(raw) ? raw : []).map(text).filter(Boolean); async function readJson(response: Response, fallback: string): Promise { const body: unknown = await response.json().catch(() => null); if (response.ok) return body; // main.py reshapes every refusal to a top-level `error`; a bare router answers under `detail`. const shaped = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown } } } | null; throw new Error(text(shaped?.error?.message) || text(shaped?.detail?.error?.message) || fallback); } const failure = (reason: unknown, fallback: string) => (reason instanceof Error && reason.message ? reason.message : fallback); function parseDrop(raw: unknown): Drop | null { const row = (raw ?? {}) as Row; const id = text(row.id); if (!id) return null; return { id, week: text(row.week), asin: text(row.asin), sku: text(row.sku), productTitle: text(row.productTitle), causeKey: text(row.causeKey), cause: text(row.cause), fix: text(row.fix), reason: text(row.reason), signals: strings(row.signals), status: text(row.status) || "Open", owner: text(row.owner), due: text(row.due), rankNow: num(row.rankNow), rankChange: num(row.rankChange), rankTrend: rows(row.rankTrend).map((point) => ({ week: text(point.week), rank: num(point.rank) })) .filter((point) => point.week), }; } /** Read readiness from the same scoped screen response as the rows. */ function parseReadiness(body: Row): Readiness | null { const sent = body.readiness as Row | null | undefined; if (sent && typeof sent === "object") { const held = num(sent.heldWeeks); if (held === null) return null; return { held, needed: num(sent.weeksNeeded) ?? 2, nextSync: text(sent.nextSync) }; } return null; } function parseScreen(raw: unknown): Screen { const body = (raw ?? {}) as Row; const counts: Record = {}; for (const [key, value] of Object.entries((body.counts ?? {}) as Row)) counts[key] = num(value) ?? 0; const statuses = strings(body.statuses); return { canEdit: body.canEdit === true, week: text(body.week), weeks: strings(body.weeks), counts, items: (Array.isArray(body.items) ? body.items : []).map(parseDrop).filter((row): row is Drop => row !== null), cursor: text(body.cursor) || null, problems: strings(body.problems), statuses: statuses.length ? statuses : DEFAULT_STATUSES, total: num(body.total) ?? 0, summedAsins: num((body.sourceTotals as Row | null)?.summedAsins), readiness: parseReadiness(body), }; } function parseAsins(raw: unknown): AsinPage { const body = (raw ?? {}) as Row; const list = rows(body.asins).map((row) => ({ asin: text(row.asin), title: text(row.title), skus: strings(row.skus), units: num(row.units), sales: num(row.sales), causeLabel: text(row.causeLabel), itemId: text(row.itemId), })).filter((row) => row.asin); return { asins: list, cursor: text(body.cursor) || null, total: num(body.total) ?? list.length }; } function parsePoints(raw: unknown): Point[] { return rows((raw as Row | null)?.points).map((row) => ({ week: text(row.week), sessions: num(row.sessions), buyBox: num(row.buyBox), units: num(row.units), salesRank: num(row.salesRank), searchShare: num(row.searchShare), adSpend: num(row.adSpend), })).filter((point) => point.week).sort((a, b) => a.week.localeCompare(b.week)); } function parseDetail(raw: unknown): Detail | null { const body = (raw ?? {}) as Row; const item = parseDrop(body.item); if (!item) return null; return { item, history: rows(body.history).map((event) => ({ at: text(event.at), by: text(event.by), status: text(event.status), owner: text(event.owner), due: text(event.due), note: text(event.note), })), }; } function parseContent(raw: unknown): ContentPage { const body = (raw ?? {}) as Row; return { cursor: text(body.cursor) || null, changes: rows(body.changes).map((row) => { const drop = (row.rankDrop ?? {}) as Row; const before = num(drop.before), after = num(drop.after); return { id: text(row.id), day: text(row.day), sku: text(row.sku), field: text(row.field), label: text(row.label), before: text(row.before), after: text(row.after), rankDrop: text(drop.day) && before !== null && after !== null ? { day: text(drop.day), before, after } : null }; }) }; } /** "Oct 18, 2026" from an ISO day or stamp. A calendar day is read in UTC. */ function dayWords(raw: string) { const value = raw.trim(); const date = new Date(value.length === 10 ? value + "T00:00:00Z" : value); return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }); } const plural = (n: number, one: string, many: string) => `${n.toLocaleString()} ${n === 1 ? one : many}`; const whole = (value: number) => Math.round(value).toLocaleString(); const decimals = (value: number, places: number) => value.toLocaleString(undefined, { maximumFractionDigits: places }); const money = (value: number) => value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); /** One signal's value as a person reads it. */ function signalValue(key: SignalKey, value: number | null) { if (value === null) return "Not reported"; if (key === "buyBox") return `${decimals(value, 1)}%`; if (key === "salesRank") return `#${whole(value)}`; if (key === "searchShare") return decimals(value, 2); if (key === "adSpend") return money(value); return whole(value); } interface Delta { words: string; tone: "up" | "down" | "flat" } /** The change from the week before, toned by whether it is good for the ASIN. */ function signalDelta(key: SignalKey, before: number | null, now: number | null): Delta | null { if (before === null || now === null) return null; if (key === "buyBox") { const points = now - before; if (Math.abs(points) < 0.5) return { words: "No change", tone: "flat" }; return { words: `${points < 0 ? "Down" : "Up"} ${decimals(Math.abs(points), 0)} points`, tone: points < 0 ? "down" : "up" }; } if (before === 0) return now === 0 ? { words: "No change", tone: "flat" } : null; const pct = ((now - before) / Math.abs(before)) * 100; if (Math.abs(pct) < 0.5) return { words: "No change", tone: "flat" }; if (key === "salesRank") { return pct > 0 ? { words: `Worse by ${decimals(pct, 0)}%`, tone: "down" } : { words: `Better by ${decimals(-pct, 0)}%`, tone: "up" }; } return { words: `${pct < 0 ? "Down" : "Up"} ${decimals(Math.abs(pct), 0)}%`, tone: pct < 0 ? "down" : "up" }; } const fellWords = (signals: string[]) => signals .map((key) => SIGNALS.find((signal) => signal.key === key)?.short ?? key).join(", "); function Skeleton({ chart }: { chart?: boolean }) { return
{chart ?
: <>
}
; } function Failed({ message, onRetry }: { message: string; onRetry: () => void }) { return

{message}{" "}

; } /** A small weekly rank line. Rank is better when lower, so a better week draws higher. */ function RankSpark({ points, asin }: { points: { week: string; rank: number | null }[]; asin: string }) { const held = points.filter((point): point is { week: string; rank: number } => point.rank !== null); if (held.length < 2) return No trend; const ranks = held.map((point) => point.rank); const low = ranks.reduce((a, b) => Math.min(a, b)), high = ranks.reduce((a, b) => Math.max(a, b)), span = high - low || 1; const width = 96, height = 24, step = width / (points.length - 1); const segments: string[][] = [[]]; points.forEach((point, index) => { if (point.rank === null) { segments.push([]); return; } segments[segments.length - 1].push(`${(index * step).toFixed(1)},${(2 + ((point.rank - low) / span) * (height - 4)).toFixed(1)}`); }); const worse = ranks[ranks.length - 1] > ranks[0]; return {points.map((point) => `${point.week}: ${point.rank === null ? "Not reported" : `#${whole(point.rank)}`}`).join(", ")} {segments.filter((line) => line.length > 1).map((line, index) => )} {points.map((point, index) => point.rank === null ? null : )} ; } const STATUS_TONE: Record = { Open: "is-open", "In progress": "is-progress", Fixed: "is-fixed", Ignored: "is-ignored" }; function StatusChip({ status }: { status: string }) { return {status}; } function RankChange({ drop }: { drop: Drop }) { const before = drop.rankNow !== null && drop.rankChange !== null ? drop.rankNow - drop.rankChange : null; const delta = signalDelta("salesRank", before, drop.rankNow); return delta ? {delta.words} : No comparison; } function DropTable({ items, onOpen }: { items: Drop[]; onOpen: (drop: Drop) => void }) { return {items.map((drop) => )}
ProductRank nowRank change Weekly rankStatus
{[drop.asin, drop.sku].filter(Boolean).join(" · ")}
Details {drop.cause} {fellWords(drop.signals)} {drop.owner || "No owner"}
{drop.rankNow === null ? Not reported : signalValue("salesRank", drop.rankNow)}
; } const AMAZON_CONNECTOR = "#/connectors?connector=amazon_sp&tab=overview"; /** Shown until two weekly syncs are held: one action over three short steps, weeks held and the next sync. */ function FirstRun({ readiness }: { readiness: Readiness }) { const steps: [string, string][] = [ ["Connect Amazon", "Sales, traffic and catalog data"], ["Two weekly syncs", "Each week adds one rank point"], ["See each drop", "Rank, cause and a fix per ASIN"], ]; const held = Math.min(readiness.held, readiness.needed); return

Two weekly syncs needed

{readiness.held} of {readiness.needed} weeks held {readiness.nextSync && <> · Next weekly sync {dayWords(readiness.nextSync)}}

Open Amazon connector
    {steps.map(([title, line], index) =>
  1. {title} {line}
  2. )}
; } function AsinTable({ list, onOpen }: { list: AsinRow[]; onOpen: (row: AsinRow) => void }) { return {list.map((row) => )}
ASINUnits SalesDrop
{(row.title || row.skus[0]) && {row.title || row.skus[0]}} {row.units === null ? "" : whole(row.units)} {row.units !== null && {row.units === 1 ? " unit" : " units"}} {row.sales === null ? "" : money(row.sales)} {row.causeLabel || None}
; } function SignalTrend({ points, signal, asin, week }: { points: Point[]; signal: SignalKey; asin: string; week: string }) { const meta = SIGNALS.find((row) => row.key === signal) ?? SIGNALS[0]; const held = points.filter((point) => point[signal] !== null).length; if (points.length < 2) return

The trend shows after two weekly syncs.

; if (held < 2) return

{meta.label} is not reported for two weeks yet.

; return ({ x: point.week, value: point[signal] }))} label={`${meta.label} by week for ${asin}`} reverse={signal === "salesRank"} format={signal === "salesRank" ? ",d" : undefined} selected={week} />; } /** The signal cards double as the chart's tabs: one card per signal, value over its weekly change. */ function SignalCards({ points, week, picked, onPick }: { points: Point[]; week: string; picked: SignalKey; onPick: (key: SignalKey) => void; }) { const index = points.findIndex((point) => point.week === week); const at = index >= 0 ? index : points.length - 1; const now = points[at] ?? null; const before = at > 0 ? points[at - 1] : null; return <>{before &&

Against the week of {dayWords(before.week)}

}
{SIGNALS.map((signal) => { const delta = now && before ? signalDelta(signal.key, before[signal.key], now[signal.key]) : null; return ; })}
; } interface DrawerProps { appId: string; opened: Opened; url: (path: string, params?: Record) => string; editable: boolean; statuses: string[]; onClose: () => void; onSaved: () => void; } function ContentTimeline({ changes }: { changes: ContentChange[] }) { if (!changes.length) return

No content changes

; return
    {changes.map((change) =>
  1. {change.label}{" · "}{change.sku}
    Before
    {change.before || "Empty"}
    After
    {change.after || "Empty"}
    {change.rankDrop && Before rank drop on {dayWords(change.rankDrop.day)}{" "} (#{whole(change.rankDrop.before)} to #{whole(change.rankDrop.after)}) }
  2. )}
; } function ContentChanges({ asin, url, onRank }: { asin: string; url: DrawerProps["url"]; onRank: () => void; }) { const [result, setResult] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const [cursors, setCursors] = useState([""]); const [page, setPage] = useState(0); const cursor = cursors[page] ?? ""; useEffect(() => { const controller = new AbortController(); setResult({ phase: "loading" }); void fetch(url(`/content-history/${encodeURIComponent(asin)}`, { cursor, limit: "200" }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Content changes could not be loaded.")) .then((body) => { if (!controller.signal.aborted) setResult({ phase: "ready", value: parseContent(body) }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setResult({ phase: "error", message: failure(reason, "Content changes could not be loaded.") }); }); return () => controller.abort(); }, [asin, url, cursor, attempt]); return

Content changes

{result.phase === "loading" && } {result.phase === "error" && setAttempt((n) => n + 1)} />} {result.phase === "ready" && <> {(page > 0 || result.value.cursor) &&
Page {page + 1}
} }
; } function Drawer({ appId, opened, url, editable, statuses, onClose, onSaved }: DrawerProps) { const [detail, setDetail] = useState>({ phase: "loading" }); const [detailAttempt, setDetailAttempt] = useState(0); const [trend, setTrend] = useState>({ phase: "loading" }); const [trendAttempt, setTrendAttempt] = useState(0); const [signal, setSignal] = useState("salesRank"); const [status, setStatus] = useState(""); const [saving, setSaving] = useState(false); const [saveError, setSaveError] = useState(""); const [saved, setSaved] = useState(false); useEffect(() => { if (!opened.itemId) { setDetail({ phase: "ready", value: null }); return; } const controller = new AbortController(); setDetail({ phase: "loading" }); void fetch(url(`/items/${encodeURIComponent(opened.itemId)}`), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "This drop could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseDetail(body); if (!value) { setDetail({ phase: "error", message: "This drop could not be loaded." }); return; } setDetail({ phase: "ready", value }); setStatus(value.item.status); const first = value.item.signals.includes("salesRank") ? SIGNALS.find((row) => row.key === "salesRank") : SIGNALS.find((row) => value.item.signals.includes(row.key)); if (first && detailAttempt === 0) setSignal(first.key); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setDetail({ phase: "error", message: failure(reason, "This drop could not be loaded.") }); }); return () => controller.abort(); }, [url, opened.itemId, detailAttempt]); useEffect(() => { const controller = new AbortController(); setTrend({ phase: "loading" }); void fetch(url(`/trend/${encodeURIComponent(opened.asin)}`), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "The trend could not be loaded.")) .then((body) => { if (!controller.signal.aborted) setTrend({ phase: "ready", value: parsePoints(body) }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setTrend({ phase: "error", message: failure(reason, "The trend could not be loaded.") }); }); return () => controller.abort(); }, [url, opened.asin, trendAttempt]); const item = detail.phase === "ready" ? detail.value?.item ?? null : null; const changed = item !== null && status !== "" && status !== item.status; const save = async () => { if (!item || !changed) return; setSaving(true); setSaveError(""); setSaved(false); try { const response = await fetch(url(`/items/${encodeURIComponent(item.id)}`), { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status }), }); await readJson(response, "The status was not saved."); setSaved(true); setDetailAttempt((count) => count + 1); onSaved(); } catch (reason) { setSaveError(failure(reason, "The status was not saved.")); } finally { setSaving(false); } }; const history = detail.phase === "ready" ? detail.value?.history ?? [] : []; const week = item?.week || opened.week; // D-12061, D-12028: the shared SKU actions drawer holds this ASIN's detail, its action list and the App cadence. return
{detail.phase === "loading" && } {detail.phase === "error" && setDetailAttempt((count) => count + 1)} />} {detail.phase === "ready" && !item &&

No drop this week

} {item &&

Cause

{item.cause}

{item.reason &&

{item.reason}

}

Fix

{item.fix}

} {item && (editable ?
{ event.preventDefault(); void save(); }}>
{saved && Saved}
{saveError &&

{saveError}

}
: null)}

Weekly trend

{trend.phase === "loading" && } {trend.phase === "error" && setTrendAttempt((count) => count + 1)} />} {trend.phase === "ready" && <>
}
setSignal("salesRank")} /> {item &&
{!editable &&
Status
{item.status}
}
Owner
{item.owner || "No owner"}
{item.due &&
Due
{dayWords(item.due)}
}
Week of
{dayWords(item.week)}
} {history.length > 0 &&

History

    {history.map((event, index) =>
  1. {event.status} {[event.by && `By ${event.by}`, event.owner && `Owner ${event.owner}`, event.due && `Due ${dayWords(event.due)}`, event.note].filter(Boolean).join(", ")} {event.at ? dayWords(event.at) : "Unknown date"}
  2. )}
}
; } export default function RankingDiagnosticView({ application, canEdit }: { application: RankingDiagnosticApplication; canEdit?: boolean; }) { const appId = application.id; const url = useCallback((path: string, params: Record = {}) => { const query = new URLSearchParams({ app: appId, ...params }); return `${API_V1}/app-kinds/ranking_diagnostic${path}?${query.toString()}`; }, [appId]); const [tab, setTab] = useState(DROPS); const [week, setWeek] = useState(""); const [search, setSearch] = useState(""); const [query, setQuery] = useState(""); const [page, setPage] = useState(0); const [screenCursors, setScreenCursors] = useState([""]); const [asinCursors, setAsinCursors] = useState([""]); const [screen, setScreen] = useState>({ phase: "loading" }); const [screenAttempt, setScreenAttempt] = useState(0); const [held, setHeld] = useState<{ week: string; weeks: string[]; counts: Record | null; summedAsins: number | null; readiness?: Readiness | null }>({ week: "", weeks: [], counts: null, summedAsins: null }); const [statuses, setStatuses] = useState(DEFAULT_STATUSES); const [problems, setProblems] = useState([]); const [serverEdit, setServerEdit] = useState(false); const [asins, setAsins] = useState>({ phase: "loading" }); const [asinAttempt, setAsinAttempt] = useState(0); const [opened, setOpened] = useState(null); const [listedAction, setListedAction] = useState(null); const opener = useRef(null); const statusTab = statuses.includes(tab) ? tab : ""; const screenParams = useCallback((extra: Record = {}) => { const params: Record = { limit: "200", q: query, ...extra }; if (statusTab) params.status = statusTab; if (week) params.week = week; return params; }, [statusTab, week, query]); const screenCursor = screenCursors[page] ?? ""; const asinCursor = asinCursors[page] ?? ""; useEffect(() => { const controller = new AbortController(); setScreen({ phase: "loading" }); void fetch(url("/screen", screenParams({ cursor: screenCursor })), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "The drop list could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseScreen(body); setScreen({ phase: "ready", value }); setHeld({ week: value.week, weeks: value.weeks, counts: value.counts, summedAsins: value.summedAsins, readiness: value.readiness }); setStatuses(value.statuses); setProblems(value.problems); setServerEdit(value.canEdit); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setScreen({ phase: "error", message: failure(reason, "The drop list could not be loaded.") }); }); return () => controller.abort(); }, [url, screenParams, screenAttempt, screenCursor]); useEffect(() => { const controller = new AbortController(); setAsins({ phase: "loading" }); const params: Record = { limit: "200", q: query, cursor: asinCursor }; if (week) params.week = week; void fetch(url("/asins", params), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "The ASIN list could not be loaded.")) .then((body) => { if (!controller.signal.aborted) setAsins({ phase: "ready", value: parseAsins(body) }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setAsins({ phase: "error", message: failure(reason, "The ASIN list could not be loaded.") }); }); return () => controller.abort(); }, [url, week, asinAttempt, query, asinCursor]); const editable = canEdit === true && serverEdit; const resetPages = () => { setPage(0); setScreenCursors([""]); setAsinCursors([""]); }; const nextPage = () => { if (!cursor) return; if (tab === ASINS) setAsinCursors((now) => [...now.slice(0, page + 1), cursor]); else setScreenCursors((now) => [...now.slice(0, page + 1), cursor]); setPage((now) => now + 1); }; const open = (next: Opened) => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; setListedAction(null); setOpened(next); }; const closeDrawer = useCallback(() => { setOpened(null); opener.current?.focus(); }, []); const onSaved = useCallback(() => { setPage(0); setScreenCursors([""]); setAsinCursors([""]); setScreenAttempt((count) => count + 1); }, []); const counts = held.counts; const dropTotal = counts ? statuses.reduce((sum, status) => sum + (counts[status] ?? 0), 0) : null; const asinTotal = asins.phase === "ready" ? asins.value.total : null; const tabs: [string, number | null][] = [[DROPS, dropTotal], [DASHBOARD, null], ...statuses.map((status): [string, number | null] => [status, counts ? counts[status] ?? 0 : null]), [ASINS, asinTotal], [BENCHMARK, null]]; const state = tab === ASINS ? asins : screen; const retry = () => (tab === ASINS ? setAsinAttempt : setScreenAttempt)((count) => count + 1); const listed = tab === ASINS ? (asins.phase === "ready" ? asins.value.asins.length : 0) : (screen.phase === "ready" ? screen.value.items.length : 0); const total = tab === ASINS ? asinTotal ?? listed : screen.phase === "ready" ? screen.value.total : 0; const cursor = tab === ASINS ? (asins.phase === "ready" ? asins.value.cursor : null) : (screen.phase === "ready" ? screen.value.cursor : null); const shownWeek = week || held.week; const readiness = held.readiness ?? null; if (screen.phase === "ready" && readiness && readiness.held < readiness.needed) { return
; } return
{tab !== DASHBOARD && tab !== BENCHMARK && shownWeek &&
{held.weeks.length > 1 ? :

Week of {dayWords(shownWeek)}

} {held.summedAsins !== null && {plural(held.summedAsins, "summed ASIN", "summed ASINs")}}
} {tab !== DASHBOARD && tab !== BENCHMARK &&
{ event.preventDefault(); setQuery(search.trim()); resetPages(); setOpened(null); setListedAction(null); }}>
} ({ id, label: tabLabel(id), count }))} value={tab} aria-label="Ranking diagnostic tabs" onChange={(key) => { setTab(key); resetPages(); setOpened(null); setListedAction(null); }} /> {tab !== DASHBOARD && tab !== BENCHMARK && problems.length > 0 &&
{problems.map((problem) =>

{problem}

)}
}
{tab === DASHBOARD ? : tab === BENCHMARK ? : <> {state.phase === "loading" && } {state.phase === "error" && } {state.phase === "ready" && listed === 0 &&

{EMPTY[tab] ?? "Nothing here"}

} {tab !== ASINS && screen.phase === "ready" && listed > 0 && open({ asin: drop.asin, title: drop.productTitle, itemId: drop.id, week: drop.week })} />} {tab === ASINS && asins.phase === "ready" && listed > 0 && open({ asin: row.asin, title: row.title, itemId: row.itemId, week: shownWeek })} />} {state.phase === "ready" && (listed > 0 || page > 0) &&
{tab === ASINS ? plural(total, "ASIN", "ASINs") : plural(total, "drop", "drops")} Page {page + 1}
} { setOpened(null); setListedAction(action); }} /> }
{opened && } {listedAction && setListedAction(null)} />}
; }