import { Link } from '@inertiajs/react';
import {
    ArrowDownRight,
    ArrowUpRight,
    Activity,
    AlertTriangle,
    CalendarDays,
    Minus,
    RefreshCw,
    TrendingDown,
    TrendingUp,
    ShieldCheck,
    Target,
} from 'lucide-react';
import { FinancialAdvisorCard } from '@/components/growth-score/financial-advisor-card';
import {
    GrowthScoreCharts,
    GrowthScoreRadial,
    GrowthScoreSparkline,
} from '@/components/growth-score/growth-score-charts';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { GRADE_LABELS, GRADE_STYLES, isGrowthGrade } from '@/lib/growth-grade';
import { cn } from '@/lib/utils';
import { refresh as refreshGrowthScore } from '@/routes/growth-score';
import type {
    GrowthAnalysis,
    GrowthTransition,
    SavedAdvisorAdvice,
} from '@/types/growth-score';

type Props = {
    analysis: GrowthAnalysis;
    currency?: string;
    savedAdvice?: SavedAdvisorAdvice | null;
    externalCompany?: {
        id: string;
        accountType: string;
        name: string;
    };
};

function money(value: number, currency = 'USD'): string {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency,
        maximumFractionDigits: 0,
    }).format(value);
}

function percent(value: number | null): string {
    if (value === null) {
        return '—';
    }

    const formatted = new Intl.NumberFormat('en-US', {
        maximumFractionDigits: 1,
        signDisplay: 'exceptZero',
    }).format(value);

    return `${formatted}%`;
}

function score(value: number | null): string {
    if (value === null) {
        return '—';
    }

    return `${new Intl.NumberFormat('en-US', {
        maximumFractionDigits: 1,
    }).format(value)} / 100`;
}

function trendLabel(trend: string): string {
    return trend.replaceAll('_', ' ');
}

function flagLabel(flag: string): string {
    return flag.replaceAll('_', ' ');
}

function flagVariant(
    flag: string,
): 'default' | 'secondary' | 'destructive' | 'outline' {
    if (flag === 'loss_to_profit') {
        return 'default';
    }

    if (flag === 'profit_to_loss' || flag === 'gap') {
        return 'destructive';
    }

    return 'outline';
}

function TransitionFlags({ transition }: { transition: GrowthTransition }) {
    if (transition.flags.length === 0) {
        return <span className="text-muted-foreground">Scored</span>;
    }

    return (
        <div className="flex flex-wrap gap-1">
            {transition.flags.map((flag) => (
                <Badge key={flag} variant={flagVariant(flag)}>
                    {flagLabel(flag)}
                </Badge>
            ))}
        </div>
    );
}

function ScoreCompositionRow({
    label,
    value,
    fallback,
    weight,
}: {
    label: string;
    value: number | null;
    fallback: string;
    weight: string;
}) {
    const isPositive = value !== null && value > 0;
    const isNegative = value !== null && value < 0;
    const Icon = isPositive
        ? ArrowUpRight
        : isNegative
          ? ArrowDownRight
          : Minus;
    const status = isPositive
        ? 'Growing'
        : isNegative
          ? 'Declining'
          : 'Needs context';
    const barWidth =
        value === null ? 0 : Math.min(Math.max(Math.abs(value), 8), 100);

    return (
        <div className="rounded-xl border bg-card/80 p-3">
            <div className="flex items-center justify-between gap-3">
                <div className="flex min-w-0 items-center gap-2">
                    <span
                        className={cn(
                            'flex size-7 shrink-0 items-center justify-center rounded-lg',
                            isPositive
                                ? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
                                : isNegative
                                  ? 'bg-red-500/15 text-red-600 dark:text-red-400'
                                  : 'bg-muted text-muted-foreground',
                        )}
                    >
                        <Icon className="size-4" />
                    </span>
                    <div className="min-w-0">
                        <p className="truncate text-sm font-medium">{label}</p>
                        <p className="text-[11px] text-muted-foreground">
                            {weight} of score
                        </p>
                    </div>
                </div>
                <div className="shrink-0 text-right">
                    <p
                        className={cn(
                            'text-sm font-semibold',
                            isPositive
                                ? 'text-emerald-600 dark:text-emerald-400'
                                : isNegative
                                  ? 'text-red-600 dark:text-red-400'
                                  : 'text-muted-foreground',
                        )}
                    >
                        {value === null ? fallback : percent(value)}
                    </p>
                    <p className="text-[11px] text-muted-foreground">
                        {status}
                    </p>
                </div>
            </div>
            <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-muted">
                <div
                    className={cn(
                        'h-full rounded-full transition-all',
                        isPositive
                            ? 'bg-emerald-500'
                            : isNegative
                              ? 'bg-red-500'
                              : 'bg-muted-foreground/40',
                    )}
                    style={{ width: `${barWidth}%` }}
                />
            </div>
        </div>
    );
}

function trendPresentation(trend: string): {
    icon: typeof TrendingUp;
    className: string;
    summary: string;
} {
    if (trend === 'improving') {
        return {
            icon: TrendingUp,
            className:
                'border-emerald-500/40 bg-emerald-500/15 text-emerald-700 dark:text-emerald-400',
            summary:
                'The overall 0–100 score sits above 55, which we classify as improving.',
        };
    }

    if (trend === 'declining') {
        return {
            icon: TrendingDown,
            className:
                'border-red-500/40 bg-red-500/15 text-red-700 dark:text-red-400',
            summary:
                'The overall 0–100 score sits below 45, which we classify as declining.',
        };
    }

    if (trend === 'stable') {
        return {
            icon: Minus,
            className:
                'border-amber-500/40 bg-amber-500/15 text-amber-800 dark:text-amber-400',
            summary:
                'The overall 0–100 score is between 45 and 55, which we classify as stable.',
        };
    }

    return {
        icon: Minus,
        className: 'border-border bg-muted text-muted-foreground',
        summary:
            'Not enough comparable years to classify a trend. Adjacent years without gaps are required.',
    };
}

function TrendOutlook({
    analysis,
    scoredTransitions,
}: {
    analysis: GrowthAnalysis;
    scoredTransitions: GrowthTransition[];
}) {
    const latestScored =
        scoredTransitions[scoredTransitions.length - 1] ?? null;
    const previousScored =
        scoredTransitions[scoredTransitions.length - 2] ?? null;
    const scoreDelta =
        latestScored && previousScored
            ? (latestScored.growth_score ?? 0) -
              (previousScored.growth_score ?? 0)
            : null;
    const momentumIcon =
        scoreDelta === null || Math.abs(scoreDelta) < 1
            ? Minus
            : scoreDelta > 0
              ? TrendingUp
              : TrendingDown;
    const MomentumIcon = momentumIcon;
    const momentumLabel =
        scoreDelta === null
            ? latestScored
                ? 'Baseline established'
                : 'Awaiting scored history'
            : Math.abs(scoreDelta) < 1
              ? 'Momentum stable'
              : scoreDelta > 0
                ? 'Momentum improving'
                : 'Momentum weakening';
    const momentumClass =
        scoreDelta === null || Math.abs(scoreDelta) < 1
            ? 'text-muted-foreground'
            : scoreDelta > 0
              ? 'text-emerald-600 dark:text-emerald-400'
              : 'text-red-600 dark:text-red-400';
    const currentScore = analysis.growth_score;
    const milestoneLabel =
        currentScore === null
            ? 'Need scored history'
            : currentScore > 55
              ? 'Above improving threshold'
              : currentScore >= 45
                ? `${(55 - currentScore).toFixed(1)} points to improving`
                : `${(45 - currentScore).toFixed(1)} points to stable`;
    const coverageNeedsReview =
        analysis.data_quality.has_sign_flips ||
        analysis.data_quality.missing_years.length > 0;
    const coverageLabel = coverageNeedsReview
        ? 'Review data quality'
        : analysis.metrics.scored_transition_count >= 2
          ? 'Strong signal'
          : 'Limited history';
    const CoverageIcon = coverageNeedsReview ? AlertTriangle : ShieldCheck;
    const riskMessage = analysis.data_quality.has_sign_flips
        ? 'Profit / loss reversal needs review before comparing momentum.'
        : analysis.data_quality.missing_years.length > 0
          ? `${analysis.data_quality.missing_years.length} missing year${analysis.data_quality.missing_years.length === 1 ? '' : 's'} affect comparability.`
          : 'No critical data quality flags detected.';

    return (
        <div className="mt-auto space-y-3 border-t pt-4">
            <div className="flex items-center justify-between gap-3">
                <div>
                    <p className="text-sm font-semibold">Trend outlook</p>
                    <p className="text-xs text-muted-foreground">
                        Momentum, milestone, and signal quality
                    </p>
                </div>
                {latestScored && (
                    <Badge variant="secondary" className="gap-1">
                        <CalendarDays className="size-3.5" />
                        {latestScored.from_year} → {latestScored.to_year}
                    </Badge>
                )}
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
                <div className="rounded-xl border bg-card/80 p-3">
                    <div className="flex items-center gap-2">
                        <MomentumIcon className={cn('size-4', momentumClass)} />
                        <p className="text-xs font-medium text-muted-foreground">
                            Momentum signal
                        </p>
                    </div>
                    <p
                        className={cn(
                            'mt-2 text-sm font-semibold',
                            momentumClass,
                        )}
                    >
                        {momentumLabel}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">
                        {scoreDelta === null
                            ? 'A second scored period will establish direction.'
                            : `${scoreDelta >= 0 ? '+' : ''}${scoreDelta.toFixed(1)} points vs previous scored period`}
                    </p>
                </div>
                <div className="rounded-xl border bg-card/80 p-3">
                    <div className="flex items-center gap-2">
                        <Target className="size-4 text-primary" />
                        <p className="text-xs font-medium text-muted-foreground">
                            Next milestone
                        </p>
                    </div>
                    <p className="mt-2 text-sm font-semibold">
                        {milestoneLabel}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">
                        Improving starts above 55; stable starts at 45.
                    </p>
                </div>
            </div>

            <div className="space-y-2 rounded-xl border bg-muted/30 p-3">
                <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-2">
                        <CoverageIcon
                            className={cn(
                                'size-4',
                                coverageNeedsReview
                                    ? 'text-amber-600 dark:text-amber-400'
                                    : 'text-emerald-600 dark:text-emerald-400',
                            )}
                        />
                        <span className="text-xs font-semibold">
                            Signal coverage
                        </span>
                    </div>
                    <Badge variant="outline">{coverageLabel}</Badge>
                </div>
                <p className="text-xs text-muted-foreground">{riskMessage}</p>
                <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
                    <span>
                        {analysis.metrics.coverage_years} coverage year
                        {analysis.metrics.coverage_years === 1 ? '' : 's'}
                    </span>
                    <span>
                        {analysis.metrics.scored_transition_count} scored
                    </span>
                    {analysis.metrics.score_volatility !== null && (
                        <span>
                            ±{analysis.metrics.score_volatility.toFixed(1)}{' '}
                            volatility
                        </span>
                    )}
                </div>
            </div>
        </div>
    );
}

export function GrowthScoreReport({
    analysis,
    currency = 'USD',
    savedAdvice,
    externalCompany,
}: Props) {
    const latestTransition =
        analysis.transitions.length > 0
            ? analysis.transitions[analysis.transitions.length - 1]
            : null;
    const scoredTransitions = analysis.transitions.filter(
        (transition) => transition.growth_score !== null,
    );
    const latestScoredTransition =
        scoredTransitions.length > 0
            ? scoredTransitions[scoredTransitions.length - 1]
            : null;
    const trend = trendPresentation(analysis.trend);
    const TrendIcon = trend.icon;
    const grade = isGrowthGrade(analysis.grade) ? analysis.grade : null;
    const yearCountLabel = `${analysis.years.length} year${analysis.years.length === 1 ? '' : 's'}`;
    const yearRange =
        analysis.years.length > 0
            ? `${analysis.years[0].year}–${analysis.years[analysis.years.length - 1].year}`
            : null;
    const scoreColor =
        analysis.trend === 'declining'
            ? 'var(--destructive)'
            : analysis.trend === 'improving'
              ? 'var(--chart-2)'
              : 'var(--chart-1)';
    const bestTransition =
        scoredTransitions.length > 0
            ? scoredTransitions.reduce((best, transition) =>
                  (transition.growth_score ?? 0) > (best.growth_score ?? 0)
                      ? transition
                      : best,
              )
            : null;
    const weakestTransition =
        scoredTransitions.length > 0
            ? scoredTransitions.reduce((weakest, transition) =>
                  (transition.growth_score ?? 0) < (weakest.growth_score ?? 0)
                      ? transition
                      : weakest,
              )
            : null;

    return (
        <div className="flex flex-col gap-6">
            <Card className="overflow-hidden border-primary/20 bg-gradient-to-br from-primary/5 via-card to-card">
                <CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="space-y-1.5">
                        <p className="text-xs font-semibold tracking-widest text-primary uppercase">
                            Financial health dashboard
                        </p>
                        <CardTitle className="text-xl font-bold tracking-tight md:text-2xl">
                            History
                        </CardTitle>
                        <CardDescription className="text-sm">
                            {yearCountLabel}
                            {yearRange ? ` covering ${yearRange}` : ''} of
                            synced financial results.
                        </CardDescription>
                        <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground">
                            <span>
                                Last synced:{' '}
                                {analysis.sync.synced_at
                                    ? new Intl.DateTimeFormat(undefined, {
                                          dateStyle: 'medium',
                                          timeStyle: 'short',
                                      }).format(
                                          new Date(analysis.sync.synced_at),
                                      )
                                    : 'Not yet synced'}
                            </span>
                            {analysis.sync.refreshing && (
                                <span>Refresh in progress.</span>
                            )}
                            {analysis.sync.last_error && (
                                <span className="text-destructive">
                                    Latest refresh failed; showing the last
                                    successful data.
                                </span>
                            )}
                        </div>
                    </div>
                    {externalCompany && (
                        <Button asChild variant="outline">
                            <Link
                                href={refreshGrowthScore(externalCompany.id)}
                                method="post"
                                as="button"
                                data={{
                                    account_type: externalCompany.accountType,
                                    company_name: externalCompany.name,
                                }}
                            >
                                <RefreshCw />
                                Refresh data
                            </Link>
                        </Button>
                    )}
                </CardHeader>
                {analysis.years.length > 0 && (
                    <CardContent>
                        <div className="flex flex-wrap items-center gap-2">
                            <span className="mr-1 text-xs font-medium tracking-wide text-muted-foreground uppercase">
                                Coverage
                            </span>
                            {analysis.years.map((year) => (
                                <Badge
                                    key={year.year}
                                    variant="secondary"
                                    className="px-3 py-1 text-sm"
                                >
                                    {year.year}
                                </Badge>
                            ))}
                        </div>
                    </CardContent>
                )}
            </Card>

            <div className="grid items-stretch gap-4 xl:grid-cols-2">
                <Card className="h-full overflow-hidden border-primary/20 shadow-sm">
                    <CardHeader>
                        <div className="flex items-start justify-between gap-3">
                            <div>
                                <CardTitle className="text-xl font-bold tracking-tight md:text-2xl">
                                    Growth Score
                                </CardTitle>
                                <CardDescription className="mt-1 text-sm">
                                    Weighted across comparable year-to-year
                                    performance.
                                </CardDescription>
                            </div>
                            <Badge variant="outline" className="gap-1.5">
                                <Activity className="size-3.5" />
                                {analysis.metrics.scored_transition_count}{' '}
                                scored
                            </Badge>
                        </div>
                    </CardHeader>
                    <CardContent className="grid flex-1 gap-5 sm:grid-cols-[11rem_minmax(0,1fr)]">
                        <div className="grid min-w-0 items-center gap-6 sm:col-span-2 sm:grid-cols-[11rem_minmax(0,1fr)]">
                            <div className="rounded-2xl border bg-muted/20 p-2">
                                <GrowthScoreRadial
                                    score={analysis.growth_score}
                                    color={scoreColor}
                                />
                            </div>
                            <div className="min-w-0 space-y-5">
                                <div className="flex min-w-0 items-center gap-3">
                                    <div
                                        className={cn(
                                            'flex size-14 shrink-0 items-center justify-center rounded-2xl border',
                                            grade
                                                ? GRADE_STYLES[grade]
                                                : 'border-border bg-muted text-muted-foreground',
                                        )}
                                    >
                                        <span className="text-3xl leading-none font-extrabold">
                                            {grade ?? '—'}
                                        </span>
                                    </div>
                                    <div className="min-w-0">
                                        <p className="truncate text-lg font-semibold">
                                            {grade
                                                ? GRADE_LABELS[grade]
                                                : 'No grade yet'}
                                        </p>
                                        <p className="truncate text-sm text-muted-foreground">
                                            {analysis.growth_score === null
                                                ? 'Add adjacent years to unlock a score.'
                                                : score(analysis.growth_score)}
                                        </p>
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <div className="flex justify-between text-xs text-muted-foreground">
                                        <span>Score weighting</span>
                                        <span>60 / 40</span>
                                    </div>
                                    <div
                                        className="flex h-2 overflow-hidden rounded-full bg-muted"
                                        aria-label="Revenue 60 percent, net income 40 percent"
                                    >
                                        <div className="w-3/5 bg-primary" />
                                        <div className="w-2/5 bg-chart-2" />
                                    </div>
                                    <div className="flex justify-between text-xs text-muted-foreground">
                                        <span>Revenue</span>
                                        <span>Net income</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="space-y-3 border-t pt-4 sm:col-span-2">
                            <div className="flex items-center justify-between gap-3">
                                <div>
                                    <p className="text-sm font-semibold">
                                        Score composition
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                        Latest scored transition
                                    </p>
                                </div>
                                <Badge variant="secondary" className="gap-1">
                                    <CalendarDays className="size-3.5" />
                                    {latestScoredTransition
                                        ? `${latestScoredTransition.from_year} → ${latestScoredTransition.to_year}`
                                        : 'Not available'}
                                </Badge>
                            </div>
                            <div className="grid gap-3 sm:grid-cols-2">
                                <ScoreCompositionRow
                                    label="Revenue momentum"
                                    value={analysis.metrics.revenue_growth_pct}
                                    fallback="No data"
                                    weight="60%"
                                />
                                <ScoreCompositionRow
                                    label="Net income momentum"
                                    value={
                                        analysis.metrics.net_income_growth_pct
                                    }
                                    fallback={
                                        analysis.metrics.net_income_delta !==
                                        null
                                            ? money(
                                                  analysis.metrics
                                                      .net_income_delta,
                                                  currency,
                                              )
                                            : 'No data'
                                    }
                                    weight="40%"
                                />
                            </div>
                        </div>

                        <div className="space-y-2 rounded-xl border bg-muted/30 p-3 sm:col-span-2">
                            <div className="flex items-center justify-between text-xs font-medium">
                                <span>Score interpretation</span>
                                <span className="text-muted-foreground">
                                    0–100 scale
                                </span>
                            </div>
                            <div className="relative pt-1">
                                <div className="flex h-2 overflow-hidden rounded-full">
                                    <div className="w-[45%] bg-red-500/70" />
                                    <div className="w-[10%] bg-amber-500/70" />
                                    <div className="w-[45%] bg-emerald-500/70" />
                                </div>
                                {analysis.growth_score !== null && (
                                    <span
                                        className="absolute top-0 size-4 -translate-x-1/2 rounded-full border-2 border-background bg-foreground shadow-sm"
                                        style={{
                                            left: `${Math.min(
                                                Math.max(
                                                    analysis.growth_score,
                                                    0,
                                                ),
                                                100,
                                            )}%`,
                                        }}
                                        aria-label={`Current score ${analysis.growth_score} out of 100`}
                                    />
                                )}
                            </div>
                            <div className="flex justify-between text-[11px] text-muted-foreground">
                                <span>Declining &lt; 45</span>
                                <span>Stable 45–55</span>
                                <span>Improving &gt; 55</span>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                <Card className="h-full overflow-hidden shadow-sm">
                    <CardHeader>
                        <div className="flex items-start justify-between gap-3">
                            <div>
                                <CardTitle className="text-xl font-bold tracking-tight md:text-2xl">
                                    Trend
                                </CardTitle>
                                <CardDescription className="mt-1 text-sm">
                                    Direction of the overall growth score.
                                </CardDescription>
                            </div>
                            <div
                                className={cn(
                                    'flex size-11 shrink-0 items-center justify-center rounded-xl border',
                                    trend.className,
                                )}
                            >
                                <TrendIcon className="size-5" />
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="flex flex-1 flex-col gap-4">
                        <div className="flex items-end justify-between gap-4">
                            <div>
                                <p className="text-3xl font-bold tracking-tight capitalize md:text-4xl">
                                    {trendLabel(analysis.trend)}
                                </p>
                                <p className="mt-1 max-w-md text-sm text-muted-foreground">
                                    {trend.summary}
                                </p>
                            </div>
                            <span className="hidden shrink-0 text-right text-xs text-muted-foreground sm:block">
                                Latest score
                                <strong className="mt-1 block text-lg text-foreground">
                                    {score(
                                        latestTransition?.growth_score ?? null,
                                    )}
                                </strong>
                            </span>
                        </div>
                        <GrowthScoreSparkline analysis={analysis} />

                        <div className="grid grid-cols-2 gap-3">
                            <div className="rounded-xl border bg-muted/40 px-3 py-2">
                                <p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
                                    Latest revenue
                                </p>
                                <p className="mt-1 text-lg font-semibold">
                                    {percent(
                                        latestTransition?.revenue_growth_pct ??
                                            null,
                                    )}
                                </p>
                            </div>
                            <div className="rounded-xl border bg-muted/40 px-3 py-2">
                                <p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
                                    Latest net income
                                </p>
                                <p className="mt-1 text-lg font-semibold">
                                    {latestTransition?.net_income_growth_pct ===
                                        null &&
                                    latestTransition?.net_income_delta !== null
                                        ? money(
                                              latestTransition.net_income_delta,
                                              currency,
                                          )
                                        : percent(
                                              latestTransition?.net_income_growth_pct ??
                                                  null,
                                          )}
                                </p>
                            </div>
                        </div>

                        <div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
                            <Badge variant="outline">
                                {scoredTransitions.length} scored transition
                                {scoredTransitions.length === 1 ? '' : 's'}
                            </Badge>
                            <Badge variant="outline">Improving &gt; 55</Badge>
                            <Badge variant="outline">Stable 45–55</Badge>
                            <Badge variant="outline">Declining &lt; 45</Badge>
                            {analysis.data_quality.has_sign_flips && (
                                <Badge variant="destructive">
                                    Profit / loss sign flip excluded
                                </Badge>
                            )}
                        </div>
                        <TrendOutlook
                            analysis={analysis}
                            scoredTransitions={scoredTransitions}
                        />
                    </CardContent>
                </Card>
            </div>

            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                {[
                    {
                        label: 'Latest revenue',
                        value:
                            analysis.metrics.latest_revenue === null
                                ? '—'
                                : money(
                                      analysis.metrics.latest_revenue,
                                      currency,
                                  ),
                        detail: percent(analysis.metrics.revenue_growth_pct),
                    },
                    {
                        label: 'Latest net income',
                        value:
                            analysis.metrics.latest_net_income === null
                                ? '—'
                                : money(
                                      analysis.metrics.latest_net_income,
                                      currency,
                                  ),
                        detail: percent(analysis.metrics.net_income_growth_pct),
                    },
                    {
                        label: 'Net margin',
                        value: percent(analysis.metrics.latest_net_margin),
                        detail: 'Latest available year',
                    },
                    {
                        label: 'Score consistency',
                        value:
                            analysis.metrics.score_volatility === null
                                ? '—'
                                : `±${analysis.metrics.score_volatility.toFixed(1)}`,
                        detail:
                            analysis.metrics.score_range === null
                                ? 'Need scored history'
                                : `${analysis.metrics.score_range.toFixed(1)} point range`,
                    },
                ].map((metric) => (
                    <Card key={metric.label} className="shadow-sm">
                        <CardContent className="space-y-2 p-4">
                            <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                                {metric.label}
                            </p>
                            <p className="truncate text-xl font-bold tracking-tight">
                                {metric.value}
                            </p>
                            <p className="text-xs text-muted-foreground">
                                {metric.detail}
                            </p>
                        </CardContent>
                    </Card>
                ))}
            </div>

            <Card className="border-primary/15 bg-primary/[0.03] shadow-sm">
                <CardHeader>
                    <CardTitle className="text-lg">What changed?</CardTitle>
                    <CardDescription>
                        The clearest signals from the available year-to-year
                        transitions.
                    </CardDescription>
                </CardHeader>
                <CardContent className="grid gap-3 md:grid-cols-3">
                    <div className="rounded-xl border bg-card p-4">
                        <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                            Strongest period
                        </p>
                        <p className="mt-2 font-semibold">
                            {bestTransition
                                ? `${bestTransition.from_year} → ${bestTransition.to_year}`
                                : 'Not available'}
                        </p>
                        <p className="mt-1 text-sm text-emerald-600 dark:text-emerald-400">
                            {bestTransition
                                ? score(bestTransition.growth_score)
                                : 'Need scored history'}
                        </p>
                    </div>
                    <div className="rounded-xl border bg-card p-4">
                        <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                            Watch period
                        </p>
                        <p className="mt-2 font-semibold">
                            {weakestTransition
                                ? `${weakestTransition.from_year} → ${weakestTransition.to_year}`
                                : 'Not available'}
                        </p>
                        <p className="mt-1 text-sm text-amber-600 dark:text-amber-400">
                            {weakestTransition
                                ? score(weakestTransition.growth_score)
                                : 'Need scored history'}
                        </p>
                    </div>
                    <div className="rounded-xl border bg-card p-4">
                        <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                            Data quality
                        </p>
                        <p className="mt-2 font-semibold">
                            {analysis.data_quality.missing_years.length === 0
                                ? 'Complete coverage'
                                : `${analysis.data_quality.missing_years.length} year gap`}
                        </p>
                        <p className="mt-1 text-sm text-muted-foreground">
                            {analysis.data_quality.has_sign_flips
                                ? 'Sign flip requires context'
                                : `${analysis.metrics.coverage_years} years synced`}
                        </p>
                    </div>
                </CardContent>
            </Card>

            <FinancialAdvisorCard
                analysis={analysis}
                externalCompany={externalCompany}
                savedAdvice={savedAdvice}
            />

            <GrowthScoreCharts analysis={analysis} currency={currency} />

            {analysis.data_quality.missing_years.length > 0 && (
                <p className="text-sm text-muted-foreground">
                    Missing financial years:{' '}
                    {analysis.data_quality.missing_years.join(', ')}. Those gaps
                    are excluded from the overall score.
                </p>
            )}

            <Card>
                <CardHeader>
                    <CardTitle>Year-by-year results</CardTitle>
                    <CardDescription>
                        Revenue and net income from live accounting data.
                    </CardDescription>
                </CardHeader>
                <CardContent className="overflow-x-auto">
                    <table className="w-full min-w-[32rem] text-left text-sm">
                        <thead>
                            <tr className="border-b text-muted-foreground">
                                <th className="py-2 pr-4 font-medium">Year</th>
                                <th className="py-2 pr-4 font-medium">
                                    Revenue
                                </th>
                                <th className="py-2 font-medium">Net income</th>
                            </tr>
                        </thead>
                        <tbody>
                            {analysis.years.map((year) => (
                                <tr
                                    key={year.year}
                                    className="border-b last:border-0"
                                >
                                    <td className="py-2 pr-4">{year.year}</td>
                                    <td className="py-2 pr-4">
                                        {money(year.revenue, currency)}
                                    </td>
                                    <td className="py-2">
                                        {money(year.net_income, currency)}
                                    </td>
                                </tr>
                            ))}
                            {analysis.years.length === 0 && (
                                <tr>
                                    <td
                                        colSpan={3}
                                        className="py-6 text-muted-foreground"
                                    >
                                        No historical P&amp;L data was returned.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Year-to-year transitions</CardTitle>
                    <CardDescription>
                        Growth is calculated for every consecutive pair, not
                        only the oldest vs newest year.
                    </CardDescription>
                </CardHeader>
                <CardContent className="overflow-x-auto">
                    <table className="w-full min-w-[48rem] text-left text-sm">
                        <thead>
                            <tr className="border-b text-muted-foreground">
                                <th className="py-2 pr-4 font-medium">
                                    Period
                                </th>
                                <th className="py-2 pr-4 font-medium">
                                    Revenue growth
                                </th>
                                <th className="py-2 pr-4 font-medium">
                                    Net income growth
                                </th>
                                <th className="py-2 pr-4 font-medium">
                                    Transition score
                                </th>
                                <th className="py-2 font-medium">Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            {analysis.transitions.map((transition) => (
                                <tr
                                    key={`${transition.from_year}-${transition.to_year}`}
                                    className="border-b last:border-0"
                                >
                                    <td className="py-2 pr-4">
                                        {transition.from_year} →{' '}
                                        {transition.to_year}
                                    </td>
                                    <td className="py-2 pr-4">
                                        {percent(transition.revenue_growth_pct)}
                                    </td>
                                    <td className="py-2 pr-4">
                                        {transition.net_income_growth_pct ===
                                            null &&
                                        transition.net_income_delta !== null
                                            ? money(
                                                  transition.net_income_delta,
                                                  currency,
                                              )
                                            : percent(
                                                  transition.net_income_growth_pct,
                                              )}
                                    </td>
                                    <td className="py-2 pr-4">
                                        {score(transition.growth_score)}
                                    </td>
                                    <td className="py-2">
                                        <TransitionFlags
                                            transition={transition}
                                        />
                                    </td>
                                </tr>
                            ))}
                            {analysis.transitions.length === 0 && (
                                <tr>
                                    <td
                                        colSpan={5}
                                        className="py-6 text-muted-foreground"
                                    >
                                        Not enough adjacent years to calculate
                                        growth.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </CardContent>
            </Card>
        </div>
    );
}
