import { useMemo, useState } from "react";
import {
  FlaskConical,
  CheckCircle2,
  Atom,
  LineChart,
  Database,
  Gauge,
  Wind,
  RefreshCw,
  SunMedium,
  Layers3,
  Beaker,
  Microscope,
  Radar,
  ScrollText,
  ShieldCheck,
  AlertTriangle,
  FileText,
  FileSpreadsheet,
  Package,
  Github,
  BookOpen,
  ArrowRight,
  Ruler,
  Download,
} from "lucide-react";
import { Section, KpiCard, MiniKpi, StatusBadge, Callout, Chip } from "./primitives";
import {
  ReactorSchematic,
  SamplingCycleDiagram,
  PhotocatalysisMechanism,
  CatalystSynthesisFlow,
} from "./diagrams";
import {
  KineticFitChart,
  ComparativeCurveChart,
} from "./charts";
import { PROJECT } from "@/lib/project-config";
import kpis from "@/data/dashboard_kpis.json";
import workflow from "@/data/workflow_steps.json";
import reactorCfg from "@/data/reactor_configuration.json";
import catalyst from "@/data/catalyst_characterization.json";
import calibration from "@/data/calibration_limits.json";
import experimentPlan from "@/data/experiment_plan.json";
import experimental from "@/data/experimental_data.json";
import kinetics from "@/data/kinetic_parameters.json";
import butanone from "@/data/butanone_case.json";
import sources from "@/data/methodology_sources.json";
import sourceNotes from "@/data/source_notes.json";
import qa from "@/data/qa_controls.json";

/* ---------- KPI SECTION ---------- */
export function KpiSection() {
  const headline = [
    { value: "41", label: "Completed experiments", icon: FlaskConical, tone: "teal" as const },
    { value: "82.0%", label: "Experimental plan delivered", icon: CheckCircle2, tone: "emerald" as const },
    { value: "5", label: "VOCs studied", icon: Atom, tone: "cyan" as const },
    { value: "4", label: "VOCs with kinetic fits", icon: LineChart, tone: "teal" as const },
    { value: "40", label: "Fitted observations", icon: Database, tone: "cyan" as const },
    { value: "1–103.4 ppmv", label: "Inlet concentration window", icon: Gauge, tone: "amber" as const },
    { value: "23.8 L min⁻¹", label: "Airflow", icon: Wind, tone: "teal" as const },
    { value: "0.8 kg m⁻² s⁻¹", label: "Solids circulation flux", icon: RefreshCw, tone: "cyan" as const },
    { value: "75 W · 254 nm", label: "Germicidal UVC source", icon: SunMedium, tone: "emerald" as const },
    { value: "430 m² g⁻¹", label: "Coated catalyst surface area", icon: Layers3, tone: "teal" as const },
  ];
  const secondary = [
    { value: "20 wt%", label: "TiO₂ loading" },
    { value: "98%", label: "Anatase phase" },
    { value: "59 µm", label: "Sauter mean d[3,2]" },
    { value: "45–55%", label: "Relative-humidity control band" },
  ];
  return (
    <Section
      id="kpis"
      eyebrow="STUDY OVERVIEW"
      title="Experimental programme at a glance"
      intro="Ten headline metrics summarise the completed experimental matrix, reactor operating point, analytical scope and catalyst used to estimate gas-phase VOC degradation kinetics."
    >
      <div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-5">
        {headline.map((k) => (
          <KpiCard key={k.label} {...k} />
        ))}
      </div>
      <div className="mt-6 grid grid-cols-2 gap-3 md:grid-cols-4">
        {secondary.map((s) => (
          <MiniKpi key={s.label} value={s.value} label={s.label} tone="cyan" />
        ))}
      </div>
      <p className="mt-6 text-center text-xs text-muted-foreground">
        The {kpis.completed_experiments} completed matrix runs comprise {kpis.fitted_observations} concentration–conversion
        observations used for four kinetic fits plus one successful butanone experiment. Control tests are documented
        separately and are not counted as additional matrix points.
      </p>
      <ExecutiveClaim />
    </Section>
  );
}

function ExecutiveClaim() {
  return (
    <div className="mt-10 glass-panel rounded-2xl p-6 lg:p-8">
      <div className="flex items-start gap-4">
        <span className="grid h-10 w-10 place-items-center rounded-lg bg-[color:var(--emerald)]/15 text-[color:var(--emerald)]">
          <ShieldCheck className="h-5 w-5" />
        </span>
        <p className="text-sm leading-relaxed text-foreground lg:text-base">
          AEROCAT demonstrates a complete experimental modelling chain: catalyst synthesis, material qualification,
          controlled VOC generation, high-velocity solids recirculation, inlet/outlet GC measurement, steady-state
          validation, nonlinear parameter estimation and engineering interpretation.
        </p>
      </div>
      <div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-3">
        {[
          { h: "Materials", b: "20 wt% TiO₂/SiO₂, 98% anatase, 430 m² g⁻¹." },
          { h: "Experiments", b: "41 completed runs, 40 fitted observations, 5 target VOCs." },
          { h: "Model", b: "Plug-flow balance, Langmuir–Hinshelwood kinetics, fitted k and Kₐ." },
        ].map((e) => (
          <div key={e.h} className="rounded-lg border border-border/60 bg-background/30 p-4">
            <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">{e.h}</div>
            <div className="mt-1 text-sm text-foreground">{e.b}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- WORKFLOW ---------- */
export function WorkflowSection() {
  return (
    <Section
      id="workflow"
      eyebrow="ANALYTICAL CHAIN"
      title="From catalyst synthesis to kinetic interpretation"
      intro="Each stage produces a traceable object or acceptance rule, preserving the link between material properties, operating conditions, analytical measurements, conversion results and fitted parameters."
    >
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {workflow.map((w) => (
          <div key={w.id} className="glass-panel hover-lift rounded-xl p-5">
            <div className="flex items-center gap-3">
              <span className="text-[color:var(--teal)] font-mono text-xs">{w.id}</span>
              <span className="h-px flex-1 bg-border" />
            </div>
            <div className="mt-3 text-sm font-semibold text-foreground">{w.title}</div>
            <div className="mt-3 text-[11px] uppercase tracking-[0.15em] text-muted-foreground">Method</div>
            <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{w.method}</p>
            <div className="mt-3 text-[11px] uppercase tracking-[0.15em] text-muted-foreground">Output</div>
            <p className="mt-1 text-xs leading-relaxed text-foreground">{w.output}</p>
          </div>
        ))}
      </div>
      <div className="mt-8 overflow-x-auto">
        <div className="glass-panel min-w-max rounded-xl px-6 py-4 text-[11px] uppercase tracking-[0.2em] text-muted-foreground">
          MATERIAL → REACTOR → FEED → STEADY STATE → GC CYCLE → CONVERSION → FIT → INTERPRETATION
        </div>
      </div>
      <div className="mt-6 grid gap-3 md:grid-cols-3">
        {[
          "UVC is activated only after adsorption saturation is demonstrated by C ≈ C₀.",
          "Stable pressure drop is used as evidence of stable solids holdup.",
          "A run closes only after three stable inlet/outlet sampling cycles.",
        ].map((p, i) => (
          <div key={i} className="rounded-lg border border-border/60 bg-background/30 p-4 text-xs text-muted-foreground">
            {p}
          </div>
        ))}
      </div>
    </Section>
  );
}

/* ---------- REACTOR ---------- */
export function ReactorSection() {
  const metrics = [
    { v: "23.8 L min⁻¹", l: "Airflow Q", tone: "teal" as const },
    { v: "0.8 kg m⁻² s⁻¹", l: "Solids flux Gs", tone: "cyan" as const },
    { v: "200 g", l: "Reservoir inventory", tone: "emerald" as const },
    { v: "≈3 g", l: "Irradiated-zone mass", tone: "amber" as const },
    { v: "45–55% RH", l: "Humidity band", tone: "cyan" as const },
    { v: "5 °C", l: "VOC bubbler bath", tone: "teal" as const },
  ];
  return (
    <Section
      id="reactor"
      eyebrow="EXPERIMENTAL SYSTEM"
      title="A circulating annular photoreactor operated at the kinetic plateau"
      intro="The selected operating point combines high gas velocity, maximum solids circulation and a small irradiated catalyst inventory to reduce mass-transfer, contact and irradiation limitations while maintaining measurable conversion."
    >
      <div className="grid gap-6 lg:grid-cols-[7fr_5fr]">
        <div className="glass-panel rounded-2xl p-4 lg:p-6">
          <ReactorSchematic />
        </div>
        <div className="grid grid-cols-2 gap-3">
          {metrics.map((m) => (
            <MiniKpi key={m.l} value={m.v} label={m.l} tone={m.tone} />
          ))}
        </div>
      </div>
      <div className="mt-8">
        <Callout tone="teal">
          The operating point was selected at the beginning of the high-velocity reaction-rate plateau. Above this
          region, contact and irradiation limitations are reduced, while excessively higher flow would lower conversion
          and increase uncertainty.
        </Callout>
      </div>
      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        <SamplingCycleDiagram />
        <div className="grid grid-cols-1 gap-3">
          {reactorCfg.monitored_variables.map((v, i) => (
            <div key={v} className="glass-panel rounded-xl px-4 py-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-foreground">{v}</span>
                <span className="text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
                  {i < 2 ? "constant" : i < 4 ? "GC cycle / continuous" : "continuous"}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="mt-6 glass-panel rounded-xl p-5">
        <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Control evidence</div>
        <ul className="mt-3 space-y-2 text-sm text-muted-foreground">
          {experimentPlan.control_summary.map((c, i) => (
            <li key={i} className="flex gap-2">
              <span className="text-[color:var(--teal)]">•</span>
              <span>{c}</span>
            </li>
          ))}
        </ul>
      </div>
    </Section>
  );
}

/* ---------- CATALYST ---------- */
export function CatalystSection() {
  const cards = [
    { v: "98% anatase / 2% rutile", l: "XRD", tone: "emerald" as const },
    { v: "430 m² g⁻¹", l: "N₂ adsorption / BET", tone: "teal" as const },
    { v: "40–200 µm", l: "Particle-size range", tone: "cyan" as const },
    { v: "d[3,2] = 59 µm", l: "Sauter mean diameter", tone: "amber" as const },
  ];
  const rows = [
    ["Crystalline phase", "98% anatase, 2% rutile", "X-ray diffraction"],
    ["Surface area", "430 m² g⁻¹", "N₂ adsorption / BET"],
    ["Particle size", "40–200 µm; d[3,2] = 59 µm", "Static light scattering"],
    ["TiO₂ loading", "20 wt%", "Synthesis basis"],
    ["Calcination", "450 °C, 1 h", "Thermal treatment"],
  ];
  return (
    <Section
      id="catalyst"
      eyebrow="MATERIAL SYSTEM"
      title="Supported TiO₂ engineered for fast fluidization and UVC activation"
      intro="The catalyst combines a silica support suitable for fluidization with a photoactive TiO₂ coating, preserving high surface area while providing an anatase-dominant crystalline phase."
    >
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="glass-panel rounded-2xl p-4 lg:p-6">
          <PhotocatalysisMechanism />
        </div>
        <div className="glass-panel rounded-2xl p-6">
          <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Synthesis flow</div>
          <div className="mt-4">
            <CatalystSynthesisFlow steps={catalyst.synthesis_steps} />
          </div>
        </div>
      </div>
      <div className="mt-8 grid grid-cols-2 gap-3 lg:grid-cols-4">
        {cards.map((c) => (
          <MiniKpi key={c.l} value={c.v} label={c.l} tone={c.tone} />
        ))}
      </div>
      <div className="mt-8 overflow-x-auto">
        <table className="w-full min-w-[560px] text-left text-sm">
          <thead>
            <tr className="border-b border-border/60 text-[11px] uppercase tracking-[0.15em] text-muted-foreground">
              <th className="py-3">Property</th>
              <th>Value</th>
              <th>Method</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i} className="border-b border-border/40">
                <td className="py-3 text-muted-foreground">{r[0]}</td>
                <td className="text-foreground">{r[1]}</td>
                <td className="text-muted-foreground">{r[2]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="mt-6">
        <Callout tone="amber">
          The final coated-catalyst value is 430 m² g⁻¹. The 460 m² g⁻¹ figure refers to the original silica support or
          earlier contextual characterisation, not the final dashboard KPI.
        </Callout>
      </div>
    </Section>
  );
}

/* ---------- EXPERIMENTS ---------- */
export function ExperimentsSection() {
  const [expanded, setExpanded] = useState(false);
  const [filter, setFilter] = useState("");
  const filtered = useMemo(() => {
    const f = filter.toLowerCase();
    return experimental.filter(
      (r) =>
        r.pollutant.toLowerCase().includes(f) ||
        r.phase.toLowerCase().includes(f) ||
        String(r.c0_ppmv).includes(f)
    );
  }, [filter]);
  const visible = expanded ? filtered : filtered.slice(0, 12);
  return (
    <Section
      id="experiments"
      eyebrow="EXPERIMENTAL MATRIX"
      title="Forty fitted observations across four VOCs, plus one butanone case"
      intro="The two project phases jointly cover ten inlet concentrations for each fitted pollutant. The combined matrix spans low-concentration adsorption control, a mixed kinetic regime and high-concentration surface-site limitation."
    >
      <div className="grid grid-cols-2 gap-3 md:grid-cols-5">
        <MiniKpi value="50" label="Planned matrix experiments" tone="cyan" />
        <MiniKpi value="41" label="Completed" tone="teal" />
        <MiniKpi value="82.0%" label="Completion" tone="emerald" />
        <MiniKpi value="40" label="Fitted observations" tone="teal" />
        <MiniKpi value="1" label="Successful butanone case" tone="amber" />
      </div>
      <div className="mt-6">
        <Callout tone="amber">
          Nine planned butanone runs were not completed because strong adsorption extended operating time and caused
          excessive photocatalyst attrition and entrainment. The limitation is reported explicitly rather than hidden.
        </Callout>
      </div>

      {/* Concentration matrix */}
      <div className="mt-10">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <div className="text-sm font-semibold text-foreground">Planned concentration matrix (ppmv)</div>
          <StatusBadge tone="cyan">Source label normalised · n-pentane</StatusBadge>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[720px] text-left text-xs">
            <thead>
              <tr className="border-b border-border/60 text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
                <th className="py-3 pr-4">Pollutant</th>
                {Array.from({ length: 10 }).map((_, i) => (
                  <th key={i} className="pr-3">C{i + 1}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {experimentPlan.fitted_matrix.map((row) => (
                <tr key={row.pollutant} className="border-b border-border/40">
                  <td className="py-2.5 pr-4 text-foreground">{row.pollutant}</td>
                  {row.c0_ppmv.map((v, i) => (
                    <td key={i} className="pr-3 text-muted-foreground">
                      {v.toFixed(1)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <p className="mt-3 text-[11px] text-muted-foreground">
          Source label normalised: the final report matrix contains “cyclohexane”, but the concentration series,
          figures, narrative and kinetic constants consistently identify n-pentane.
        </p>
      </div>

      {/* GC settings */}
      <div className="mt-10 grid gap-6 lg:grid-cols-[6fr_5fr]">
        <div className="glass-panel rounded-xl p-5">
          <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">GC-PID/TID settings</div>
          <ul className="mt-4 grid grid-cols-1 gap-2 text-sm text-muted-foreground sm:grid-cols-2">
            {[
              ["Oven", "70 °C, isothermal"],
              ["Sample loop", "98 µL"],
              ["Injector pressure", "4 kgf in⁻²"],
              ["Carrier gas", "N₂"],
              ["PID detector", "200 °C"],
              ["Column", "RTX-Volatiles, 30 m, 0.32 mm ID, 2.0 µm film"],
            ].map((r) => (
              <li key={r[0]} className="flex justify-between gap-2 rounded-md border border-border/60 bg-background/30 px-3 py-2">
                <span>{r[0]}</span>
                <span className="text-foreground">{r[1]}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="overflow-x-auto rounded-xl border border-border/60">
          <table className="w-full min-w-[420px] text-left text-xs">
            <thead>
              <tr className="border-b border-border/60 bg-background/40 text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
                <th className="p-3">Pollutant</th>
                <th className="p-3">LOD (ppmv)</th>
                <th className="p-3">LOQ (ppmv)</th>
                <th className="p-3">tR (min)</th>
              </tr>
            </thead>
            <tbody>
              {calibration.map((c) => (
                <tr key={c.pollutant} className="border-b border-border/40">
                  <td className="p-3 text-foreground">{c.pollutant}</td>
                  <td className="p-3 text-muted-foreground">{c.detection_limit_ppmv}</td>
                  <td className="p-3 text-muted-foreground">{c.quantification_limit_ppmv}</td>
                  <td className="p-3 text-muted-foreground">{c.gc_retention_time_min}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Experimental data table */}
      <div className="mt-10">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <div className="text-sm font-semibold text-foreground">Experimental observations</div>
          <input
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            placeholder="Filter by pollutant, phase or C₀"
            aria-label="Filter table"
            className="w-64 max-w-full rounded-md border border-border bg-background/40 px-3 py-1.5 text-xs text-foreground placeholder:text-muted-foreground focus:border-[color:var(--primary)]/60 focus:outline-none"
          />
        </div>
        <div className="overflow-x-auto rounded-xl border border-border/60">
          <table className="w-full min-w-[640px] text-left text-xs">
            <thead>
              <tr className="border-b border-border/60 bg-background/40 text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
                <th className="p-3">Pollutant</th>
                <th className="p-3">Phase</th>
                <th className="p-3">C₀ (ppmv)</th>
                <th className="p-3">σ C₀</th>
                <th className="p-3">X (%)</th>
                <th className="p-3">σ X</th>
              </tr>
            </thead>
            <tbody>
              {visible.map((r, i) => (
                <tr key={i} className="border-b border-border/40">
                  <td className="p-3 text-foreground">{r.pollutant}</td>
                  <td className="p-3 text-muted-foreground">{r.phase}</td>
                  <td className="p-3 text-muted-foreground">{r.c0_ppmv.toFixed(1)}</td>
                  <td className="p-3 text-muted-foreground">{r.c0_sd_ppmv ?? "—"}</td>
                  <td className="p-3 text-foreground">{r.conversion_pct.toFixed(1)}</td>
                  <td className="p-3 text-muted-foreground">{r.conversion_sd_pct ?? "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length > 12 && (
          <div className="mt-3 text-right">
            <button
              className="inline-flex items-center gap-1 rounded-md border border-border bg-background/40 px-3 py-1.5 text-xs text-foreground transition-colors hover:border-[color:var(--primary)]/60"
              onClick={() => setExpanded((v) => !v)}
            >
              {expanded ? "Collapse" : `View all ${filtered.length} observations`}
              <ArrowRight className="h-3 w-3" />
            </button>
          </div>
        )}
      </div>
    </Section>
  );
}

/* ---------- KINETICS ---------- */
export function KineticsSection() {
  const regimes = [
    {
      h: "C₀ < 10 ppmv · adsorption-sensitive",
      body: ["Order: toluene > benzene > n-hexane > n-pentane.", "Kₐ strongly influences conversion."],
      tone: "emerald" as const,
    },
    {
      h: "10–70 ppmv · mixed control",
      body: [
        "Order evolves toward toluene > n-hexane > benzene > n-pentane.",
        "Adsorption and surface reaction both matter.",
      ],
      tone: "teal" as const,
    },
    {
      h: "C₀ > 70 ppmv · site-limited",
      body: ["Available TiO₂ sites and residence time dominate.", "Modelled conversion remains below about 15%."],
      tone: "amber" as const,
    },
  ];
  return (
    <Section
      id="kinetics"
      eyebrow="KINETIC MODELLING"
      title="Langmuir–Hinshelwood fits reveal distinct adsorption and reaction regimes"
      intro="A plug-flow material balance was combined with a single-component Langmuir–Hinshelwood rate law and fitted by nonlinear least squares to each ten-point pollutant dataset."
    >
      <div className="grid gap-6 md:grid-cols-2">
        {kinetics.map((k) => (
          <div key={k.pollutant} className="glass-panel rounded-2xl p-5">
            <div className="flex items-center justify-between">
              <div className="text-sm font-semibold text-foreground">{k.pollutant}</div>
              <div className="flex gap-2 text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
                <span>k {k.k_mg_gcat_h}</span>
                <span>·</span>
                <span>Kₐ {k.ka_m3_mg}</span>
              </div>
            </div>
            <KineticFitChart pollutant={k.pollutant} seriesKey={k.series_key} tone={k.tone} />
            <div className="mt-2 text-[11px] text-muted-foreground">
              Curve reconstructed from reported equations and constants.
            </div>
          </div>
        ))}
      </div>
      <div className="mt-10 glass-panel rounded-2xl p-5">
        <div className="mb-3 flex items-center justify-between">
          <div className="text-sm font-semibold text-foreground">Comparative model curves</div>
          <span className="text-[11px] text-muted-foreground">Reconstructed · four VOCs</span>
        </div>
        <ComparativeCurveChart />
      </div>

      <div className="mt-10 overflow-x-auto rounded-xl border border-border/60">
        <table className="w-full min-w-[560px] text-left text-sm">
          <thead>
            <tr className="border-b border-border/60 bg-background/40 text-[11px] uppercase tracking-[0.15em] text-muted-foreground">
              <th className="p-3">Pollutant</th>
              <th className="p-3 text-right">k (mg gcat⁻¹ h⁻¹)</th>
              <th className="p-3 text-right">Kₐ (m³ mg⁻¹)</th>
              <th className="p-3">Interpretation</th>
            </tr>
          </thead>
          <tbody>
            {kinetics.map((k) => (
              <tr key={k.pollutant} className="border-b border-border/40">
                <td className="p-3 text-foreground">{k.pollutant}</td>
                <td className="p-3 text-right text-foreground">{k.k_mg_gcat_h}</td>
                <td className="p-3 text-right text-foreground">{k.ka_m3_mg}</td>
                <td className="p-3 text-muted-foreground">{k.interpretation}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="mt-10 grid gap-4 md:grid-cols-3">
        {regimes.map((r) => (
          <div key={r.h} className="glass-panel hover-lift rounded-xl p-5">
            <div className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground">Regime</div>
            <div className="mt-1 text-sm font-semibold text-foreground">{r.h}</div>
            <ul className="mt-3 space-y-1 text-xs text-muted-foreground">
              {r.body.map((b, i) => (
                <li key={i}>• {b}</li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div className="mt-6">
        <Callout tone="cyan">
          The aromatic compounds have adsorption constants about four times the n-hexane value and nearly twenty times
          the n-pentane value. Toluene combines strong adsorption with a substantially faster surface reaction than
          benzene.
        </Callout>
      </div>
    </Section>
  );
}

/* ---------- BUTANONE ---------- */
export function ButanoneSection() {
  return (
    <Section
      id="butanone"
      eyebrow="OPERATIONAL EDGE CASE"
      title="Chemically favourable, operationally difficult"
      intro="A single long-duration butanone run produced the highest conversion at a comparable inlet concentration, but strong adsorption greatly extended equilibration and amplified catalyst loss."
    >
      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6">
        <MiniKpi value="18 ppmv" label="Inlet · source 17.7 ppmv" tone="cyan" />
        <MiniKpi value="43.5%" label="Steady-state conversion" tone="emerald" />
        <MiniKpi value="2 h" label="Adsorption equilibration" tone="teal" />
        <MiniKpi value="7 h" label="Total experiment" tone="teal" />
        <MiniKpi value="91.3 g" label="Catalyst lost" tone="rust" />
        <MiniKpi value="108.7 g" label="Catalyst remaining" tone="amber" />
      </div>

      <div className="mt-10 glass-panel rounded-2xl p-5 lg:p-6">
        <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Incident-style timeline</div>
        <ol className="mt-6 grid gap-4 md:grid-cols-5">
          {butanone.timeline.map((t, i) => (
            <li key={i} className="relative rounded-lg border border-border/60 bg-background/30 p-4">
              <div className="text-[color:var(--teal)] text-xs font-mono">t = {t.time_min} min</div>
              <div className="mt-2 text-xs text-foreground">{t.label}</div>
              {i < butanone.timeline.length - 1 && (
                <span className="absolute right-[-10px] top-1/2 hidden h-px w-5 bg-border md:block" />
              )}
            </li>
          ))}
        </ol>
        <p className="mt-4 text-[11px] text-muted-foreground">
          The report provides a plotted profile but not a tabulated digital time series; milestones are shown
          instead of a fabricated continuous curve.
        </p>
      </div>

      <div className="mt-8 rounded-2xl border border-[color:var(--rust)]/40 bg-[color:var(--rust)]/10 p-6">
        <div className="flex items-start gap-3">
          <AlertTriangle className="h-5 w-5 shrink-0 text-[color:var(--rust)]" />
          <div className="space-y-2 text-sm text-foreground">
            <p>
              The butanone run lost 91.3 g of photocatalyst, compared with approximately 10–15 g for a typical
              experiment with the other VOCs. Strong adsorption made the chemistry favourable but the high-velocity
              fluidized-bed configuration operationally costly for this compound.
            </p>
            <p className="text-xs text-muted-foreground">
              No k or Kₐ is reported for butanone. Do not extrapolate a kinetic fit from this single run.
            </p>
          </div>
        </div>
      </div>
    </Section>
  );
}

/* ---------- MODEL ---------- */
export function ModelSection() {
  const formulas = [
    {
      h: "Plug-flow material balance",
      body: "Q · dC/dm = −rₘ",
      note: "Concentration decreases along catalyst mass; the source report uses its own rate-sign convention.",
    },
    { h: "Langmuir–Hinshelwood rate", body: "rₘ = (k · Kₐ · C) / (1 + Kₐ · C)" },
    { h: "Conversion", body: "X = 1 − C/C₀" },
  ];
  const dictionary = [
    ["Q", "gas volumetric flow, m³ h⁻¹"],
    ["C₀", "inlet VOC concentration, mg m⁻³ or ppmv before unit conversion"],
    ["C", "outlet/local VOC concentration"],
    ["m", "catalyst mass in the irradiated reactor zone"],
    ["rₘ", "mass-specific reaction rate, mg gcat⁻¹ h⁻¹"],
    ["k", "surface-reaction constant, mg gcat⁻¹ h⁻¹"],
    ["Kₐ", "adsorption constant, m³ mg⁻¹"],
  ];
  const regression = [
    "Nonlinear least squares",
    "lsqnonlin routine",
    "Levenberg–Marquardt algorithm",
    "Ten observations per fitted VOC",
    "≈3 g catalyst in irradiated zone",
    "Q = 1.428 m³ h⁻¹ from 23.8 L min⁻¹",
  ];
  const limits = [
    "Single-component adsorption model.",
    "Plug-flow representation rather than a full residence-time-distribution model.",
    "No explicit radiation-field attenuation term.",
    "No explicit void-fraction submodel inside this page.",
    "Parent-VOC conversion, not mineralization or by-product yield.",
    "No fitted-parameter confidence intervals reported.",
  ];
  return (
    <Section
      id="model"
      eyebrow="MODEL ARCHITECTURE"
      title="A plug-flow balance coupled to surface adsorption and reaction"
      intro="The model separates reactor transport representation from the intrinsic Langmuir–Hinshelwood rate expression, then estimates pollutant-specific adsorption and surface-reaction constants."
    >
      <div className="grid gap-4 md:grid-cols-3">
        {formulas.map((f) => (
          <div key={f.h} className="glass-panel rounded-xl p-5">
            <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">{f.h}</div>
            <div className="mt-4 rounded-lg border border-border/60 bg-background/40 p-4 text-center font-mono text-base text-foreground">
              {f.body}
            </div>
            {f.note && <p className="mt-3 text-[11px] text-muted-foreground">{f.note}</p>}
          </div>
        ))}
      </div>
      <div className="mt-10 grid gap-6 lg:grid-cols-[5fr_7fr]">
        <div className="glass-panel rounded-xl p-5">
          <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Variable dictionary</div>
          <dl className="mt-4 space-y-2 text-sm">
            {dictionary.map(([k, v]) => (
              <div key={k} className="flex gap-3 border-b border-border/40 pb-2 last:border-0">
                <dt className="w-14 font-mono text-[color:var(--teal)]">{k}</dt>
                <dd className="flex-1 text-muted-foreground">{v}</dd>
              </div>
            ))}
          </dl>
        </div>
        <div className="glass-panel rounded-xl p-5">
          <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Regression method</div>
          <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2">
            {regression.map((r) => (
              <div key={r} className="rounded-md border border-border/60 bg-background/30 px-3 py-2 text-xs text-foreground">
                {r}
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="mt-8">
        <Callout tone="amber">
          The local <code className="font-mono text-[11px]">model_curves.json</code> file is a transparent
          reconstruction for website visualisation. It uses the reported equations, k, Kₐ, Q = 1.428 m³ h⁻¹,
          approximately 3.0 g irradiated catalyst and a 24.45 L mol⁻¹ gas conversion basis at 25 °C. These points are
          model outputs, not additional measurements.
        </Callout>
      </div>
      <div className="mt-8 grid gap-3 md:grid-cols-3">
        {limits.map((l, i) => (
          <div key={i} className="rounded-lg border border-border/60 bg-background/30 p-4 text-xs text-muted-foreground">
            {l}
          </div>
        ))}
      </div>

      <div className="mt-10 glass-panel rounded-xl p-5">
        <div className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Reproducible package</div>
        <div className="mt-3 overflow-x-auto">
          <div className="min-w-max font-mono text-xs text-foreground">
            data/ → notebooks/ → model/ → figures/ → docs/ → evidence/ → qa/ → website/
          </div>
        </div>
        <div className="mt-5 flex flex-wrap gap-3">
          <a
            href={PROJECT.datasetUrl}
            className="inline-flex items-center gap-2 rounded-md border border-border bg-background/40 px-4 py-2 text-xs text-foreground hover:border-[color:var(--primary)]/60"
          >
            <FileSpreadsheet className="h-4 w-4" /> Download experimental dataset
          </a>
          <a
            href={PROJECT.reportUrl}
            className="inline-flex items-center gap-2 rounded-md border border-border bg-background/40 px-4 py-2 text-xs text-foreground hover:border-[color:var(--primary)]/60"
          >
            <FileText className="h-4 w-4" /> Read final report
          </a>
        </div>
      </div>
    </Section>
  );
}

/* ---------- METHODOLOGY ---------- */
export function MethodologySection() {
  const method = [
    { icon: Wind, h: "VOC problem framing", b: "Atmospheric relevance, difficult removal and treatment trade-offs." },
    { icon: SunMedium, h: "Heterogeneous photocatalysis", b: "UVC activation, electron–hole generation and surface oxidation." },
    { icon: RefreshCw, h: "Fast fluidization", b: "Improved pollutant–catalyst–radiation contact with attrition trade-off." },
    { icon: Microscope, h: "Analytical measurement", b: "Calibrated inlet/outlet GC-PID/TID cycles." },
    { icon: Radar, h: "Steady-state validation", b: "C≈C₀ before UVC, stable ΔP and RH, three stable cycles." },
    { icon: LineChart, h: "Kinetic estimation", b: "PFR + Langmuir–Hinshelwood fitted by Levenberg–Marquardt." },
  ];
  const boundaries = [
    "Laboratory-scale research dataset.",
    "No industrial-scale performance guarantee.",
    "No institutional endorsement implied.",
    "No claim of complete mineralization.",
    "No k/Kₐ for butanone.",
    "No invented R², confidence interval, raw monitoring time series or by-product profile.",
  ];
  return (
    <Section
      id="methodology"
      eyebrow="METHODOLOGY"
      title="A traceable method grounded in photocatalysis and fluidization literature"
      intro="The project combines gas-phase VOC chemistry, supported-semiconductor preparation, circulating fluidized-bed operation, chromatographic measurement and nonlinear kinetic estimation."
    >
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {method.map((m) => {
          const Icon = m.icon;
          return (
            <div key={m.h} className="glass-panel hover-lift rounded-xl p-5">
              <span className="grid h-9 w-9 place-items-center rounded-md bg-[color:var(--teal)]/15 text-[color:var(--teal)]">
                <Icon className="h-4 w-4" />
              </span>
              <div className="mt-3 text-sm font-semibold text-foreground">{m.h}</div>
              <p className="mt-2 text-xs text-muted-foreground">{m.b}</p>
            </div>
          );
        })}
      </div>

      <div className="mt-12">
        <div className="mb-3 flex items-center gap-2 text-[10px] uppercase tracking-[0.2em] text-muted-foreground">
          <BookOpen className="h-3.5 w-3.5" /> Literature
        </div>
        <div className="grid gap-3 md:grid-cols-2">
          {sources.map((s) => (
            <div key={s.id} className="rounded-lg border border-border/60 bg-background/30 p-4">
              <div className="text-[10px] uppercase tracking-[0.15em] text-[color:var(--teal)]">{s.id}</div>
              <div className="mt-1 text-xs text-foreground">{s.citation}</div>
              <div className="mt-2 text-[11px] text-muted-foreground">{s.role}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="mt-10 glass-panel rounded-xl p-5">
        <div className="mb-3 flex items-center gap-2 text-[10px] uppercase tracking-[0.2em] text-muted-foreground">
          <ScrollText className="h-3.5 w-3.5" /> Source normalisation
        </div>
        <div className="grid gap-3 md:grid-cols-2">
          {sourceNotes.map((n, i) => (
            <div key={i} className="rounded-lg border border-border/60 bg-background/30 p-4">
              <div className="text-[11px] text-[color:var(--amber)]">{n.issue}</div>
              <div className="mt-1 text-xs text-muted-foreground">{n.normalization}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="mt-10 grid gap-3 md:grid-cols-3">
        {boundaries.map((b, i) => (
          <div key={i} className="rounded-lg border border-border/60 bg-background/30 p-4 text-xs text-muted-foreground">
            {b}
          </div>
        ))}
      </div>
    </Section>
  );
}

/* ---------- QA ---------- */
export function QaSection() {
  return (
    <Section
      id="qa"
      eyebrow="QUALITY ASSURANCE"
      title="Every headline number has a reconciliation rule"
      intro="Fifteen checks reconcile the experiment counts, pollutant scope, operating conditions, material properties, fitted parameters, source normalisations and model-curve provenance."
    >
      <div className="overflow-x-auto rounded-xl border border-border/60">
        <table className="w-full min-w-[720px] text-left text-xs">
          <thead>
            <tr className="border-b border-border/60 bg-background/40 text-[10px] uppercase tracking-[0.15em] text-muted-foreground">
              <th className="p-3">ID</th>
              <th className="p-3">Control</th>
              <th className="p-3">Expected</th>
              <th className="p-3">Status</th>
            </tr>
          </thead>
          <tbody>
            {qa.map((r) => (
              <tr key={r.id} className="border-b border-border/40">
                <td className="p-3 font-mono text-[color:var(--teal)]">{r.id}</td>
                <td className="p-3 text-foreground">{r.control}</td>
                <td className="p-3 text-muted-foreground">{r.expected}</td>
                <td className="p-3">
                  <StatusBadge tone="emerald">{r.status}</StatusBadge>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="mt-8 grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6">
        {[
          ["40 / 40", "Fitted observations present"],
          ["4 × 10", "Concentration points reconciled"],
          ["41 / 50", "Experimental plan"],
          ["5", "VOC identities resolved"],
          ["4", "Exact k/Kₐ pairs"],
          ["0", "Invented R² or fitted uncertainties"],
        ].map(([v, l]) => (
          <MiniKpi key={l} value={v} label={l} tone="teal" />
        ))}
      </div>

      <div className="mt-8 overflow-x-auto rounded-lg border border-border/60 bg-background/60 p-4 font-mono text-xs text-muted-foreground">
        <div><span className="text-[color:var(--teal)]">$</span> npm run build</div>
        <div><span className="text-[color:var(--teal)]">$</span> npm run test:data</div>
        <div className="text-[color:var(--emerald)]"># all dataset reconciliation checks passed</div>
      </div>
    </Section>
  );
}

/* ---------- CONCLUSIONS ---------- */
export function ConclusionsSection() {
  const items = [
    "Adsorption dominates pollutant ranking at low inlet concentration.",
    "n-Pentane is limited primarily by weak adsorption despite a surface-reaction constant similar to n-hexane.",
    "Toluene combines strong adsorption and higher surface reactivity than benzene.",
    "At high concentration, site availability and residence time constrain all four fitted VOCs to low conversion.",
    "Butanone is chemically easy to remove but operationally unsuitable for long high-velocity runs without attrition mitigation.",
  ];
  const future = [
    "Void-fraction prediction.",
    "Radiation-field attenuation as solids concentration rises.",
    "Hydrodynamics more complex than ideal PFR.",
    "Attrition-aware reactor configuration for strongly adsorbing VOCs.",
  ];
  return (
    <Section
      id="conclusions"
      eyebrow="ENGINEERING READ-OUT"
      title="What the results change in reactor interpretation"
    >
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
        {items.map((c, i) => (
          <div key={i} className="glass-panel hover-lift rounded-xl p-5">
            <div className="text-[color:var(--teal)] font-mono text-xs">C{String(i + 1).padStart(2, "0")}</div>
            <p className="mt-3 text-xs leading-relaxed text-foreground">{c}</p>
          </div>
        ))}
      </div>
      <div className="mt-10">
        <div className="mb-3 text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Future modelling directions</div>
        <div className="grid gap-3 md:grid-cols-4">
          {future.map((f) => (
            <div key={f} className="rounded-lg border border-border/60 bg-background/30 p-4 text-xs text-muted-foreground">
              {f}
            </div>
          ))}
        </div>
      </div>
    </Section>
  );
}

/* ---------- REPRODUCIBILITY ---------- */
export function ReproducibilitySection() {
  const cards = [
    { icon: FileText, h: "Final scientific report", href: PROJECT.reportUrl, b: "Complete FAPESP final report with methodology, results and discussion." },
    { icon: FileSpreadsheet, h: "Experimental dataset", href: PROJECT.datasetUrl, b: "Structured concentration–conversion data used for the kinetic fits." },
    { icon: Package, h: "Complete project package", href: PROJECT.packageUrl, b: "Data, notebooks, model reconstruction, figures and QA in one archive." },
    { icon: Github, h: "GitHub repository", href: PROJECT.githubUrl, external: true, b: "Source, data files and reproducible model reconstruction." },
  ];
  const evidence = [
    { icon: Ruler, h: "Methodology", href: PROJECT.methodologyUrl },
    { icon: ScrollText, h: "Technical specification", href: PROJECT.specificationUrl },
    { icon: ShieldCheck, h: "QA report", href: PROJECT.qaUrl },
  ];
  return (
    <Section
      id="reproducibility"
      eyebrow="REPRODUCIBILITY"
      title="Data, report, method and model connected to the same evidence chain"
      intro="The final report, structured dataset, model reconstruction, technical specification and QA notes are exposed through stable local paths and a single project configuration."
    >
      <div className="grid gap-4 md:grid-cols-2">
        {cards.map((c) => {
          const Icon = c.icon;
          return (
            <a
              key={c.h}
              href={c.href}
              target={c.external ? "_blank" : undefined}
              rel={c.external ? "noreferrer" : undefined}
              download={c.external ? undefined : true}
              className="glass-panel hover-lift block rounded-2xl p-6"
            >
              <div className="flex items-start justify-between">
                <span className="grid h-10 w-10 place-items-center rounded-lg bg-[color:var(--teal)]/15 text-[color:var(--teal)]">
                  <Icon className="h-5 w-5" />
                </span>
                <Download className="h-4 w-4 text-muted-foreground" />
              </div>
              <div className="mt-4 text-base font-semibold text-foreground">{c.h}</div>
              <p className="mt-2 text-xs text-muted-foreground">{c.b}</p>
            </a>
          );
        })}
      </div>
      <div className="mt-6 grid gap-3 md:grid-cols-3">
        {evidence.map((e) => {
          const Icon = e.icon;
          return (
            <a
              key={e.h}
              href={e.href}
              download
              className="flex items-center justify-between rounded-lg border border-border/60 bg-background/30 px-4 py-3 text-xs text-foreground transition-colors hover:border-[color:var(--primary)]/60"
            >
              <span className="inline-flex items-center gap-2">
                <Icon className="h-4 w-4 text-muted-foreground" />
                {e.h}
              </span>
              <ArrowRight className="h-3.5 w-3.5 text-muted-foreground" />
            </a>
          );
        })}
      </div>
    </Section>
  );
}
