/**
 * TopDecliningPanel — "Top Declining Pages" section of the Dashboard.
 *
 * Extracted from Dashboard.tsx (DEBT-005) — behavior-preserving refactor only.
 * Hairline rows with monospace deltas. Empty-state preserves test-asserted phrasing.
 *
 * DUX-02: each declining-page row now has a per-row forward CTA that deep-links
 * to the Recommendations page pre-filtered to that page_url, matching the
 * every-row-needs-a-forward-action mandate the other list surfaces honour.
 */
import { BarChart3 } from 'lucide-react';

import { Link } from '@inertiajs/react';

import { EmptyState } from '@/Components/ui/empty-state';
import { Skeleton } from '@/Components/ui/skeleton';
import { EMPTY_TITLE } from '@/lib/emptyStateMessages';
import { truncateUrl } from '@/lib/format';

export interface TopDecliningPage {
  id: number;
  page_url: string;
  delta_percent: number;
  delta_absolute: number;
}

export interface TopDecliningPanelProps {
  topDeclining: TopDecliningPage[];
  firstSite: { id: string; name: string; domain: string } | null;
  isDecliningLoading: boolean;
  hasLatestAnalysis: boolean;
}

export function TopDecliningPanel({
  topDeclining,
  firstSite,
  isDecliningLoading,
  hasLatestAnalysis,
}: TopDecliningPanelProps) {
  return (
    <section aria-labelledby="declining-heading" className="mb-12">
      <div className="mb-4 flex items-end justify-between">
        <h2 id="declining-heading" className="editorial-rule left flex-1">
          Top Declining Pages
        </h2>
      </div>

      {isDecliningLoading ? (
        /* Shape-matched to the row list below: a bordered card holding 5
           divided rows, each with a left URL placeholder, a short delta
           placeholder, and a compact CTA placeholder.
           animate-pulse is gated to `animation: none` under
           prefers-reduced-motion in app.css. */
        <div
          className="rounded-2xl border bg-card overflow-hidden"
          role="status"
          aria-busy="true"
          aria-label="Loading top declining pages"
        >
          <ul className="divide-y">
            {Array.from({ length: 5 }).map((_, i) => (
              <li key={i} className="flex items-center gap-4 px-5 py-3">
                {/* role/aria-label overridden via spread — the wrapping card
                    owns the single status live region; the inner bars are
                    decorative so screen readers don't announce 10 "Loading"s. */}
                <Skeleton
                  variant="text-line"
                  role="presentation"
                  aria-label={undefined}
                  aria-busy={false}
                  className="h-4 w-2/3 max-w-xs flex-1"
                />
                <Skeleton
                  variant="text-line"
                  role="presentation"
                  aria-label={undefined}
                  aria-busy={false}
                  className="h-4 w-12 shrink-0"
                />
                <Skeleton
                  variant="text-line"
                  role="presentation"
                  aria-label={undefined}
                  aria-busy={false}
                  className="ml-auto h-4 w-10 shrink-0"
                />
              </li>
            ))}
          </ul>
        </div>
      ) : topDeclining.length > 0 ? (
        <div className="rounded-2xl border bg-card overflow-hidden">
          <ul className="divide-y">
            {topDeclining.map((page) => {
              /* DUX-02: build the recommendations deep-link for this page.
                 RecommendationsPageController accepts ?page_url= to scope the list
                 (R3UX-006). When firstSite is null (edge case), the CTA is omitted. */
              const fixHref = firstSite
                ? `${route('recommendations.index', firstSite.id)}?page_url=${encodeURIComponent(page.page_url)}`
                : null;

              return (
                <li
                  key={page.id}
                  className="flex items-center gap-4 px-5 py-3"
                >
                  <span
                    className="font-data text-sm text-muted-foreground truncate flex-1 min-w-0"
                    title={page.page_url}
                  >
                    {truncateUrl(page.page_url)}
                  </span>
                  <span
                    className="font-data text-sm font-semibold tabular-nums shrink-0 text-destructive-strong"
                    aria-label={`Traffic change: ${page.delta_percent >= 0 ? '+' : ''}${page.delta_percent.toFixed(1)}%`}
                  >
                    {page.delta_percent >= 0 ? '+' : ''}
                    {page.delta_percent.toFixed(1)}%
                  </span>
                  {/* DUX-02: per-row forward CTA — deep-links to the Recommendations
                      page filtered to this page_url. Styled consistent with the panel
                      footer link so it reads as navigation-affordance, not a button
                      that triggers a side-effect. */}
                  {fixHref && (
                    <Link
                      href={fixHref}
                      className="shrink-0 text-[11px] font-semibold uppercase tracking-[0.16em] text-primary hover:underline"
                      aria-label={`View recommendations for ${page.page_url}`}
                    >
                      Fix →
                    </Link>
                  )}
                </li>
              );
            })}
            {firstSite && (
              <li className="bg-muted/30 px-5 py-3">
                <Link
                  href={route('analyze.index', firstSite.id)}
                  className="text-[11px] font-semibold uppercase tracking-[0.16em] text-primary hover:underline"
                >
                  View Full Analysis →
                </Link>
              </li>
            )}
          </ul>
        </div>
      ) : hasLatestAnalysis ? (
        /* Ran-but-nothing: an analysis HAS completed but no page lost enough
           traffic to clear our significance threshold. Honest low-data copy —
           NOT "run an analysis" (they already did) and NOT a dead CTA back to
           a page that would just re-show this. Point them at the recommendations
           queue (real next step) instead. */
        <EmptyState
          variant="zero"
          icon={BarChart3}
          title={EMPTY_TITLE.lowDataDeclines}
          description="Your last analysis ran, but no page lost enough traffic to flag — we ignore pages with only a click or two so noise doesn't show up here. As your traffic grows this fills in; for now, work the recommendations queue to keep building."
          primaryAction={
            firstSite
              ? { label: 'View Recommendations', href: route('recommendations.index', firstSite.id) }
              : undefined
          }
        />
      ) : (
        /* Never-run: no analysis has completed yet — the CTA fires the action. */
        <EmptyState
          variant="zero"
          /* Override the default Sparkles icon — this surface is about
             traffic data, not analyses; BarChart3 is the right semantic. */
          icon={BarChart3}
          title={EMPTY_TITLE.declineData}
          description="Once you run an analysis, this shows your highest-priority pages — the ones losing the most traffic."
          primaryAction={
            firstSite ? { label: 'Run Analysis', href: route('analyze.index', firstSite.id) } : undefined
          }
        />
      )}
    </section>
  );
}
