/**
 * GscMetricsPanel — hairline 4-cell grid for the "Metrics · Last 28 Days" section.
 *
 * Extracted from Dashboard.tsx (DEBT-005) — behavior-preserving refactor only.
 * No logic or copy changes.
 */
import { BarChart3, FileText, Siren, Sparkles, TrendingDown, TrendingUp } from 'lucide-react';

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

import ContextualHelp from '@/Components/Shared/ContextualHelp';
import { Eyebrow } from '@/Components/ui/eyebrow';
import { Skeleton } from '@/Components/ui/skeleton';
import { formatNumber, formatRelativeTime } from '@/lib/format';
import { cn } from '@/lib/utils';

export interface GscMetricsPanelProps {
  dashboardMetrics: {
    total_clicks_28d: number;
    total_clicks_28d_prior: number;
    total_clicks_28d_delta_percent: number | null;
    pending_recommendations: number;
    drafts_generated_month: number;
    latest_analysis_at: string | null;
  } | null;
  firstSite: { id: string; name: string; domain: string } | null;
  isActivated: boolean;
  isDataLoading: boolean;
  gscSyncing: boolean;
  openTrafficAlertsCount: number;
  siteCount: number;
}

export function GscMetricsPanel({
  dashboardMetrics,
  firstSite,
  isActivated,
  isDataLoading,
  gscSyncing,
  openTrafficAlertsCount,
  siteCount,
}: GscMetricsPanelProps) {
  return (
    <section aria-labelledby="metrics-heading" className="mb-12">
      {/* Section heading row: title on the left, an open-alerts pill on
          the right when there's anything to look at. The alerts route is
          site-scoped, so we land the user on first_site's alerts surface;
          that's the implicit landing context the rest of the dashboard
          uses for portfolio users. The /alerts page itself shows portfolio
          alerts via the SiteSwitcher in DashboardLayout. */}
      <div className="mb-4 flex items-end justify-between gap-3">
        <h2 id="metrics-heading" className="editorial-rule left flex-1">
          Metrics · Last 28 Days
        </h2>
        {openTrafficAlertsCount > 0 && firstSite && (
          <Link
            href={route('alerts.index', firstSite.id)}
            className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-warning/40 bg-warning/5 px-2.5 py-1 text-[11px] font-semibold text-warning transition-colors hover:bg-warning/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
            aria-label={`${openTrafficAlertsCount} open traffic ${openTrafficAlertsCount === 1 ? 'alert' : 'alerts'} — view details`}
          >
            <Siren className="size-3" aria-hidden="true" />
            <span className="font-data tabular-nums">{openTrafficAlertsCount}</span>
            <span>open {openTrafficAlertsCount === 1 ? 'alert' : 'alerts'}</span>
            <span aria-hidden="true">→</span>
          </Link>
        )}
      </div>

      <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border bg-border lg:grid-cols-4">
        {/* Total Clicks 28d */}
        <div
          className="bg-card p-5 flex flex-col gap-3 min-h-[124px]"
          aria-busy={isDataLoading || undefined}
        >
          <div className="flex items-start justify-between gap-2">
            <div className="flex items-center gap-1.5">
              <Eyebrow as="span" className="text-muted-foreground">
                Total Clicks (28d)
              </Eyebrow>
              <ContextualHelp>
                All-pages site-wide traffic: the total number of times users clicked on any of
                your pages from Google search results in the last 28 days. This is whole-site
                GSC traffic, not recommendation-attributed recovery.
              </ContextualHelp>
            </div>
            <BarChart3 className="size-3.5 text-muted-foreground/60 shrink-0" />
          </div>
          {isDataLoading ? (
            /* Shape: one tall number bar + one short subtext bar,
               matching the 3xl value + xs caption below. */
            <>
              <Skeleton variant="text-line-lg" className="h-8 w-24" aria-label="Loading clicks" />
              <Skeleton variant="text-line" className="h-3 w-28" aria-busy={false} role="presentation" aria-label={undefined} />
            </>
          ) : dashboardMetrics ? (
            <>
              <div className="font-data text-3xl font-semibold tabular-nums tracking-tight text-foreground">
                {formatNumber(dashboardMetrics.total_clicks_28d)}
              </div>
              {/* Trend line: shown only when prior period had clicks (not
                  null) AND delta isn't exactly 0 — neither case carries
                  useful directional signal. Subtext stays as the
                  portfolio-context anchor when no trend renders. */}
              {dashboardMetrics.total_clicks_28d_delta_percent !== null &&
              dashboardMetrics.total_clicks_28d_delta_percent !== 0 ? (
                <p
                  className={cn(
                    'flex items-center gap-1 text-xs font-medium',
                    dashboardMetrics.total_clicks_28d_delta_percent > 0
                      ? 'text-success-strong'
                      : 'text-destructive-strong',
                  )}
                  aria-label={`${dashboardMetrics.total_clicks_28d_delta_percent > 0 ? 'Up' : 'Down'} ${Math.abs(dashboardMetrics.total_clicks_28d_delta_percent)} percent versus prior 28 days`}
                >
                  {dashboardMetrics.total_clicks_28d_delta_percent > 0 ? (
                    <TrendingUp className="size-3" aria-hidden="true" />
                  ) : (
                    <TrendingDown className="size-3" aria-hidden="true" />
                  )}
                  <span className="font-data tabular-nums">
                    {dashboardMetrics.total_clicks_28d_delta_percent > 0 ? '+' : ''}
                    {dashboardMetrics.total_clicks_28d_delta_percent.toFixed(1)}%
                  </span>
                  <span className="text-muted-foreground font-normal">
                    vs prior 28d{siteCount > 1 ? ' · all sites' : ''}
                  </span>
                </p>
              ) : (
                <p className="text-xs text-muted-foreground">Across all sites</p>
              )}
              {/* DASH-ROI-REVENUE: All-pages context — makes clear this is site-wide
                  GSC traffic, not tool-attributed recovery. Prevents this cell from
                  out-shouting the RecoveryHero which tracks recommendation-attributed lift. */}
              <p
                className="text-[10px] text-muted-foreground/60 mt-auto"
                data-testid="gsc-metrics-sitwide-context"
                aria-label="All pages · site-wide GSC traffic, not recommendation-attributed recovery"
              >
                All pages · last 28 days (site-wide GSC traffic)
              </p>
            </>
          ) : !isActivated && firstSite ? (
            <p className="text-xs text-primary mt-auto">
              <Link href={route('onboarding.index', firstSite.id)} className="hover:underline">
                Connect GSC to see clicks →
              </Link>
            </p>
          ) : (
            <div className="font-data text-3xl font-semibold tabular-nums text-muted-foreground/40">
              —
            </div>
          )}
        </div>

        {/* Pending Recommendations */}
        <div className="bg-card p-5 flex flex-col gap-3 min-h-[124px]">
          <div className="flex items-start justify-between gap-2">
            <div className="flex items-center gap-1.5">
              <Eyebrow as="span" className="text-muted-foreground">
                Pending Recommendations
              </Eyebrow>
              <ContextualHelp>
                SEO improvements waiting for your review. Each recommendation suggests a
                specific action to improve traffic.
              </ContextualHelp>
            </div>
            <Sparkles className="size-3.5 text-muted-foreground/60 shrink-0" />
          </div>
          {dashboardMetrics ? (
            <>
              <div className="font-data text-3xl font-semibold tabular-nums tracking-tight text-foreground">
                {dashboardMetrics.pending_recommendations > 0 && firstSite ? (
                  // product name: "Action Queue" (route: opportunity-map.index)
                  <Link
                    href={
                      route('opportunity-map.index', firstSite.id) +
                      '?type=recommendation'
                    }
                    className="hover:text-primary transition-colors"
                  >
                    {dashboardMetrics.pending_recommendations}
                  </Link>
                ) : !isActivated && firstSite ? (
                  <span className="text-sm font-medium text-primary font-sans normal-case tracking-normal">
                    <Link href={route('analyze.index', firstSite.id)} className="hover:underline">
                      Run analysis to get recommendations →
                    </Link>
                  </span>
                ) : (
                  dashboardMetrics.pending_recommendations
                )}
              </div>
              <p className="text-xs text-muted-foreground">Awaiting review</p>
            </>
          ) : (
            <div className="font-data text-3xl font-semibold tabular-nums text-muted-foreground/40">
              —
            </div>
          )}
        </div>

        {/* Drafts Generated */}
        <div className="bg-card p-5 flex flex-col gap-3 min-h-[124px]">
          <div className="flex items-start justify-between gap-2">
            <Eyebrow as="span" className="text-muted-foreground">
              Drafts Generated
            </Eyebrow>
            <FileText className="size-3.5 text-muted-foreground/60 shrink-0" />
          </div>
          {dashboardMetrics ? (
            <>
              <div className="font-data text-3xl font-semibold tabular-nums tracking-tight text-foreground">
                {dashboardMetrics.drafts_generated_month > 0 || isActivated ? (
                  dashboardMetrics.drafts_generated_month
                ) : firstSite ? (
                  <span className="text-sm font-medium text-primary font-sans normal-case tracking-normal">
                    <Link href={route('settings.ai')} className="hover:underline">
                      Add OpenAI key to generate drafts →
                    </Link>
                  </span>
                ) : (
                  dashboardMetrics.drafts_generated_month
                )}
              </div>
              <p className="text-xs text-muted-foreground">This month</p>
            </>
          ) : (
            <div className="font-data text-3xl font-semibold tabular-nums text-muted-foreground/40">
              —
            </div>
          )}
        </div>

        {/* Last Analyzed */}
        <div
          className="bg-card p-5 flex flex-col gap-3 min-h-[124px]"
          aria-busy={isDataLoading || undefined}
        >
          <div className="flex items-start justify-between gap-2">
            <Eyebrow as="span" className="text-muted-foreground">
              Last Analyzed
            </Eyebrow>
            {gscSyncing ? (
              <span className="live-dot mt-1" aria-hidden="true" />
            ) : (
              <BarChart3 className="size-3.5 text-muted-foreground/60 shrink-0" />
            )}
          </div>
          {isDataLoading ? (
            /* Shape: one medium number bar + one short subtext bar,
               matching the 2xl relative-time value + xs caption below. */
            <>
              <Skeleton variant="text-line-lg" className="h-7 w-20" aria-label="Loading last analyzed" />
              <Skeleton variant="text-line" className="h-3 w-32" aria-busy={false} role="presentation" aria-label={undefined} />
            </>
          ) : dashboardMetrics?.latest_analysis_at ? (
            <>
              <div className="font-data text-2xl font-semibold tabular-nums tracking-tight text-foreground">
                {formatRelativeTime(dashboardMetrics.latest_analysis_at)}
              </div>
              <p className="text-xs text-muted-foreground">Most recent analysis</p>
            </>
          ) : (
            <>
              <div className="text-sm font-medium text-muted-foreground">No analysis yet</div>
              <p className="text-xs text-muted-foreground/80">
                {firstSite ? (
                  <Link
                    href={route('analyze.index', firstSite.id)}
                    className="text-primary hover:underline"
                  >
                    Run your first analysis →
                  </Link>
                ) : (
                  'Add a site to get started'
                )}
              </p>
            </>
          )}
        </div>
      </div>
    </section>
  );
}
