/**
 * ContentPipelinePanel — "Content Pipeline" section of the Dashboard.
 *
 * Extracted from Dashboard.tsx (DEBT-005) — behavior-preserving refactor only.
 * Includes: RecommendationFunnel + content intelligence cell-grid.
 *
 * Accepts `contentIntelligence` directly and builds the intelligence card array
 * internally so Dashboard.tsx doesn't need to import the Lucide icon set.
 */
import { GitMerge, Layers, RefreshCw, Target } from 'lucide-react';

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

import RecommendationFunnel from '@/Components/Dashboard/RecommendationFunnel';
import { Eyebrow } from '@/Components/ui/eyebrow';
import { Skeleton } from '@/Components/ui/skeleton';
import { cn } from '@/lib/utils';

export interface FunnelMetrics {
  generated: number;
  approved: number;
  applied: number;
}

export interface ContentIntelligence {
  site_id: string;
  site_name: string;
  cannibalization_count: number;
  topic_cluster_count: number;
  freshness_count: number;
  keyword_opportunity_count: number;
}

export interface ContentPipelinePanelProps {
  funnelMetrics: FunnelMetrics;
  firstSite: { id: string; name: string; domain: string } | null;
  contentIntelligence: ContentIntelligence | null | undefined;
  isDataLoading: boolean;
  showBiggestOpportunity: boolean;
  siteCount: number;
}

export function ContentPipelinePanel({
  funnelMetrics,
  firstSite,
  contentIntelligence,
  isDataLoading,
  showBiggestOpportunity,
  siteCount,
}: ContentPipelinePanelProps) {
  const intelligenceCards = contentIntelligence
    ? [
        {
          key: 'cannibalization',
          label: 'Cannibalization',
          description: 'Competing pages',
          count: contentIntelligence.cannibalization_count,
          icon: GitMerge,
          href: firstSite ? route('cannibalization.index', firstSite.id) : '#',
        },
        {
          key: 'clusters',
          label: 'Topic Clusters',
          description: 'Grouped by topic',
          count: contentIntelligence.topic_cluster_count,
          icon: Layers,
          href: firstSite ? route('topic-clusters.index', firstSite.id) : '#',
        },
        {
          key: 'freshness',
          label: 'Freshness',
          description: 'Need a refresh',
          count: contentIntelligence.freshness_count,
          icon: RefreshCw,
          href: firstSite ? route('freshness.index', firstSite.id) : '#',
        },
        {
          key: 'opportunities',
          label: 'Keyword Opps.',
          description: 'Ready to climb',
          count: contentIntelligence.keyword_opportunity_count,
          icon: Target,
          href: firstSite ? route('opportunity-map.index', firstSite.id) : '#', // product name: "Action Queue"
        },
      ]
    : [];
  return (
    <section
      aria-labelledby="content-pipeline-heading"
      className={cn('mb-12', showBiggestOpportunity && 'opacity-90')}
    >
      <h2 id="content-pipeline-heading" className="editorial-rule left mb-4">
        Content Pipeline
      </h2>
      {/* P2-10: when the biggest-opportunity hero is leading the page, the
          content-intelligence counts are secondary context, not the primary
          call to action — frame them as such so they don't compete. */}
      {showBiggestOpportunity && intelligenceCards.length > 0 && (
        <p className="mb-3 text-[11px] text-muted-foreground">
          Secondary signals — your biggest opportunity is at the top of the page.
        </p>
      )}

      <div className="mb-6">
        <RecommendationFunnel metrics={funnelMetrics} siteId={firstSite?.id} />
      </div>

      {/* Scope hint: the intelligence counts below are first-site only,
          while the funnel above aggregates across all sites. Render this
          only on multi-site accounts where the asymmetry is actually
          user-visible. Single-site users would just see noise. */}
      {firstSite && intelligenceCards.length > 0 && siteCount > 1 && contentIntelligence && (
        <p className="mb-2 text-[11px] text-muted-foreground">
          Showing signals for{' '}
          <span className="font-medium text-foreground">{contentIntelligence.site_name}</span>.
          Switch sites in the header to see others.
        </p>
      )}

      {/* UI-012: show skeleton when syncing and no intelligence data yet */}
      {firstSite && isDataLoading && intelligenceCards.length === 0 && (
        <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border bg-border md:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="bg-card p-5">
              <Skeleton className="mb-2 size-4" />
              <Skeleton className="h-8 w-16" aria-label="Loading intelligence count" />
              <Skeleton className="mt-1 h-3 w-24" />
            </div>
          ))}
        </div>
      )}
      {firstSite && intelligenceCards.length > 0 && (
        <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border bg-border md:grid-cols-4">
          {intelligenceCards.map(({ key, label, description, count, icon: Icon, href }) => {
            const hasSignal = count > 0;
            return (
              <Link
                key={key}
                href={href}
                className={cn(
                  'group flex flex-col justify-between gap-3 bg-card p-5 transition-colors',
                  hasSignal ? 'hover:bg-accent/40' : 'hover:bg-muted/40',
                )}
                aria-label={`View ${label} details`}
              >
                <div className="flex items-start justify-between gap-2">
                  <Icon
                    className={cn(
                      'size-4',
                      hasSignal ? 'text-primary' : 'text-muted-foreground/60',
                    )}
                    aria-hidden="true"
                  />
                  <Eyebrow as="span" className="text-primary opacity-0 transition-opacity group-hover:opacity-100">
                    View →
                  </Eyebrow>
                </div>
                <div>
                  <div
                    className={cn(
                      'font-data font-semibold tabular-nums tracking-tight',
                      // P2-10: smaller numerals when demoted beneath the hero.
                      showBiggestOpportunity ? 'text-2xl' : 'text-3xl',
                      hasSignal ? 'text-foreground' : 'text-muted-foreground/40',
                    )}
                  >
                    {count}
                  </div>
                  <p className="text-xs font-medium mt-1.5">{label}</p>
                  <p className="text-[11px] text-muted-foreground mt-0.5">{description}</p>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </section>
  );
}
