"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import type { GraftCombination, Plant, SoilProfile } from "@/types/api";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

type Step = 1 | 2 | 3 | 4 | 5;

interface CareForm {
  scenarioName: string;
  nitrogen: number;
  phosphorus: number;
  potassium: number;
  irrigationMethod: "drip" | "sprinkler" | "flood" | "rainfed";
  irrigationFrequencyDays: number;
  season: "spring" | "summer" | "autumn" | "winter";
  durationDays: number;
}

// ---------------------------------------------------------------------------
// Shared UI atoms
// ---------------------------------------------------------------------------

function Badge({ label, className }: { label: string; className: string }) {
  return (
    <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium capitalize ${className}`}>
      {label}
    </span>
  );
}

function ToleranceRow({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div className="flex items-center gap-2">
      <span className="w-14 shrink-0 text-xs text-stone-400">{label}</span>
      <div className="h-1.5 flex-1 rounded-full bg-stone-100">
        <div className={`h-1.5 rounded-full ${color}`} style={{ width: `${value * 10}%` }} />
      </div>
      <span className="w-4 text-right text-xs text-stone-500">{value}</span>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step indicator
// ---------------------------------------------------------------------------

const STEPS = [
  { n: 1, label: "Scion" },
  { n: 2, label: "Rootstock" },
  { n: 3, label: "Soil" },
  { n: 4, label: "Care Protocol" },
  { n: 5, label: "Review & Run" },
];

function StepIndicator({ current }: { current: Step }) {
  return (
    <nav className="mb-8 sm:mb-10">
      <ol className="flex items-center justify-between sm:justify-start gap-0 sm:gap-0">
        {STEPS.map((s, i) => {
          const done = s.n < current;
          const active = s.n === current;
          return (
            <li key={s.n} className={`flex items-center ${i < STEPS.length - 1 ? "flex-1" : "flex-initial"}`}>
              <div className="flex flex-col items-center gap-1">
                <div
                  className={`flex h-7 w-7 sm:h-8 sm:w-8 items-center justify-center rounded-full text-xs sm:text-sm font-semibold transition-colors ${
                    done
                      ? "bg-emerald-700 text-white"
                      : active
                        ? "border-2 border-emerald-700 bg-white text-emerald-700"
                        : "border-2 border-stone-200 bg-white text-stone-400"
                  }`}
                >
                  {done ? (
                    <svg className="h-3 w-3 sm:h-4 sm:w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                    </svg>
                  ) : (
                    s.n
                  )}
                </div>
                <span
                  className={`hidden text-[10px] sm:text-xs font-medium lg:block ${
                    active ? "text-emerald-700" : done ? "text-stone-500" : "text-stone-400"
                  }`}
                >
                  {s.label}
                </span>
              </div>
              {i < STEPS.length - 1 && (
                <div className={`mx-1 sm:mx-2 mb-0 sm:mb-5 h-0.5 flex-1 ${done ? "bg-emerald-600" : "bg-stone-200"}`} />
              )}
            </li>
          );
        })}
      </ol>
      {/* Mobile label */}
      <div className="mt-4 text-center sm:hidden">
        <p className="text-xs font-bold text-emerald-800 uppercase tracking-wider">
          Step {current}: {STEPS[current - 1].label}
        </p>
      </div>
    </nav>
  );
}

// ---------------------------------------------------------------------------
// Step 1 — Select Scion
// ---------------------------------------------------------------------------

function Step1({
  plants,
  selected,
  onSelect,
}: {
  plants: Plant[];
  selected: Plant | null;
  onSelect: (p: Plant) => void;
}) {
  const [search, setSearch] = useState("");
  const scions = useMemo(
    () =>
      plants
        .filter((p) => p.variety_type === "scion" || p.variety_type === "both")
        .filter(
          (p) =>
            !search ||
            p.name.toLowerCase().includes(search.toLowerCase()) ||
            p.species.toLowerCase().includes(search.toLowerCase())
        ),
    [plants, search]
  );

  return (
    <div>
      <h2 className="text-base sm:text-lg font-semibold text-stone-900">Select your scion variety</h2>
      <p className="mt-1 text-xs sm:text-sm text-stone-500">
        The scion is the plant whose fruit you want to grow. Choose the variety you&apos;d like to evaluate.
      </p>

      <div className="relative mt-5 w-full sm:max-w-sm">
        <svg className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
        </svg>
        <input
          type="text"
          placeholder="Search varieties…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full rounded-lg border border-stone-200 bg-white py-2 pl-9 pr-3 text-sm placeholder:text-stone-400 focus:border-emerald-400 focus:outline-none focus:ring-2 focus:ring-emerald-100"
        />
      </div>

      {scions.length === 0 ? (
        <div className="mt-8 rounded-xl border border-dashed border-stone-200 bg-white py-16 text-center">
          <p className="text-sm text-stone-400">No plants found. Make sure the backend is running and seeded.</p>
        </div>
      ) : (
        <div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {scions.map((plant) => {
            const isSelected = selected?.id === plant.id;
            return (
              <button
                key={plant.id}
                onClick={() => onSelect(plant)}
                className={`flex flex-col rounded-xl border-2 bg-white p-4 text-left transition hover:border-emerald-300 hover:shadow-sm ${
                  isSelected ? "border-emerald-600 shadow-md ring-2 ring-emerald-100" : "border-stone-200"
                }`}
              >
                <div className="mb-3 flex items-start justify-between gap-2">
                  <div>
                    <p className="text-sm font-semibold text-stone-900">{plant.name}</p>
                    <p className="text-xs italic text-stone-400">{plant.species}</p>
                  </div>
                  {isSelected && (
                    <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-600">
                      <svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                      </svg>
                    </div>
                  )}
                </div>
                <div className="space-y-1">
                  <ToleranceRow label="Drought" value={plant.drought_tolerance} color="bg-amber-400" />
                  <ToleranceRow label="Heat" value={plant.heat_tolerance} color="bg-red-400" />
                  <ToleranceRow label="Salinity" value={plant.salinity_tolerance} color="bg-blue-400" />
                </div>
                <div className="mt-3 flex flex-wrap gap-2 border-t border-stone-100 pt-3 text-xs text-stone-500">
                  <span>pH {plant.optimal_ph_min}–{plant.optimal_ph_max}</span>
                  <span>·</span>
                  <span>{plant.growth_cycle_days}d cycle</span>
                  <span>·</span>
                  <span>{plant.yield_potential_kg_per_plant} kg/plant</span>
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 2 — Choose Rootstock
// ---------------------------------------------------------------------------

function Step2({
  grafts,
  selectedPlant,
  selectedGraft,
  onSelectGraft,
  onSkip,
}: {
  grafts: GraftCombination[];
  selectedPlant: Plant;
  selectedGraft: GraftCombination | null;
  onSelectGraft: (g: GraftCombination | null) => void;
  onSkip: () => void;
}) {
  const compatible = useMemo(
    () =>
      grafts
        .filter((g) => g.scion_id === selectedPlant.id)
        .sort((a, b) => b.compatibility_score - a.compatibility_score),
    [grafts, selectedPlant.id]
  );

  return (
    <div>
      <h2 className="text-lg font-semibold text-stone-900">Choose a rootstock</h2>
      <p className="mt-1 text-sm text-stone-500">
        Grafting onto a rootstock can boost drought/salinity tolerance and yield. This step is optional.
      </p>

      {/* Skip option */}
      <button
        onClick={onSkip}
        className={`mt-5 flex w-full items-center gap-3 rounded-xl border-2 bg-white p-4 text-left transition hover:border-stone-300 ${
          selectedGraft === null ? "border-stone-400 ring-2 ring-stone-100" : "border-stone-200"
        }`}
      >
        <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${selectedGraft === null ? "bg-stone-700 text-white" : "bg-stone-100 text-stone-500"}`}>
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15" />
          </svg>
        </div>
        <div>
          <p className="text-sm font-semibold text-stone-900">Grow ungrafted</p>
          <p className="text-xs text-stone-500">
            Evaluate {selectedPlant.name} on its own root system.
          </p>
        </div>
      </button>

      {compatible.length === 0 ? (
        <div className="mt-4 rounded-xl border border-dashed border-stone-200 bg-white py-10 text-center">
          <p className="text-sm text-stone-400">No registered graft combinations for this variety.</p>
          <p className="text-xs text-stone-400 mt-1">Proceed ungrafted or add combinations to the database.</p>
        </div>
      ) : (
        <div className="mt-4 grid gap-3 sm:grid-cols-2">
          {compatible.map((graft) => {
            const isSelected = selectedGraft?.id === graft.id;
            const pct = Math.round(graft.compatibility_score * 100);
            return (
              <button
                key={graft.id}
                onClick={() => onSelectGraft(graft)}
                className={`flex flex-col rounded-xl border-2 bg-white p-4 text-left transition hover:border-emerald-300 hover:shadow-sm ${
                  isSelected ? "border-emerald-600 shadow-md ring-2 ring-emerald-100" : "border-stone-200"
                }`}
              >
                <div className="mb-3 flex items-start justify-between gap-2">
                  <div>
                    <p className="text-sm font-semibold text-stone-900">{graft.rootstock.name}</p>
                    <p className="text-xs italic text-stone-400">{graft.rootstock.species}</p>
                  </div>
                  {isSelected && (
                    <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-600">
                      <svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                      </svg>
                    </div>
                  )}
                </div>

                <div className="mb-3">
                  <div className="mb-1 flex items-center justify-between">
                    <span className="text-xs text-stone-500">Compatibility</span>
                    <span className="text-xs font-semibold text-stone-700">{pct}%</span>
                  </div>
                  <div className="h-1.5 rounded-full bg-stone-100">
                    <div
                      className={`h-1.5 rounded-full ${pct >= 80 ? "bg-emerald-500" : pct >= 60 ? "bg-amber-400" : "bg-red-400"}`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 border-t border-stone-100 pt-3">
                  {[
                    { label: "Vigor", value: `${graft.vigor_boost.toFixed(2)}×` },
                    { label: "Yield", value: `${graft.yield_modifier.toFixed(2)}×` },
                    { label: "Drought", value: `${graft.rootstock.drought_tolerance}/10` },
                  ].map((m) => (
                    <div key={m.label}>
                      <p className="text-[10px] text-stone-400">{m.label}</p>
                      <p className="text-xs font-semibold text-stone-700">{m.value}</p>
                    </div>
                  ))}
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 3 — Select Soil
// ---------------------------------------------------------------------------

const SOIL_COLORS: Record<string, string> = {
  sandy: "bg-amber-100 text-amber-800",
  loam: "bg-lime-100 text-lime-800",
  clay: "bg-orange-100 text-orange-800",
  silt: "bg-cyan-100 text-cyan-800",
  peat: "bg-stone-200 text-stone-700",
  chalky: "bg-gray-100 text-gray-700",
};

function Step3({
  soils,
  selected,
  onSelect,
}: {
  soils: SoilProfile[];
  selected: SoilProfile | null;
  onSelect: (s: SoilProfile) => void;
}) {
  return (
    <div>
      <h2 className="text-lg font-semibold text-stone-900">Select soil environment</h2>
      <p className="mt-1 text-sm text-stone-500">
        Choose the soil profile that best represents your growing conditions.
      </p>

      {soils.length === 0 ? (
        <div className="mt-8 rounded-xl border border-dashed border-stone-200 bg-white py-16 text-center">
          <p className="text-sm text-stone-400">No soil profiles found. Make sure the backend is running and seeded.</p>
        </div>
      ) : (
        <div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {soils.map((soil) => {
            const isSelected = selected?.id === soil.id;
            return (
              <button
                key={soil.id}
                onClick={() => onSelect(soil)}
                className={`flex flex-col rounded-xl border-2 bg-white p-4 text-left transition hover:border-emerald-300 hover:shadow-sm ${
                  isSelected ? "border-emerald-600 shadow-md ring-2 ring-emerald-100" : "border-stone-200"
                }`}
              >
                <div className="mb-3 flex items-start justify-between gap-2">
                  <div>
                    <p className="text-sm font-semibold text-stone-900">{soil.name}</p>
                    <div className="mt-1.5 flex flex-wrap gap-1.5">
                      <Badge label={soil.soil_type} className={SOIL_COLORS[soil.soil_type] ?? "bg-stone-100 text-stone-700"} />
                      <Badge label={soil.climate_zone} className="bg-teal-100 text-teal-800" />
                    </div>
                  </div>
                  {isSelected && (
                    <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-600">
                      <svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                      </svg>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-x-3 gap-y-2">
                  {[
                    { label: "pH", value: soil.ph_level },
                    { label: "Salinity", value: `${soil.salinity_level} dS/m` },
                    { label: "Org. Matter", value: `${soil.organic_matter_percent}%` },
                    { label: "Temp Range", value: `${soil.temperature_range_min}–${soil.temperature_range_max}°C` },
                  ].map((m) => (
                    <div key={m.label}>
                      <p className="text-[10px] text-stone-400">{m.label}</p>
                      <p className="text-xs font-semibold text-stone-700">{m.value}</p>
                    </div>
                  ))}
                </div>

                {soil.description && (
                  <p className="mt-3 line-clamp-2 text-xs leading-relaxed text-stone-400">
                    {soil.description}
                  </p>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Scenario name input with Tab-to-accept ghost suggestion
// ---------------------------------------------------------------------------

function ScenarioNameInput({
  value,
  suggestion,
  onChange,
}: {
  value: string;
  suggestion: string;
  onChange: (v: string) => void;
}) {
  const inputRef = useRef<HTMLInputElement>(null);

  // Ghost text: only show the part of the suggestion that hasn't been typed yet
  const ghostSuffix =
    value === ""
      ? suggestion
      : suggestion.toLowerCase().startsWith(value.toLowerCase())
        ? suggestion.slice(value.length)
        : "";

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Tab" && ghostSuffix) {
      e.preventDefault();
      onChange(value === "" ? suggestion : value + ghostSuffix);
    }
  }

  return (
    <div className="relative mt-1.5">
      {/* Ghost suggestion layer */}
      {ghostSuffix && (
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 flex items-center px-3 py-2.5"
        >
          <span className="text-sm text-transparent">{value}</span>
          <span className="text-sm text-stone-300">{ghostSuffix}</span>
        </div>
      )}
      <input
        ref={inputRef}
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder={value === "" ? "" : suggestion}
        className="w-full rounded-lg border border-stone-200 bg-transparent px-3 py-2.5 text-sm text-stone-900 placeholder:text-stone-400 focus:border-emerald-400 focus:outline-none focus:ring-2 focus:ring-emerald-100"
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 4 — Care Protocol
// ---------------------------------------------------------------------------

function Slider({
  label,
  unit,
  value,
  min,
  max,
  step = 1,
  onChange,
  hint,
}: {
  label: string;
  unit: string;
  value: number;
  min: number;
  max: number;
  step?: number;
  onChange: (v: number) => void;
  hint?: string;
}) {
  return (
    <div>
      <div className="mb-2 flex items-center justify-between">
        <label className="text-sm font-medium text-stone-700">
          {label}
          {hint && <span className="ml-1.5 text-xs font-normal text-stone-400">{hint}</span>}
        </label>
        <span className="rounded-lg bg-emerald-50 px-2.5 py-0.5 text-sm font-semibold text-emerald-800">
          {value} {unit}
        </span>
      </div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="h-2 w-full cursor-pointer appearance-none rounded-full bg-stone-200 accent-emerald-700"
      />
      <div className="mt-1 flex justify-between text-xs text-stone-400">
        <span>{min}</span>
        <span>{max}</span>
      </div>
    </div>
  );
}

const IRRIGATION_OPTIONS = [
  { value: "drip", label: "Drip", desc: "Targeted, efficient" },
  { value: "sprinkler", label: "Sprinkler", desc: "Overhead coverage" },
  { value: "flood", label: "Flood", desc: "Surface saturation" },
  { value: "rainfed", label: "Rain-fed", desc: "No irrigation" },
] as const;

const SEASONS = ["spring", "summer", "autumn", "winter"] as const;

function Step4({
  selectedPlant,
  selectedSoil,
  form,
  onChange,
}: {
  selectedPlant: Plant;
  selectedSoil: SoilProfile;
  form: CareForm;
  onChange: (updates: Partial<CareForm>) => void;
}) {
  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-lg font-semibold text-stone-900">Configure care protocol</h2>
        <p className="mt-1 text-sm text-stone-500">
          Set your fertilisation plan, irrigation method, and season. The AI will assess these against your soil and plant selection.
        </p>
      </div>

      {/* Scenario name with Tab-to-accept suggestion */}
      <div>
        <label className="text-sm font-medium text-stone-700">Scenario Name</label>
        <ScenarioNameInput
          value={form.scenarioName}
          suggestion={`${selectedPlant.name} in ${selectedSoil.name}`}
          onChange={(v) => onChange({ scenarioName: v })}
        />
        <p className="mt-1.5 text-xs text-stone-400">
          Press <kbd className="rounded border border-stone-200 bg-stone-50 px-1 py-0.5 font-mono text-xs text-stone-500">Tab</kbd> to accept suggestion
        </p>
      </div>

      {/* NPK */}
      <div>
        <h3 className="mb-4 text-sm font-semibold text-stone-700">Fertilisation (kg / ha)</h3>
        <div className="space-y-6">
          <Slider label="Nitrogen (N)" unit="kg/ha" value={form.nitrogen} min={0} max={300} onChange={(v) => onChange({ nitrogen: v })} hint="primary growth driver" />
          <Slider label="Phosphorus (P)" unit="kg/ha" value={form.phosphorus} min={0} max={200} onChange={(v) => onChange({ phosphorus: v })} hint="root development" />
          <Slider label="Potassium (K)" unit="kg/ha" value={form.potassium} min={0} max={200} onChange={(v) => onChange({ potassium: v })} hint="fruit quality &amp; stress resistance" />
        </div>
      </div>

      {/* Irrigation method */}
      <div>
        <h3 className="mb-3 text-sm font-semibold text-stone-700">Irrigation Method</h3>
        <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
          {IRRIGATION_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              onClick={() => onChange({ irrigationMethod: opt.value })}
              className={`rounded-xl border-2 p-3 text-left transition ${
                form.irrigationMethod === opt.value
                  ? "border-emerald-600 bg-emerald-50 ring-2 ring-emerald-100"
                  : "border-stone-200 bg-white hover:border-stone-300"
              }`}
            >
              <p className="text-xs sm:text-sm font-semibold text-stone-900">{opt.label}</p>
              <p className="text-[10px] sm:text-xs text-stone-500">{opt.desc}</p>
            </button>
          ))}
        </div>
      </div>

      {/* Irrigation frequency + Season + Duration */}
      <div className="grid gap-6 sm:grid-cols-2">
        <Slider
          label="Irrigation Frequency"
          unit="days"
          value={form.irrigationFrequencyDays}
          min={1}
          max={14}
          onChange={(v) => onChange({ irrigationFrequencyDays: v })}
          hint="interval between waterings"
        />
        <div>
          <h3 className="mb-3 text-sm font-semibold text-stone-700">Growing Season</h3>
          <div className="flex gap-2">
            {SEASONS.map((s) => (
              <button
                key={s}
                onClick={() => onChange({ season: s })}
                className={`flex-1 rounded-lg border-2 py-2 text-xs font-medium capitalize transition ${
                  form.season === s
                    ? "border-emerald-600 bg-emerald-50 text-emerald-800"
                    : "border-stone-200 bg-white text-stone-600 hover:border-stone-300"
                }`}
              >
                {s}
              </button>
            ))}
          </div>
        </div>
      </div>

      <Slider
        label="Simulation Duration"
        unit="days"
        value={form.durationDays}
        min={30}
        max={365}
        step={5}
        onChange={(v) => onChange({ durationDays: v })}
        hint="total grow period to model"
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Plant growing loading overlay
// ---------------------------------------------------------------------------

const GROWTH_STAGES = [
  "Seeding scenario…",
  "Analysing soil chemistry…",
  "Modelling root development…",
  "Simulating graft union…",
  "Projecting yield outcomes…",
  "Finalising AI analysis…",
];

function PlantGrowingOverlay({ stageIndex: _ }: { stageIndex: number }) {

  // Stem draws from y=1000 (bottom) up to y=10 (top) over ANIM_DUR seconds.
  // Leaf delay = time for stem to reach that y coordinate.
  const STEM_LEN = 1040;
  const ANIM_DUR = 30;

  const leaves: Array<{ y: number; side: -1 | 1; rot: number }> = [
    { y: 880, side: -1, rot: -42 },
    { y: 760, side:  1, rot:  38 },
    { y: 640, side: -1, rot: -48 },
    { y: 510, side:  1, rot:  40 },
    { y: 390, side: -1, rot: -50 },
    { y: 260, side:  1, rot:  35 },
    { y: 145, side: -1, rot: -44 },
  ];

  return (
    <>
      {/* Plant SVG pinned to right edge, full viewport height, no background */}
      <svg
        style={{
          position: "fixed",
          right: 0,
          top: 0,
          width: 88,
          height: "100dvh",
          zIndex: 50,
          pointerEvents: "none",
          transform: "scaleX(-1)",
        }}
        viewBox="0 0 88 1000"
        preserveAspectRatio="none"
      >
        {/* Main stem — slightly wavy, grows from bottom to top */}
        <path
          d="M44 1000 C42 910 48 820 40 730 C32 640 50 550 43 460 C36 370 51 280 43 190 C36 120 46 55 44 10"
          fill="none"
          stroke="#03ff94"
          strokeWidth="3.5"
          strokeLinecap="round"
          style={{
            strokeDasharray: STEM_LEN,
            strokeDashoffset: STEM_LEN,
            animation: `plant-stem ${ANIM_DUR}s linear forwards`,
          }}
        />

        {/* Leaves — pop in as stem passes each height */}
        {leaves.map((leaf, i) => {
          // lx: leaf group origin offset horizontally from stem
          const lx = leaf.side === -1 ? 18 : 70;
          const delay = (ANIM_DUR * (1000 - leaf.y) / 990).toFixed(1);
          return (
            <g key={i} transform={`translate(${lx}, ${leaf.y}) rotate(${leaf.rot})`}>
              <ellipse
                cx={0} cy={0}
                rx={17} ry={8}
                fill="rgba(3,255,148,0.72)"
                style={{
                  transformOrigin: "0px 0px",
                  animation: `leaf-pop 0.5s ${delay}s ease-out both`,
                }}
              />
              {/* Leaf midrib */}
              <line
                x1={leaf.side === -1 ? -14 : 14} y1={0}
                x2={0} y2={0}
                stroke="rgba(3,255,148,0.35)"
                strokeWidth="1"
                style={{
                  transformOrigin: "0px 0px",
                  animation: `leaf-pop 0.5s ${delay}s ease-out both`,
                }}
              />
            </g>
          );
        })}
      </svg>

      <style>{`
        @keyframes plant-stem {
          from { stroke-dashoffset: ${STEM_LEN}; }
          to   { stroke-dashoffset: 0; }
        }
        @keyframes leaf-pop {
          from { opacity: 0; transform: scale(0); }
          to   { opacity: 1; transform: scale(1); }
        }
        @keyframes fade-in {
          from { opacity: 0; transform: translateY(4px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </>
  );
}

// ---------------------------------------------------------------------------
// Step 5 — Review & Run
// ---------------------------------------------------------------------------

function ReviewRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-center justify-between py-2.5 gap-1">
      <span className="text-xs sm:text-sm text-stone-500">{label}</span>
      <span className="text-sm font-medium text-stone-900">{value}</span>
    </div>
  );
}

function Step5({
  selectedPlant,
  selectedGraft,
  selectedSoil,
  form,
  onRun,
  loading,
  error,
  stageText,
}: {
  selectedPlant: Plant;
  selectedGraft: GraftCombination | null;
  selectedSoil: SoilProfile;
  form: CareForm;
  onRun: () => void;
  loading: boolean;
  error: string | null;
  stageText: string | null;
}) {
  const name = form.scenarioName || `${selectedPlant.name} in ${selectedSoil.name}`;

  return (
    <div>
      <h2 className="text-lg font-semibold text-stone-900">Review & run simulation</h2>
      <p className="mt-1 text-sm text-stone-500">
        Confirm your selections and run the AI analysis. This usually takes 10–20 seconds.
      </p>

      <div className="mt-6 space-y-4">
        {/* Plant & Graft */}
        <div className="rounded-xl border border-stone-200 bg-white px-5 divide-y divide-stone-100">
          <p className="py-3 text-xs font-semibold uppercase tracking-wider text-stone-400">Plant Setup</p>
          <ReviewRow label="Scenario Name" value={name} />
          <ReviewRow label="Scion" value={`${selectedPlant.name} (${selectedPlant.species})`} />
          <ReviewRow
            label="Rootstock"
            value={
              selectedGraft ? (
                <span className="flex items-center gap-1.5">
                  {selectedGraft.rootstock.name}
                  <Badge
                    label={`${Math.round(selectedGraft.compatibility_score * 100)}% match`}
                    className="bg-emerald-100 text-emerald-800"
                  />
                </span>
              ) : (
                <span className="text-stone-400">Ungrafted</span>
              )
            }
          />
        </div>

        {/* Soil */}
        <div className="rounded-xl border border-stone-200 bg-white px-5 divide-y divide-stone-100">
          <p className="py-3 text-xs font-semibold uppercase tracking-wider text-stone-400">Soil Environment</p>
          <ReviewRow label="Profile" value={selectedSoil.name} />
          <ReviewRow label="Type" value={<span className="capitalize">{selectedSoil.soil_type}</span>} />
          <ReviewRow label="Climate" value={selectedSoil.climate_zone} />
          <ReviewRow label="pH" value={selectedSoil.ph_level} />
        </div>

        {/* Care */}
        <div className="rounded-xl border border-stone-200 bg-white px-5 divide-y divide-stone-100">
          <p className="py-3 text-xs font-semibold uppercase tracking-wider text-stone-400">Care Protocol</p>
          <ReviewRow label="Nitrogen" value={`${form.nitrogen} kg/ha`} />
          <ReviewRow label="Phosphorus" value={`${form.phosphorus} kg/ha`} />
          <ReviewRow label="Potassium" value={`${form.potassium} kg/ha`} />
          <ReviewRow label="Irrigation" value={<span className="capitalize">{form.irrigationMethod} · every {form.irrigationFrequencyDays} day{form.irrigationFrequencyDays > 1 ? "s" : ""}</span>} />
          <ReviewRow label="Season" value={<span className="capitalize">{form.season}</span>} />
          <ReviewRow label="Duration" value={`${form.durationDays} days`} />
        </div>
      </div>

      {error && (
        <div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {error}
        </div>
      )}

      {/* Action button is now handled by the global builder navigation bar */}

      {stageText && (
        <>
          <style>{`@keyframes fade-in{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:translateY(0)}}`}</style>
          <p
            key={stageText}
            className="mt-3 text-center text-xs font-semibold uppercase tracking-widest"
            style={{ color: "#007359", animation: "fade-in 0.4s ease-out" }}
          >
            {stageText}
          </p>
        </>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// ScenarioBuilder — orchestrator
// ---------------------------------------------------------------------------

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";

const DEFAULT_FORM: CareForm = {
  scenarioName: "",
  nitrogen: 150,
  phosphorus: 80,
  potassium: 120,
  irrigationMethod: "drip",
  irrigationFrequencyDays: 3,
  season: "spring",
  durationDays: 120,
};

export default function ScenarioBuilder({
  plants,
  soils,
  grafts,
}: {
  plants: Plant[];
  soils: SoilProfile[];
  grafts: GraftCombination[];
}) {
  const router = useRouter();
  const [step, setStep] = useState<Step>(1);
  const [selectedPlant, setSelectedPlant] = useState<Plant | null>(null);
  const [selectedGraft, setSelectedGraft] = useState<GraftCombination | null>(null);
  const [graftSkipped, setGraftSkipped] = useState(false);
  const [selectedSoil, setSelectedSoil] = useState<SoilProfile | null>(null);
  const [form, setForm] = useState<CareForm>(DEFAULT_FORM);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [stageIndex, setStageIndex] = useState(0);

  useEffect(() => {
    if (!loading) { setStageIndex(0); return; }
    const id = setInterval(() => setStageIndex((i) => (i + 1) % GROWTH_STAGES.length), 2500);
    return () => clearInterval(id);
  }, [loading]);

  const canNext = useMemo(() => {
    if (step === 1) return selectedPlant !== null;
    if (step === 2) return selectedGraft !== null || graftSkipped;
    if (step === 3) return selectedSoil !== null;
    if (step === 4) return true;
    return false;
  }, [step, selectedPlant, selectedGraft, graftSkipped, selectedSoil]);

  function handleNext() {
    if (canNext && step < 5) setStep((s) => (s + 1) as Step);
  }

  function handleBack() {
    if (step > 1) setStep((s) => (s - 1) as Step);
  }

  async function handleRun() {
    if (!selectedPlant || !selectedSoil) return;
    setLoading(true);
    setError(null);

    const name = form.scenarioName.trim() || `${selectedPlant.name} in ${selectedSoil.name}`;

    const body = {
      name,
      graft_combination_id: selectedGraft?.id ?? null,
      plant_id: selectedGraft ? null : selectedPlant.id,
      soil_profile_id: selectedSoil.id,
      applied_nitrogen: form.nitrogen,
      applied_phosphorus: form.phosphorus,
      applied_potassium: form.potassium,
      irrigation_method: form.irrigationMethod,
      irrigation_frequency_days: form.irrigationFrequencyDays,
      season: form.season,
      duration_days: form.durationDays,
    };

    try {
      const res = await fetch(`${API_BASE}/api/scenarios`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.detail ?? `Server error ${res.status}`);
      }
      const scenario = await res.json();
      router.push(`/scenarios/${scenario.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unexpected error. Check that the backend is running.");
      setLoading(false);
    }
  }

  return (
    <div>
      {loading && <PlantGrowingOverlay stageIndex={stageIndex} />}
      <StepIndicator current={step} />

      <div className="rounded-2xl border border-stone-200 bg-white p-4 shadow-sm sm:p-6 lg:p-8">
        {step === 1 && (
          <Step1
            plants={plants}
            selected={selectedPlant}
            onSelect={(p) => {
              setSelectedPlant(p);
              setSelectedGraft(null);
              setGraftSkipped(false);
            }}
          />
        )}
        {step === 2 && selectedPlant && (
          <Step2
            grafts={grafts}
            selectedPlant={selectedPlant}
            selectedGraft={selectedGraft}
            onSelectGraft={(g) => {
              setSelectedGraft(g);
              setGraftSkipped(g === null);
            }}
            onSkip={() => {
              setSelectedGraft(null);
              setGraftSkipped(true);
            }}
          />
        )}
        {step === 3 && (
          <Step3
            soils={soils}
            selected={selectedSoil}
            onSelect={setSelectedSoil}
          />
        )}
        {step === 4 && selectedPlant && selectedSoil && (
          <Step4
            selectedPlant={selectedPlant}
            selectedSoil={selectedSoil}
            form={form}
            onChange={(updates) => setForm((f) => ({ ...f, ...updates }))}
          />
        )}
        {step === 5 && selectedPlant && selectedSoil && (
          <Step5
            selectedPlant={selectedPlant}
            selectedGraft={selectedGraft}
            selectedSoil={selectedSoil}
            form={form}
            onRun={handleRun}
            loading={loading}
            error={error}
            stageText={loading ? GROWTH_STAGES[stageIndex] : null}
          />
        )}
      </div>

      {/* Edge-to-edge fixed bottom bar — content aligned with page sections. */}
      <div className="fixed inset-x-0 bottom-0 z-50 border-t border-stone-200 bg-white/80 pb-6 pt-4 shadow-[0_-4px_20px_rgba(0,0,0,0.05)] backdrop-blur-md sm:py-4">
        <div className="mx-auto flex max-w-5xl items-center gap-3 px-6 lg:px-8">
          <button
            onClick={handleBack}
            disabled={step === 1 || loading}
            className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border border-stone-200 bg-white text-stone-700 shadow-sm transition hover:bg-stone-50 active:scale-95 disabled:opacity-30"
            aria-label="Go back"
          >
            <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18" />
            </svg>
          </button>

          <div className="flex min-w-0 flex-1">
            {step < 5 ? (
              <button
                onClick={handleNext}
                disabled={!canNext || loading}
                style={{ backgroundColor: "#03ff94", color: "#1c3d36" }}
                className="flex h-12 w-full min-w-0 items-center justify-center gap-2 rounded-xl px-5 text-sm font-bold shadow-sm transition hover:opacity-90 active:scale-[0.98] disabled:opacity-30"
              >
                <span className="truncate">{step === 4 ? "Review Selection" : "Continue"}</span>
                <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
                </svg>
              </button>
            ) : (
              <button
                onClick={handleRun}
                disabled={loading}
                style={{ backgroundColor: "#03ff94", color: "#1c3d36" }}
                className="flex h-12 w-full min-w-0 items-center justify-center gap-2 rounded-xl px-5 text-sm font-bold shadow-sm transition hover:opacity-90 active:scale-[0.98] disabled:opacity-30"
              >
                <span className="truncate">{loading ? "Analysing..." : "Run Simulation"}</span>
                {!loading && (
                  <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
                  </svg>
                )}
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="h-24" />
    </div>
  );
}
