import { ArrowRight, Sparkles, TrendingDown } from 'lucide-react';

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

import { truncateUrl } from '@/lib/format';

/**
 * BiggestOpportunityHero — the dashboard's single most-important next action.
 *
 * For the activated-but-not-deep cohort (analyzed ≥1 site, ≥1 declining page,
 * not yet a power user), this hero surfaces ONE concrete opportunity — the page
 * that lost the most traffic — with a one-click path to generating its rewrite.
 * It renders ABOVE the metrics grid so the user lands on "here's the page to fix
 * and the button to fix it" rather than scanning count tiles (P2-10).
 *
 * When the user has several decayed pages AND has already produced ≥1 draft,
 * it additionally offers a bulk "rewrite your top N declining pages" action so
 * the solo bulk-rewriter persona can act at scale instead of one page at a time
 * (P2-11).
 *
 * Gating is the caller's responsibility (Dashboard renders this only for the
 * right cohort with ≥1 declining page). The component has no async state of its
 * own — navigation is a fire-and-forget Inertia <Link> (gotcha #11). The CTAs
 * deep-link into the Action Queue (opportunity-map) filtered to draftable
 * recommendations, which is the existing one-click / bulk draft-generation
 * surface — no new backend endpoint is introduced.
 *
 * Persona note (v1 = solo bulk-rewriter): copy favours the concrete action
 * ("Generate the rewrite") over results-claim vocabulary, which is reserved for
 * post-result surfaces.
 */
export interface DecliningPage {
  id: string | number;
  page_url: string;
  delta_percent: number;
  delta_absolute: number;
}

interface BiggestOpportunityHeroProps {
  /** Opaque site public id used for route building. */
  siteId: string | number;
  /** Declining pages, highest-impact first (dashboard already sorts by |delta|). */
  decliningPages: DecliningPage[];
  /** True once the user has generated ≥1 AI rewrite draft (drives the bulk CTA). */
  hasGeneratedDraft: boolean;
  /** Minimum decayed-page count before the bulk CTA appears. */
  bulkThreshold?: number;
}

export default function BiggestOpportunityHero({
  siteId,
  decliningPages,
  hasGeneratedDraft,
  bulkThreshold = 3,
}: BiggestOpportunityHeroProps) {
  const top = decliningPages[0];

  // Defensive: the caller gates on a non-empty list, but never render an empty hero.
  if (!top) {
    return null;
  }

  // The Action Queue filtered to draftable recommendations — the existing
  // one-click rewrite-generation surface.
  const actionQueueHref =
    route('opportunity-map.index', siteId) + '?type=recommendation&draftable=1';

  // Guard against a non-finite delta (e.g. a zero-baseline page) so the hero
  // never renders "NaN%" — fall back to a generic phrasing without a number.
  const lossPct = Number.isFinite(top.delta_percent)
    ? Math.abs(top.delta_percent).toFixed(1)
    : null;

  // P2-11: bulk CTA only once the user has enough decayed pages AND has proven
  // the single-rewrite flow at least once (≥1 successful draft).
  const showBulkCta = hasGeneratedDraft && decliningPages.length >= bulkThreshold;

  return (
    <section
      aria-labelledby="biggest-opportunity-heading"
      className="mb-10 rounded-2xl border border-primary/30 bg-primary/5 p-5 sm:p-6"
    >
      <div className="flex items-start gap-3">
        <TrendingDown
          className="mt-0.5 size-5 shrink-0 text-destructive-strong"
          aria-hidden="true"
        />
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-primary">
            Biggest opportunity
          </p>
          <h2
            id="biggest-opportunity-heading"
            className="mt-1 text-lg font-semibold text-foreground"
          >
            {lossPct !== null ? (
              <>
                Your top declining page lost{' '}
                <span className="text-destructive-strong tabular-nums">{lossPct}%</span> of its
                clicks
              </>
            ) : (
              'Your top declining page is losing clicks'
            )}
          </h2>

          <p className="mt-1.5 flex flex-wrap items-baseline gap-x-2 text-sm text-muted-foreground">
            <span className="font-data truncate text-foreground" title={top.page_url}>
              {truncateUrl(top.page_url)}
            </span>
          </p>

          <p className="mt-1.5 text-sm text-muted-foreground">
            Generate an AI rewrite to recover the lost rankings — it&apos;s the highest-impact fix
            on your site right now.
          </p>

          <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center">
            <Link
              href={actionQueueHref}
              className="inline-flex items-center justify-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
            >
              <Sparkles className="size-4" aria-hidden="true" />
              Generate the rewrite
              <ArrowRight className="size-4" aria-hidden="true" />
            </Link>

            {showBulkCta && (
              <Link
                href={actionQueueHref}
                className="inline-flex items-center justify-center gap-1.5 rounded-md border border-primary/40 bg-background px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Rewrite your top {decliningPages.length} declining pages
                <ArrowRight className="size-4" aria-hidden="true" />
              </Link>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
