import React from "react";
import NotebookTemplate from "@/components/NotebookTemplate";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  ComposedChart,
  Line,
  LineChart,
  XAxis,
  YAxis,
} from "recharts";

import story from "@/data/usa_energy/energy_story.json";
import regionalStory from "@/data/usa_energy/regional_data.json";

type AnnualRow = {
  year: number;
  generation_twh: number;
  retail_sales_twh: number;
  losses_twh: number;
  loss_pct: number;
};

type DemandSectorRow = {
  year: number;
  residential_twh: number;
  commercial_twh: number;
  industrial_twh: number;
  transportation_twh: number;
  total_twh: number;
};

type GenerationKeyRow = {
  year: number;
  coal_twh: number;
  natural_gas_twh: number;
  nuclear_twh: number;
  renewables_twh: number;
  other_twh: number;
  total_twh: number;
};

type GenerationShareRow = {
  year: number;
  coal_pct: number;
  natural_gas_pct: number;
  nuclear_pct: number;
  renewables_pct: number;
};

type RenewablesRow = {
  year: number;
  wind_twh: number;
  solar_twh: number;
  hydro_twh: number;
  other_renewables_twh: number;
  renewables_twh: number;
};

// Regional data types
type RegionalTwhRow = {
  region: string;
  years: number[];
  coal: number[];
  natural_gas: number[];
  nuclear: number[];
  renewables: number[];
};

type RegionalSharesRow = {
  region: string;
  years: number[];
  coal_pct: number[];
  natural_gas_pct: number[];
  nuclear_pct: number[];
  renewables_pct: number[];
};

type RegionalSummary = {
  [key: string]: {
    first_year: number;
    last_year: number;
    total_change_pct: number;
    coal_share_change: number;
    natural_gas_share_change: number;
    renewables_share_change: number;
  };
};

// Transform regional data into yearly rows for charting
interface RegionalYearlyRow {
  year: number;
  region: string;
  coal_twh: number;
  natural_gas_twh: number;
  nuclear_twh: number;
  renewables_twh: number;
  total_twh: number;
  coal_pct: number;
  natural_gas_pct: number;
  nuclear_pct: number;
  renewables_pct: number;
}

const annual = story.annual as AnnualRow[];
const demandBySector = story.demand_by_sector as DemandSectorRow[];
const generationKey = story.generation_key_sources as GenerationKeyRow[];
const generationShares = story.generation_shares as GenerationShareRow[];
const renewablesBreakdown = story.renewables_breakdown as RenewablesRow[];

const regionalTwh = regionalStory.generation_twh as RegionalTwhRow[];
const regionalShares = regionalStory.generation_shares as RegionalSharesRow[];
const regionalSummary = regionalStory.summary as RegionalSummary;

// Transform regional data into flat yearly rows for small multiples
const regionalYearlyData: RegionalYearlyRow[] = regionalTwh.flatMap((region) => {
  const shares = regionalShares.find((r) => r.region === region.region);
  return region.years.map((year, idx) => ({
    year,
    region: region.region,
    coal_twh: region.coal[idx],
    natural_gas_twh: region.natural_gas[idx],
    nuclear_twh: region.nuclear[idx],
    renewables_twh: region.renewables[idx],
    total_twh: region.coal[idx] + region.natural_gas[idx] + region.nuclear[idx] + region.renewables[idx],
    coal_pct: shares?.coal_pct[idx] || 0,
    natural_gas_pct: shares?.natural_gas_pct[idx] || 0,
    nuclear_pct: shares?.nuclear_pct[idx] || 0,
    renewables_pct: shares?.renewables_pct[idx] || 0,
  }));
});

// Create a combined dataset for the renewables share comparison chart
interface RenewablesShareComparisonRow {
  year: number;
  CAISO_renewables_pct: number;
  ERCOT_renewables_pct: number;
  PJM_renewables_pct: number;
  NYISO_renewables_pct: number;
}

const renewablesShareComparison: RenewablesShareComparisonRow[] = regionalShares[0].years.map((year, idx) => ({
  year,
  CAISO_renewables_pct: regionalShares.find((r) => r.region === "CAISO")?.renewables_pct[idx] || 0,
  ERCOT_renewables_pct: regionalShares.find((r) => r.region === "ERCOT")?.renewables_pct[idx] || 0,
  PJM_renewables_pct: regionalShares.find((r) => r.region === "PJM")?.renewables_pct[idx] || 0,
  NYISO_renewables_pct: regionalShares.find((r) => r.region === "NYISO")?.renewables_pct[idx] || 0,
}));

const fmtInt = (v: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(v);

const fmtPct1 = (v: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 }).format(v);

const fmtSigned1 = (v: number) =>
  `${v >= 0 ? "+" : ""}${new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 1,
  }).format(v)}`;

const toplineConfig = {
  generation_twh: { label: "Net generation (TWh)", color: "var(--chart-1)" },
  retail_sales_twh: { label: "Retail sales (TWh)", color: "var(--chart-2)" },
  losses_twh: { label: "Losses & other (TWh)", color: "var(--chart-3)" },
  loss_pct: { label: "Loss rate (%)", color: "var(--chart-4)" },
} satisfies ChartConfig;

const demandConfig = {
  residential_twh: { label: "Residential", color: "var(--chart-1)" },
  commercial_twh: { label: "Commercial", color: "var(--chart-2)" },
  industrial_twh: { label: "Industrial", color: "var(--chart-3)" },
  transportation_twh: { label: "Transportation", color: "var(--chart-4)" },
} satisfies ChartConfig;

const generationKeyConfig = {
  coal_twh: { label: "Coal", color: "var(--chart-1)" },
  natural_gas_twh: { label: "Natural gas", color: "var(--chart-2)" },
  nuclear_twh: { label: "Nuclear", color: "var(--chart-3)" },
  renewables_twh: { label: "Renewables", color: "var(--chart-4)" },
  other_twh: { label: "Other", color: "var(--chart-5)" },
} satisfies ChartConfig;

const sharesConfig = {
  coal_pct: { label: "Coal", color: "var(--chart-1)" },
  natural_gas_pct: { label: "Natural gas", color: "var(--chart-2)" },
  nuclear_pct: { label: "Nuclear", color: "var(--chart-3)" },
  renewables_pct: { label: "Renewables", color: "var(--chart-4)" },
} satisfies ChartConfig;

const renewablesConfig = {
  wind_twh: { label: "Wind", color: "var(--chart-1)" },
  solar_twh: { label: "Solar", color: "var(--chart-2)" },
  hydro_twh: { label: "Hydro", color: "var(--chart-3)" },
  other_renewables_twh: { label: "Other renewables", color: "var(--chart-4)" },
} satisfies ChartConfig;

const regionalSharesConfig = {
  CAISO_renewables_pct: { label: "CAISO", color: "var(--chart-1)" },
  ERCOT_renewables_pct: { label: "ERCOT", color: "var(--chart-2)" },
  PJM_renewables_pct: { label: "PJM", color: "var(--chart-3)" },
  NYISO_renewables_pct: { label: "NYISO", color: "var(--chart-4)" },
} satisfies ChartConfig;

export default function UsaEnergy() {
  const h = story.headline as {
    first_year: number;
    last_year: number;
    generation_change_pct: number;
    retail_sales_change_pct: number;
    coal_share_pp: number;
    natural_gas_share_pp: number;
    renewables_share_pp: number;
    nuclear_share_pp: number;
    loss_pct_first: number;
    loss_pct_last: number;
  };

  return (
    <NotebookTemplate
      title="US electricity: demand vs supply (2014–2024)"
      subtitle="How consumption compares to generation, and how the supply mix shifted"
      sources="U.S. Energy Information Administration (EIA) Open Data + regional ISO data (ERCOT, PJM, CAISO, NYISO)"
    >
      <section className="space-y-3">
        <p className="text-foreground leading-relaxed">
          This notebook looks at annual US electricity <strong>net generation</strong> versus
          delivered <strong>retail sales</strong> (a proxy for end-use demand), plus how the
          generation mix changed across coal, gas, nuclear, and renewables.
        </p>
      </section>

      <section className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Total demand change</CardDescription>
            <CardTitle>{fmtPct1(h.retail_sales_change_pct)}%</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Retail sales, {h.first_year} → {h.last_year}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Coal share shift</CardDescription>
            <CardTitle>{fmtSigned1(h.coal_share_pp)} pp</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Share of generation, {h.first_year} → {h.last_year}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Renewables share shift</CardDescription>
            <CardTitle>{fmtSigned1(h.renewables_share_pp)} pp</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Share of generation, {h.first_year} → {h.last_year}
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Generation vs. retail sales</CardTitle>
            <CardDescription>
              TWh (annual). The gap is losses & other uses (T&D losses, plant use, accounting).
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={toplineConfig} className="h-[360px] w-full">
              <LineChart data={annual} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => fmtInt(v)}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line
                  dataKey="generation_twh"
                  stroke="var(--color-generation_twh)"
                  strokeWidth={2}
                  dot={false}
                />
                <Line
                  dataKey="retail_sales_twh"
                  stroke="var(--color-retail_sales_twh)"
                  strokeWidth={2}
                  dot={false}
                />
                <Line
                  dataKey="losses_twh"
                  stroke="var(--color-losses_twh)"
                  strokeWidth={2}
                  dot={false}
                />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>The "gap" is pretty stable</CardTitle>
            <CardDescription>
              Loss rate (% of net generation). {fmtPct1(h.loss_pct_first)}% → {fmtPct1(h.loss_pct_last)}%.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={toplineConfig} className="h-[260px] w-full">
              <LineChart data={annual} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => `${fmtPct1(v)}%`}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Line
                  dataKey="loss_pct"
                  stroke="var(--color-loss_pct)"
                  strokeWidth={2}
                  dot={false}
                />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          The gap between generation and retail sales represents <strong>transmission & distribution (T&D) losses</strong>, electricity used at power plants themselves, and accounting differences. At roughly {fmtPct1(h.loss_pct_last)}% of generation, this gap has remained remarkably stable over the decade. That stability matters: it means grid efficiency isn't deteriorating even as the system undergoes massive fuel switching. The losses are essentially a fixed overhead on the system — every terawatt-hour generated requires about {fmtPct1(h.loss_pct_last)}% more to account for T&D and plant use.
        </p>
      </section>

      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Demand is mostly a sector story</CardTitle>
            <CardDescription>
              Retail sales by end-use sector (stacked, TWh). Total grew {fmtPct1(h.retail_sales_change_pct)}% from {h.first_year} to {h.last_year}.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={demandConfig} className="h-[360px] w-full">
              <AreaChart data={demandBySector} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => fmtInt(v)}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Area
                  type="monotone"
                  dataKey="residential_twh"
                  stackId="a"
                  stroke="var(--color-residential_twh)"
                  fill="var(--color-residential_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="commercial_twh"
                  stackId="a"
                  stroke="var(--color-commercial_twh)"
                  fill="var(--color-commercial_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="industrial_twh"
                  stackId="a"
                  stroke="var(--color-industrial_twh)"
                  fill="var(--color-industrial_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="transportation_twh"
                  stackId="a"
                  stroke="var(--color-transportation_twh)"
                  fill="var(--color-transportation_twh)"
                  fillOpacity={0.35}
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          Demand growth is modest — only {fmtPct1(h.retail_sales_change_pct)}% over the decade — but it's not evenly distributed. <strong>Commercial</strong> and <strong>residential</strong> sectors have driven most of the increase, reflecting electrification of buildings, data center growth, and increased air conditioning use. <strong>Industrial</strong> demand has been relatively flat, which is notable given overall economic growth — this suggests efficiency gains and offshoring of energy-intensive manufacturing. <strong>Transportation</strong> remains the smallest sector but is growing fastest as electric vehicles gain market share, though it's still a small fraction of total electricity use.
        </p>
      </section>

      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Supply transition: coal collapses, gas and renewables rise</CardTitle>
            <CardDescription>
              Net generation by key sources (stacked, TWh). Total grew {fmtPct1(h.generation_change_pct)}% from {h.first_year} to {h.last_year}.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={generationKeyConfig} className="h-[360px] w-full">
              <AreaChart data={generationKey} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => fmtInt(v)} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Area
                  type="monotone"
                  dataKey="coal_twh"
                  stackId="a"
                  stroke="var(--color-coal_twh)"
                  fill="var(--color-coal_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="natural_gas_twh"
                  stackId="a"
                  stroke="var(--color-natural_gas_twh)"
                  fill="var(--color-natural_gas_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="nuclear_twh"
                  stackId="a"
                  stroke="var(--color-nuclear_twh)"
                  fill="var(--color-nuclear_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="renewables_twh"
                  stackId="a"
                  stroke="var(--color-renewables_twh)"
                  fill="var(--color-renewables_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="other_twh"
                  stackId="a"
                  stroke="var(--color-other_twh)"
                  fill="var(--color-other_twh)"
                  fillOpacity={0.20}
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          While demand barely budged, the <strong>supply mix transformed</strong>. Coal generation collapsed from {fmtPct1((generationShares.find((s) => s.year === h.first_year)?.coal_pct || 0))}% to {fmtPct1((generationShares.find((s) => s.year === h.last_year)?.coal_pct || 0))}% — a {fmtSigned1(h.coal_share_pp)} percentage point shift driven by EPA regulations, cheap natural gas, and plant retirements. Natural gas filled much of that gap, rising {fmtSigned1(h.natural_gas_share_pp)} percentage points to become the dominant source. But the real story is <strong>renewables</strong>: they grew {fmtSigned1(h.renewables_share_pp)} percentage points, from a modest {fmtPct1((generationShares.find((s) => s.year === h.first_year)?.renewables_pct || 0))}% to {fmtPct1((generationShares.find((s) => s.year === h.last_year)?.renewables_pct || 0))}% of generation. Nuclear held roughly steady, providing a stable baseload that became relatively more important as coal faded.
        </p>
      </section>

      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Shares tell the same story</CardTitle>
            <CardDescription>Percent of total generation.</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={sharesConfig} className="h-[320px] w-full">
              <LineChart data={generationShares} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line dataKey="coal_pct" stroke="var(--color-coal_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="natural_gas_pct" stroke="var(--color-natural_gas_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="nuclear_pct" stroke="var(--color-nuclear_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="renewables_pct" stroke="var(--color-renewables_pct)" strokeWidth={2} dot={false} />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          The share chart makes the transition clearer: coal's decline is nearly linear, while gas and renewables show accelerating growth. By {h.last_year}, natural gas and renewables together accounted for roughly {fmtPct1((generationShares.find((s) => s.year === h.last_year)?.natural_gas_pct || 0) + (generationShares.find((s) => s.year === h.last_year)?.renewables_pct || 0))}% of generation — a dramatic shift from {h.first_year} when fossil fuels (coal + gas) dominated. This isn't just fuel switching; it's a structural change in how the US produces electricity, with implications for grid reliability, emissions, and energy policy.
        </p>
      </section>

      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Within renewables: wind + solar do the heavy lifting</CardTitle>
            <CardDescription>Renewables broken down (stacked, TWh).</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={renewablesConfig} className="h-[360px] w-full">
              <AreaChart data={renewablesBreakdown} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => fmtInt(v)} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Area
                  type="monotone"
                  dataKey="hydro_twh"
                  stackId="a"
                  stroke="var(--color-hydro_twh)"
                  fill="var(--color-hydro_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="wind_twh"
                  stackId="a"
                  stroke="var(--color-wind_twh)"
                  fill="var(--color-wind_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="solar_twh"
                  stackId="a"
                  stroke="var(--color-solar_twh)"
                  fill="var(--color-solar_twh)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="other_renewables_twh"
                  stackId="a"
                  stroke="var(--color-other_renewables_twh)"
                  fill="var(--color-other_renewables_twh)"
                  fillOpacity={0.35}
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          Renewables growth isn't evenly distributed. <strong>Wind</strong> led the early expansion, particularly in the Midwest and Texas where resources are strong. <strong>Solar</strong> started later but accelerated dramatically after 2018, driven by falling costs and utility-scale deployment. <strong>Hydro</strong> provides a stable but limited base — it's geography-constrained and has grown little. <strong>Other renewables</strong> (geothermal, biomass, wood) remain niche. The divergence between wind and solar matters for grid operations: wind is more variable and often peaks at night, while solar follows a predictable daytime pattern that aligns with peak demand.
        </p>
      </section>

      <section className="space-y-6">
        <h2 className="text-2xl font-semibold">Regional patterns differ dramatically</h2>
        <p className="text-muted-foreground">
          The US has distinct electric markets. Each region followed a different path due to local resources, policy, and infrastructure.
        </p>

        <section className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardDescription>CAISO total change</CardDescription>
              <CardTitle>{fmtPct1(regionalSummary.CAISO.total_change_pct)}%</CardTitle>
            </CardHeader>
            <CardContent className="text-sm text-muted-foreground">
              Coal {fmtSigned1(regionalSummary.CAISO.coal_share_change)} pp, Renewables +{fmtPct1(regionalSummary.CAISO.renewables_share_change)} pp
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardDescription>ERCOT total change</CardDescription>
              <CardTitle>{fmtPct1(regionalSummary.ERCOT.total_change_pct)}%</CardTitle>
            </CardHeader>
            <CardContent className="text-sm text-muted-foreground">
              Coal {fmtSigned1(regionalSummary.ERCOT.coal_share_change)} pp, Renewables +{fmtPct1(regionalSummary.ERCOT.renewables_share_change)} pp
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardDescription>PJM total change</CardDescription>
              <CardTitle>{fmtPct1(regionalSummary.PJM.total_change_pct)}%</CardTitle>
            </CardHeader>
            <CardContent className="text-sm text-muted-foreground">
              Coal {fmtSigned1(regionalSummary.PJM.coal_share_change)} pp, Renewables +{fmtPct1(regionalSummary.PJM.renewables_share_change)} pp
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardDescription>NYISO total change</CardDescription>
              <CardTitle>{fmtPct1(regionalSummary.NYISO.total_change_pct)}%</CardTitle>
            </CardHeader>
            <CardContent className="text-sm text-muted-foreground">
              Coal {fmtSigned1(regionalSummary.NYISO.coal_share_change)} pp, Renewables +{fmtPct1(regionalSummary.NYISO.renewables_share_change)} pp
            </CardContent>
          </Card>
        </section>

        <Card>
          <CardHeader>
            <CardTitle>Renewables shares diverge</CardTitle>
            <CardDescription>
              Percent of generation by region. CAISO leads; ERCOT and NYISO accelerated mid-decade.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={regionalSharesConfig} className="h-[360px] w-full">
              <LineChart data={renewablesShareComparison} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line dataKey="CAISO_renewables_pct" stroke="var(--color-CAISO_renewables_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="ERCOT_renewables_pct" stroke="var(--color-ERCOT_renewables_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="PJM_renewables_pct" stroke="var(--color-PJM_renewables_pct)" strokeWidth={2} dot={false} />
                <Line dataKey="NYISO_renewables_pct" stroke="var(--color-NYISO_renewables_pct)" strokeWidth={2} dot={false} />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>

        <section className="space-y-4">
          <h3 className="text-xl font-semibold">Regional generation mix over time</h3>
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">CAISO (California)</CardTitle>
                <CardDescription className="text-xs">Coal eliminated, solar dominates</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={sharesConfig} className="h-[280px] w-full">
                  <AreaChart data={regionalYearlyData.filter((d) => d.region === "CAISO")} margin={{ left: 12, right: 12, top: 8 }}>
                    <CartesianGrid vertical={false} />
                    <XAxis dataKey="year" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="coal_pct"
                      stackId="a"
                      stroke="var(--color-coal_pct)"
                      fill="var(--color-coal_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="natural_gas_pct"
                      stackId="a"
                      stroke="var(--color-natural_gas_pct)"
                      fill="var(--color-natural_gas_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="nuclear_pct"
                      stackId="a"
                      stroke="var(--color-nuclear_pct)"
                      fill="var(--color-nuclear_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="renewables_pct"
                      stackId="a"
                      stroke="var(--color-renewables_pct)"
                      fill="var(--color-renewables_pct)"
                      fillOpacity={0.35}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">ERCOT (Texas)</CardTitle>
                <CardDescription className="text-xs">Wind-dominant, coal declines</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={sharesConfig} className="h-[280px] w-full">
                  <AreaChart data={regionalYearlyData.filter((d) => d.region === "ERCOT")} margin={{ left: 12, right: 12, top: 8 }}>
                    <CartesianGrid vertical={false} />
                    <XAxis dataKey="year" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="coal_pct"
                      stackId="a"
                      stroke="var(--color-coal_pct)"
                      fill="var(--color-coal_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="natural_gas_pct"
                      stackId="a"
                      stroke="var(--color-natural_gas_pct)"
                      fill="var(--color-natural_gas_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="nuclear_pct"
                      stackId="a"
                      stroke="var(--color-nuclear_pct)"
                      fill="var(--color-nuclear_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="renewables_pct"
                      stackId="a"
                      stroke="var(--color-renewables_pct)"
                      fill="var(--color-renewables_pct)"
                      fillOpacity={0.35}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">PJM (Mid-Atlantic + Midwest)</CardTitle>
                <CardDescription className="text-xs">Coal to gas transition</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={sharesConfig} className="h-[280px] w-full">
                  <AreaChart data={regionalYearlyData.filter((d) => d.region === "PJM")} margin={{ left: 12, right: 12, top: 8 }}>
                    <CartesianGrid vertical={false} />
                    <XAxis dataKey="year" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="coal_pct"
                      stackId="a"
                      stroke="var(--color-coal_pct)"
                      fill="var(--color-coal_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="natural_gas_pct"
                      stackId="a"
                      stroke="var(--color-natural_gas_pct)"
                      fill="var(--color-natural_gas_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="nuclear_pct"
                      stackId="a"
                      stroke="var(--color-nuclear_pct)"
                      fill="var(--color-nuclear_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="renewables_pct"
                      stackId="a"
                      stroke="var(--color-renewables_pct)"
                      fill="var(--color-renewables_pct)"
                      fillOpacity={0.35}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">NYISO (New York)</CardTitle>
                <CardDescription className="text-xs">Hydro/nuclear base, renewables grow</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={sharesConfig} className="h-[280px] w-full">
                  <AreaChart data={regionalYearlyData.filter((d) => d.region === "NYISO")} margin={{ left: 12, right: 12, top: 8 }}>
                    <CartesianGrid vertical={false} />
                    <XAxis dataKey="year" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => `${fmtPct1(v)}%`} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="coal_pct"
                      stackId="a"
                      stroke="var(--color-coal_pct)"
                      fill="var(--color-coal_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="natural_gas_pct"
                      stackId="a"
                      stroke="var(--color-natural_gas_pct)"
                      fill="var(--color-natural_gas_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="nuclear_pct"
                      stackId="a"
                      stroke="var(--color-nuclear_pct)"
                      fill="var(--color-nuclear_pct)"
                      fillOpacity={0.35}
                    />
                    <Area
                      type="monotone"
                      dataKey="renewables_pct"
                      stackId="a"
                      stroke="var(--color-renewables_pct)"
                      fill="var(--color-renewables_pct)"
                      fillOpacity={0.35}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>
          </div>
        </section>

        <section className="space-y-4 pt-4">
          <h3 className="text-xl font-semibold">What drives regional differences?</h3>
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2 text-sm">
              <p className="text-foreground">
                <strong>CAISO (California)</strong> leads the renewable transition with aggressive climate policy and solar resources. Coal was fully eliminated, and Diablo Canyon nuclear retired by 2024. Renewables grew from 22% to 65% of generation, with solar driving most gains. Gas peaked then declined as solar filled daytime load.
              </p>
              <p className="text-foreground">
                <strong>ERCOT (Texas)</strong> shows a different path: wind dominated early renewable growth, with solar accelerating more recently. Coal fell from 28% to 3%, but gas remained steady (~58%) due to fracking-driven low prices and reliability needs. The grid faces integration challenges as renewables approach 35%.
              </p>
            </div>
            <div className="space-y-2 text-sm">
              <p className="text-foreground">
                <strong>PJM</strong>, the largest ISO, followed a classic coal-to-gas transition driven by EPA regulations and gas prices. Coal dropped from 44% to 16%, while gas rose from 28% to 46%. Nuclear provides a steady base (~22%), with renewables growing modestly from 4% to 17%. The region's coal legacy means slower decarbonization.
              </p>
              <p className="text-foreground">
                <strong>NYISO (New York)</strong> benefits from Canadian hydro imports and ambitious state policy. Coal was minimal and is now gone, while Indian Point nuclear retirement reduced the nuclear share from 28% to 11%. Renewables grew from 21% to 50%, led by onshore wind and hydro. Gas remains critical at ~40% for reliability.
              </p>
            </div>
          </div>
        </section>
      </section>

      <section className="space-y-4">
        <h2 className="text-2xl font-semibold">Key takeaways</h2>
        <ul className="list-disc pl-6 space-y-2 text-foreground">
          <li>
            US electricity demand (retail sales) rose about <strong>{fmtPct1(h.retail_sales_change_pct)}%</strong> from {h.first_year} to {h.last_year}.
          </li>
          <li>
            The generation-to-sales gap stayed near ~8% of generation (losses & other uses).
          </li>
          <li>
            The supply mix is where the action is: coal share fell <strong>{fmtSigned1(h.coal_share_pp)} pp</strong>, while natural gas rose <strong>{fmtSigned1(h.natural_gas_share_pp)} pp</strong> and renewables rose <strong>{fmtSigned1(h.renewables_share_pp)} pp</strong>.
          </li>
          <li>
            Regional patterns differ: CAISO leads renewables at 65%, while PJM still relies on gas and coal. ERCOT shows wind dominance, and NYISO leverages hydro with growing wind/solar.
          </li>
        </ul>
      </section>

      <section className="space-y-4">
        <h2 className="text-2xl font-semibold">Other questions to explore</h2>
        <ul className="list-disc pl-6 space-y-2 text-foreground">
          <li>What drives renewables growth? Is wind or solar leading different states, and how does local policy (renewable portfolio standards, tax incentives) map to deployment?</li>
          <li>How volatile is demand? Monthly or seasonal data could reveal weather-driven peaks and whether climate adaptation is needed for extreme heat/cold events.</li>
          <li>What does hourly data show? Annual trends hide intra-day patterns — duck curves, peak demand timing, and battery/dispatch response tell a fuller story.</li>
          <li>How does this intersect with gas prices? The gas-to-coal switch may track natural gas price volatility and LNG export growth.</li>
          <li>What's the emissions picture? Converting generation mixes to CO₂ would show how much decarbonization happened despite flat demand.</li>
          <li>How does nuclear fit in? With aging plants and SMR interest, how has nuclear capacity and utilization changed?</li>
        </ul>
      </section>
    </NotebookTemplate>
  );
}
