import { useMemo, useState, type CSSProperties } from "react";
import {
  Bike,
  Check,
  CircleCheck,
  CircleDashed,
  Clock3,
  Home,
  MapPinned,
  Plus,
  Search,
  Sparkles,
  UserRoundPlus,
  UtensilsCrossed,
} from "lucide-react";
import HexLattice, { type HexNode } from "./HexLattice";

type CartCategoryKey = "food" | "activities" | "habitat";
type OnboardingStep = 1 | 2 | 3 | 4 | 5 | 6 | 7;
type CurrentWarmth = "hot" | "warm" | "cool";

type ClaimStatus = "dim" | "pending" | "confirmed";

type CurrentPerson = {
  name: string;
  warmth: CurrentWarmth;
  floatLevel: "Rising" | "Airy" | "Drifting" | "Cloud Walking";
  resonanceScore: number;
  signal: "hearts" | "stars" | "moons" | "hourglasses" | "balloons";
  featuredItems: string[];
  cartSummary: Record<CartCategoryKey, string[]>;
};

type SeedItem = {
  id: string;
  category: CartCategoryKey;
  name: string;
};

type ClaimSlot = {
  id: string;
  name: string;
  role: string;
  signal: "hearts" | "stars" | "moons";
};

export interface OnboardingStoryProps {
  title?: string;
  subtitle?: string;
  initialName?: string;
  onComplete?: () => void;
}

const STEP_META: Record<OnboardingStep, { title: string; label: string; icon: typeof Sparkles }> = {
  1: { title: "Name + Claim Your Hex", label: "Center ownership", icon: Sparkles },
  2: { title: "Plant Your Inner Circle", label: "Bidirectional claim", icon: UserRoundPlus },
  3: { title: "First Cart — Food", label: "Food identity", icon: UtensilsCrossed },
  4: { title: "First Cart — Activities", label: "Activity identity", icon: Bike },
  5: { title: "First Cart — Habitat", label: "Habitat identity", icon: Home },
  6: { title: "Your Constellation Begins", label: "Nine planted seeds", icon: Clock3 },
  7: { title: "First Return — The Current", label: "Ambient discovery", icon: Sparkles },
};

const INNER_CIRCLE: ClaimSlot[] = [
  { id: "north", name: "Ari", role: "Anchor", signal: "hearts" },
  { id: "northeast", name: "Sam", role: "Anchor", signal: "stars" },
  { id: "southeast", name: "Jo", role: "Anchor", signal: "moons" },
  { id: "south", name: "Mina", role: "Anchor", signal: "hearts" },
  { id: "southwest", name: "Rae", role: "Anchor", signal: "stars" },
  { id: "northwest", name: "Tae", role: "Anchor", signal: "moons" },
];

const CATEGORY_META: Record<
  CartCategoryKey,
  {
    label: string;
    prompt: string;
    examples: string[];
    accent: string;
    signal: "hearts" | "stars" | "moons";
  }
> = {
  food: {
    label: "Food",
    prompt: "Tell us how you eat.",
    examples: ["Ramen Bar X", "Farmers market on Saturdays", "My own cooking"],
    accent: "#d4a574",
    signal: "hearts",
  },
  activities: {
    label: "Activities",
    prompt: "Tell us how you spend your time.",
    examples: ["Rock climbing on weekends", "Jazz vinyl listening", "Language learning apps"],
    accent: "#8ab6d6",
    signal: "stars",
  },
  habitat: {
    label: "Habitat",
    prompt: "Tell us about your space.",
    examples: ["My plants (14 and counting)", "Minimalist kitchen", "Bookshelf I actually use"],
    accent: "#9ac18a",
    signal: "moons",
  },
};

const CURRENT_SAMPLE: CurrentPerson[] = [
  {
    name: "Mira",
    warmth: "hot",
    floatLevel: "Cloud Walking",
    resonanceScore: 88,
    signal: "hearts",
    featuredItems: ["Ramen Bar X", "Bike rides after sunset", "Ceramic mugs"],
    cartSummary: {
      food: ["Ramen Bar X", "Sour cherries", "Sunday pastries"],
      activities: ["Bike rides after sunset", "Late-night walks", "Film scores on vinyl"],
      habitat: ["Plants near every window", "Soft lighting", "A well-used kitchen"],
    },
  },
  {
    name: "Sol",
    warmth: "warm",
    floatLevel: "Airy",
    resonanceScore: 69,
    signal: "stars",
    featuredItems: ["Jazz vinyl listening", "Indie film nights", "Espresso at 4pm"],
    cartSummary: {
      food: ["Espresso at 4pm", "Farmers market tomatoes", "Lemon tart"],
      activities: ["Jazz vinyl listening", "Indie film nights", "Sketchbook walks"],
      habitat: ["Record shelves", "Open windows", "One perfect lamp"],
    },
  },
  {
    name: "Nadia",
    warmth: "cool",
    floatLevel: "Drifting",
    resonanceScore: 36,
    signal: "moons",
    featuredItems: ["My own cooking", "Secondhand sofa", "Sunday hikes"],
    cartSummary: {
      food: ["My own cooking", "Soup in winter", "Good tomatoes"],
      activities: ["Sunday hikes", "Slow mornings", "Library trips"],
      habitat: ["Secondhand sofa", "Plants in the kitchen", "Warm blankets"],
    },
  },
  {
    name: "Iris",
    warmth: "warm",
    floatLevel: "Rising",
    resonanceScore: 74,
    signal: "hourglasses",
    featuredItems: ["Farmers market on Saturdays", "Language learning apps", "Composting"],
    cartSummary: {
      food: ["Farmers market on Saturdays", "Meal prep Sundays", "Natural wine"],
      activities: ["Language learning apps", "Volunteering", "Long bike rides"],
      habitat: ["Composting", "Books everywhere", "Secondhand furniture"],
    },
  },
  {
    name: "Jun",
    warmth: "hot",
    floatLevel: "Cloud Walking",
    resonanceScore: 92,
    signal: "balloons",
    featuredItems: ["Hiking with my dog", "Gallery openings", "Meal-prepped weekdays"],
    cartSummary: {
      food: ["Meal-prepped weekdays", "Picnic lunches", "Coffee before dawn"],
      activities: ["Hiking with my dog", "Gallery openings", "Climbing gym sessions"],
      habitat: ["A dog bed by the window", "Gear hooks by the door", "Weekend laundry stacks"],
    },
  },
  {
    name: "Luca",
    warmth: "warm",
    floatLevel: "Airy",
    resonanceScore: 61,
    signal: "moons",
    featuredItems: ["Late breakfast", "Weekend markets", "A record player"],
    cartSummary: {
      food: ["Late breakfast", "Green grapes", "Ginger tea"],
      activities: ["Weekend markets", "Morning bike rides", "Reading in cafes"],
      habitat: ["A record player", "Soft rugs", "Windows that open wide"],
    },
  },
];

function makeId(prefix: string) {
  return `${prefix}-${Math.random().toString(36).slice(2, 8)}-${Date.now().toString(36)}`;
}

function initials(name: string) {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .map((part) => part[0]?.toUpperCase())
    .slice(0, 2)
    .join("");
}

function shortLabel(value: string, limit = 16) {
  const compact = value.trim().replace(/\s+/g, " ");
  return compact.length <= limit ? compact : `${compact.slice(0, limit - 1)}…`;
}

function claimStatusLabel(status: ClaimStatus) {
  if (status === "confirmed") return "CONFIRMED";
  if (status === "pending") return "PENDING";
  return "DIM";
}

function warmthMeta(warmth: CurrentWarmth) {
  if (warmth === "hot") return { label: "Hot", icon: "🔥", color: "#fb7185" };
  if (warmth === "warm") return { label: "Warm", icon: "🌡️", color: "#f59e0b" };
  return { label: "Cool", icon: "🌿", color: "#94a3b8" };
}

function statusIcon(status: ClaimStatus) {
  if (status === "confirmed") return <CircleCheck className="h-4 w-4" />;
  if (status === "pending") return <Check className="h-4 w-4" />;
  return <CircleDashed className="h-4 w-4" />;
}

function formatFloatLevel(level: CurrentPerson["floatLevel"]) {
  if (level === "Cloud Walking") return "Top tier, most visible, most trusted.";
  if (level === "Drifting") return "Visible, but still moving through circulation.";
  if (level === "Airy") return "Visible to people in the same direction.";
  return "New enough to be a signal, not a conclusion.";
}

function buildNodes(step: OnboardingStep, name: string, claims: ClaimSlot[], seeds: SeedItem[]) {
  const nodes: HexNode[] = [
    {
      id: "center",
      ring: 0,
      position: 0,
      type: "you",
      label: name.trim() || "YOU",
    },
  ];

  claims.forEach((slot, index) => {
    nodes.push({
      id: slot.id,
      ring: 1,
      position: index,
      type: "person",
      label: slot.name,
      resonanceSignal: slot.signal,
    });
  });

  if (step >= 3) {
    seeds.slice(0, 12).forEach((item, index) => {
      nodes.push({
        id: item.id,
        ring: 2,
        position: index,
        type: "person",
        label: shortLabel(item.name, 12),
        resonanceSignal: CATEGORY_META[item.category].signal,
      });
    });
  }

  if (step >= 7) {
    CURRENT_SAMPLE.forEach((person, index) => {
      nodes.push({
        id: `current-${index}`,
        ring: 6,
        position: index * 6,
        type: person.warmth === "hot" ? "resonance-hot" : person.warmth === "warm" ? "resonance-warm" : "resonance-cool",
        label: initials(person.name),
        resonanceSignal: person.signal,
      });
    });
  }

  return nodes;
}

function categorySummary(items: SeedItem[]) {
  return {
    food: items.filter((item) => item.category === "food").length,
    activities: items.filter((item) => item.category === "activities").length,
    habitat: items.filter((item) => item.category === "habitat").length,
  };
}

function currentOverview(person: CurrentPerson) {
  const warmth = warmthMeta(person.warmth);
  const signalLabel = {
    hearts: "Direct overlap",
    stars: "Category congruence",
    moons: "Complementary rhythm",
    hourglasses: "Values alignment",
    balloons: "Presence + growth",
  }[person.signal];

  return { warmth, signalLabel };
}

export default function OnboardingStory({
  title = "Cascade Onboarding",
  subtitle = "Onboarding is not a tutorial. It is the first act of the game.",
  initialName = "",
  onComplete,
}: OnboardingStoryProps) {
  const [step, setStep] = useState<OnboardingStep>(1);
  const [name, setName] = useState(initialName);
  const [claimedIds, setClaimedIds] = useState<string[]>([]);
  const [drafts, setDrafts] = useState<Record<CartCategoryKey, string>>({ food: "", activities: "", habitat: "" });
  const [seeds, setSeeds] = useState<SeedItem[]>([]);
  const [selectedCurrentId, setSelectedCurrentId] = useState("current-0");
  const [selectedCurrentMode, setSelectedCurrentMode] = useState<"quick" | "breakdown" | "profile">("quick");

  const summary = categorySummary(seeds);
  const plantedCount = 1 + claimedIds.length + seeds.length;
  const activeCategory: CartCategoryKey = step === 3 ? "food" : step === 4 ? "activities" : "habitat";
  const nodes = useMemo(
    () => buildNodes(step, name, INNER_CIRCLE, seeds),
    [name, seeds, step],
  );

  const activeStep = STEP_META[step];
  const canContinue =
    (step === 1 && name.trim().length > 0) ||
    step === 2 ||
    (step === 3 && summary.food > 0) ||
    (step === 4 && summary.activities > 0) ||
    (step === 5 && summary.habitat > 0) ||
    step === 6 ||
    step === 7;

  const selectedCurrent = CURRENT_SAMPLE.find((person, index) => `current-${index}` === selectedCurrentId) ?? CURRENT_SAMPLE[0];
  const selectedCurrentMeta = currentOverview(selectedCurrent);

  const theme = {
    bg: "#09090d",
    panel: "rgba(18, 20, 28, 0.86)",
    card: "rgba(255,255,255,0.04)",
    border: "rgba(255,255,255,0.10)",
    fg: "#f5eadc",
    muted: "rgba(245,234,220,0.68)",
    accent: "#d4a574",
  };

  const handleNext = () => {
    if (!canContinue) return;
    if (step === 7) {
      onComplete?.();
      return;
    }
    setStep((current) => ((current + 1) as OnboardingStep));
  };

  const handleBack = () => {
    setStep((current) => (Math.max(1, current - 1) as OnboardingStep));
  };

  const toggleClaim = (id: string) => {
    setClaimedIds((current) => (current.includes(id) ? current.filter((value) => value !== id) : [...current, id]));
  };

  const addSeed = (category: CartCategoryKey, value: string) => {
    const trimmed = value.trim();
    if (!trimmed) return;

    setSeeds((current) => {
      const duplicate = current.some((item) => item.category === category && item.name.toLowerCase() === trimmed.toLowerCase());
      if (duplicate) return current;
      return [...current, { id: makeId(category), category, name: trimmed }];
    });

    setDrafts((current) => ({ ...current, [category]: "" }));
  };

  const removeSeed = (id: string) => {
    setSeeds((current) => current.filter((item) => item.id !== id));
  };

  const rootStyle: CSSProperties = {
    "--bg": theme.bg,
    "--panel": theme.panel,
    "--card": theme.card,
    "--border": theme.border,
    "--fg": theme.fg,
    "--muted": theme.muted,
    "--accent": theme.accent,
  } as CSSProperties;

  const claimProgress = Math.round((claimedIds.length / 6) * 100);
  const totalSeeds = seeds.length;

  return (
    <main style={rootStyle} className="min-h-screen bg-[var(--bg)] px-5 py-6 text-[var(--fg)] sm:px-6 lg:px-8">
      <div className="mx-auto grid max-w-[1400px] gap-5">
        <header className="rounded-[28px] border border-[var(--border)] bg-[var(--panel)] p-5 shadow-2xl shadow-black/30">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="min-w-0">
              <div className="text-xs uppercase tracking-[0.24em] text-white/45">Cascade / Onboarding</div>
              <h1 className="mt-2 text-3xl font-semibold tracking-tight text-[#f6d9b3]">{title}</h1>
              <p className="mt-2 max-w-3xl text-sm leading-6 text-white/65">{subtitle}</p>
            </div>
            <div className="grid gap-2 text-right text-xs text-white/55">
              <div className="rounded-full border border-white/10 bg-white/5 px-3 py-2">Step {step} of 7</div>
              <div className="rounded-full border border-white/10 bg-white/5 px-3 py-2">{plantedCount} planted</div>
            </div>
          </div>

          <div className="mt-5 grid gap-3 lg:grid-cols-7">
            {Object.entries(STEP_META).map(([key, meta]) => {
              const number = Number(key) as OnboardingStep;
              const done =
                number < step ||
                (number === 1 && name.trim().length > 0) ||
                (number === 2 && claimedIds.length > 0) ||
                (number === 3 && summary.food > 0) ||
                (number === 4 && summary.activities > 0) ||
                (number === 5 && summary.habitat > 0);

              return (
                <button
                  key={key}
                  type="button"
                  onClick={() => setStep(number)}
                  className="flex items-center gap-3 rounded-2xl border px-4 py-3 text-left transition hover:scale-[1.01]"
                  style={{
                    borderColor: step === number ? "rgba(212,165,116,0.60)" : done ? "rgba(154,193,138,0.40)" : "rgba(255,255,255,0.08)",
                    background: step === number ? "rgba(212,165,116,0.12)" : done ? "rgba(154,193,138,0.08)" : "rgba(255,255,255,0.03)",
                  }}
                >
                  <span className="flex h-9 w-9 items-center justify-center rounded-full border border-white/10 bg-white/5">
                    {done ? <Check className="h-4 w-4" /> : <meta.icon className="h-4 w-4" />}
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="block text-sm font-medium text-white">{meta.title}</span>
                    <span className="block text-xs text-white/60">{meta.label}</span>
                  </span>
                </button>
              );
            })}
          </div>
        </header>

        <div className="grid gap-6 lg:grid-cols-[1.06fr_0.94fr]">
          <section className="rounded-[28px] border border-[var(--border)] bg-[var(--panel)] p-5 shadow-2xl shadow-black/30">
            <div className="flex flex-wrap items-center justify-between gap-4">
              <div>
                <div className="flex items-center gap-2 text-sm font-medium text-[var(--accent)]">
                  <activeStep.icon className="h-4 w-4" />
                  {activeStep.title}
                </div>
                <p className="mt-1 text-sm text-white/65">{activeStep.label}</p>
              </div>
              <div className="flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2 text-xs text-white/65">
                {step === 1 ? <MapPinned className="h-3.5 w-3.5" /> : step === 2 ? <UserRoundPlus className="h-3.5 w-3.5" /> : step === 7 ? <Sparkles className="h-3.5 w-3.5" /> : <Clock3 className="h-3.5 w-3.5" />}
                {step === 1 ? "Center hex" : step === 2 ? "Bidirectional claim" : step >= 3 && step <= 5 ? "First cart items" : step === 6 ? "Consolidating" : "Hourly atmosphere"}
              </div>
            </div>

            <div className="mt-5 overflow-hidden rounded-[26px] border border-white/10 bg-[rgba(8,9,13,0.9)] p-4">
              <HexLattice nodes={nodes} size="full" showLabels focusRing={step === 2 ? 1 : step === 7 ? 6 : step >= 3 ? 2 : 0} />
            </div>

            <div className="mt-5 grid gap-3 sm:grid-cols-3">
              <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                <div className="text-xs uppercase tracking-[0.18em] text-white/45">Center</div>
                <div className="mt-1 text-sm text-white">{name.trim() || "Your name goes here"}</div>
                <div className="mt-2 text-xs text-white/55">The center hex is fixed. It cannot be moved or taken.</div>
              </div>
              <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                <div className="text-xs uppercase tracking-[0.18em] text-white/45">Ring 1</div>
                <div className="mt-1 text-sm text-white">{claimedIds.length}/6 claimed</div>
                <div className="mt-2 text-xs text-white/55">Claiming is bidirectional. Pending until mutual.</div>
                <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-white/5">
                  <div className="h-full rounded-full bg-[var(--accent)]" style={{ width: `${claimProgress}%` }} />
                </div>
              </div>
              <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                <div className="text-xs uppercase tracking-[0.18em] text-white/45">Ring 6</div>
                <div className="mt-1 text-sm text-white">{step >= 7 ? "Atmosphere live" : "Forming hourly"}</div>
                <div className="mt-2 text-xs text-white/55">People enter The Current at the hourly tempo.</div>
              </div>
            </div>
          </section>

          <aside className="rounded-[28px] border border-[var(--border)] bg-[var(--panel)] p-5 shadow-2xl shadow-black/30">
            {step === 1 && (
              <div className="space-y-5">
                <div className="rounded-3xl border border-white/10 bg-[var(--card)] p-5">
                  <div className="text-sm font-medium text-white">Welcome to Cascade. You're in the center.</div>
                  <p className="mt-2 text-sm leading-6 text-white/65">The center hex is yours. It cannot be moved. It cannot be taken.</p>
                </div>
                <label className="block">
                  <span className="mb-2 block text-sm text-white/70">Your name</span>
                  <div className="flex items-center gap-2 rounded-2xl border border-white/10 bg-black/20 px-4 py-3">
                    <Search className="h-4 w-4 text-white/35" />
                    <input
                      value={name}
                      onChange={(event) => setName(event.target.value)}
                      placeholder="Enter your name"
                      className="w-full bg-transparent text-sm outline-none placeholder:text-white/30"
                    />
                  </div>
                </label>
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/65">
                  Step 1 establishes ownership and permanence. Everything else grows outward from here.
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="space-y-4">
                <div className="rounded-3xl border border-white/10 bg-[var(--card)] p-5">
                  <div className="text-sm font-medium text-white">You start with 6.</div>
                  <p className="mt-2 text-sm leading-6 text-white/65">These are the people who anchor your world. Choose once. You can skip for now.</p>
                </div>
                <div className="grid gap-3">
                  {INNER_CIRCLE.map((slot) => {
                    const claimed = claimedIds.includes(slot.id);
                    const status: ClaimStatus = claimed ? "pending" : "dim";

                    return (
                      <button
                        type="button"
                        key={slot.id}
                        onClick={() => toggleClaim(slot.id)}
                        className="flex items-center justify-between rounded-2xl border px-4 py-3 text-left transition hover:border-white/20"
                        style={{
                          borderColor: claimed ? "rgba(212,165,116,0.5)" : "rgba(255,255,255,0.08)",
                          background: claimed ? "rgba(212,165,116,0.1)" : "rgba(255,255,255,0.03)",
                        }}
                      >
                        <div>
                          <div className="text-sm font-medium text-white">{slot.name}</div>
                          <div className="text-xs text-white/55">{slot.role} · claim goes {claimed ? "pending" : "dim"}</div>
                        </div>
                        <div className="flex items-center gap-2 text-xs uppercase tracking-[0.18em]" style={{ color: claimed ? "#d4a574" : "rgba(255,255,255,0.48)" }}>
                          {statusIcon(status)}
                          {claimStatusLabel(status)}
                        </div>
                      </button>
                    );
                  })}
                </div>
                <div className="flex gap-3">
                  <button type="button" onClick={() => setClaimedIds([])} className="rounded-full border border-white/10 px-4 py-2 text-sm text-white/70 transition hover:bg-white/5">
                    Clear
                  </button>
                  <button type="button" onClick={handleNext} className="ml-auto rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-black transition hover:opacity-90">
                    Skip for now
                  </button>
                </div>
              </div>
            )}

            {step >= 3 && step <= 5 && (
              <div className="space-y-5">
                <div className="rounded-3xl border border-white/10 bg-[var(--card)] p-5">
                  <div className="flex items-center gap-2 text-sm font-medium text-white">
                    <span>{CATEGORY_META[activeCategory].label === "Food" ? "🍜" : CATEGORY_META[activeCategory].label === "Activities" ? "⛰️" : "🪴"}</span>
                    {CATEGORY_META[activeCategory].prompt}
                  </div>
                  <p className="mt-2 text-sm leading-6 text-white/65">First 3 items in each category are bonus-weighted. They define the initial resonance field.</p>
                </div>
                <label className="block">
                  <span className="mb-2 block text-sm text-white/70">Search bar</span>
                  <div className="flex items-center gap-2 rounded-2xl border border-white/10 bg-black/20 px-4 py-3">
                    <Search className="h-4 w-4 text-white/35" />
                    <input
                      value={drafts[activeCategory]}
                      onChange={(event) => setDrafts((current) => ({ ...current, [activeCategory]: event.target.value }))}
                      placeholder={CATEGORY_META[activeCategory].examples[0]}
                      className="w-full bg-transparent text-sm outline-none placeholder:text-white/30"
                      onKeyDown={(event) => {
                        if (event.key === "Enter") {
                          event.preventDefault();
                          addSeed(activeCategory, drafts[activeCategory]);
                        }
                      }}
                    />
                    <button
                      type="button"
                      onClick={() => addSeed(activeCategory, drafts[activeCategory])}
                      className="rounded-full p-2 text-black transition hover:opacity-90"
                      style={{ background: CATEGORY_META[activeCategory].accent }}
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  </div>
                </label>
                <div className="flex flex-wrap gap-2">
                  {CATEGORY_META[activeCategory].examples.map((example) => (
                    <button
                      key={example}
                      type="button"
                      onClick={() => addSeed(activeCategory, example)}
                      className="rounded-full border border-white/10 bg-white/5 px-3 py-2 text-xs text-white/70 transition hover:bg-white/10"
                    >
                      {example}
                    </button>
                  ))}
                </div>
                <div className="grid gap-2">
                  {seeds.filter((item) => item.category === activeCategory).length > 0 ? (
                    seeds
                      .filter((item) => item.category === activeCategory)
                      .map((item) => (
                        <div key={item.id} className="flex items-center justify-between rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm">
                          <span className="text-white">{item.name}</span>
                          <button type="button" onClick={() => removeSeed(item.id)} className="text-xs text-white/55 transition hover:text-white">
                            Remove
                          </button>
                        </div>
                      ))
                  ) : (
                    <div className="rounded-2xl border border-dashed border-white/10 px-4 py-6 text-center text-sm text-white/45">
                      Add at least one {CATEGORY_META[activeCategory].label.toLowerCase()} item to continue.
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-3">
                  <button
                    type="button"
                    onClick={handleBack}
                    className="rounded-full border border-white/10 px-4 py-2 text-sm text-white/70 transition hover:bg-white/5"
                  >
                    Back
                  </button>
                  <button
                    type="button"
                    onClick={handleNext}
                    disabled={!canContinue}
                    className="ml-auto rounded-full px-4 py-2 text-sm font-medium text-black transition disabled:cursor-not-allowed disabled:opacity-45"
                    style={{ background: "var(--accent)" }}
                  >
                    Continue
                  </button>
                </div>
              </div>
            )}

            {step === 6 && (
              <div className="space-y-5">
                <div className="rounded-3xl border border-white/10 bg-[var(--card)] p-5">
                  <div className="text-sm font-medium text-white">You've planted 9. The cascade begins.</div>
                  <p className="mt-2 text-sm leading-6 text-white/65">Your lattice is now center + R1 claims + 9 cart items. The Current is forming.</p>
                </div>
                <div className="grid gap-3 sm:grid-cols-3">
                  <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                    <div className="text-xs uppercase tracking-[0.18em] text-white/45">Food</div>
                    <div className="mt-1 text-2xl font-semibold text-white">{summary.food}</div>
                  </div>
                  <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                    <div className="text-xs uppercase tracking-[0.18em] text-white/45">Activities</div>
                    <div className="mt-1 text-2xl font-semibold text-white">{summary.activities}</div>
                  </div>
                  <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                    <div className="text-xs uppercase tracking-[0.18em] text-white/45">Habitat</div>
                    <div className="mt-1 text-2xl font-semibold text-white">{summary.habitat}</div>
                  </div>
                </div>
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/65">
                  Check back in an hour to see who has entered your atmosphere.
                </div>
                <div className="flex items-center gap-3">
                  <button type="button" onClick={handleBack} className="rounded-full border border-white/10 px-4 py-2 text-sm text-white/70 transition hover:bg-white/5">
                    Back
                  </button>
                  <button type="button" onClick={handleNext} disabled={!canContinue} className="ml-auto rounded-full px-4 py-2 text-sm font-medium text-black transition disabled:cursor-not-allowed disabled:opacity-45" style={{ background: "var(--accent)" }}>
                    See The Current
                  </button>
                </div>
              </div>
            )}

            {step === 7 && (
              <div className="space-y-5">
                <div className="rounded-3xl border border-white/10 bg-[var(--card)] p-5">
                  <div className="text-sm font-medium text-white">Welcome back. Your atmosphere is live.</div>
                  <p className="mt-2 text-sm leading-6 text-white/65">The Current is the living surface of Cascade — hourly warmth, new people, and passive discovery.</p>
                </div>

                <div className="grid gap-3 sm:grid-cols-3">
                  {CURRENT_SAMPLE.map((person, index) => {
                    const meta = currentOverview(person);
                    const selected = `current-${index}` === selectedCurrentId;
                    return (
                      <button
                        type="button"
                        key={person.name}
                        onClick={() => setSelectedCurrentId(`current-${index}`)}
                        className="rounded-2xl border p-4 text-left transition hover:border-white/20"
                        style={{
                          borderColor: selected ? "rgba(212,165,116,0.55)" : "rgba(255,255,255,0.1)",
                          background: selected ? "rgba(212,165,116,0.1)" : "rgba(255,255,255,0.05)",
                        }}
                      >
                        <div className="flex items-center justify-between gap-2">
                          <div className="text-sm font-medium text-white">{person.name}</div>
                          <span className="text-lg">{meta.warmth.icon}</span>
                        </div>
                        <div className="mt-2 text-xs uppercase tracking-[0.18em]" style={{ color: meta.warmth.color }}>
                          {meta.warmth.label}
                        </div>
                        <div className="mt-2 text-xs text-white/55">{person.floatLevel}</div>
                      </button>
                    );
                  })}
                </div>

                <div className="grid gap-4 rounded-[26px] border border-white/10 bg-[rgba(8,9,13,0.92)] p-4 lg:grid-cols-[1.1fr_0.9fr]">
                  <div className="rounded-[22px] border border-white/10 bg-white/5 p-4">
                    <div className="flex flex-wrap items-center justify-between gap-3">
                      <div>
                        <div className="text-xs uppercase tracking-[0.18em] text-white/45">Selected hex</div>
                        <div className="mt-1 text-lg font-semibold text-white">{selectedCurrent.name}</div>
                      </div>
                      <div className="text-right">
                        <div className="text-2xl font-semibold" style={{ color: selectedCurrentMeta.warmth.color }}>
                          {selectedCurrent.resonanceScore}
                        </div>
                        <div className="text-xs uppercase tracking-[0.18em] text-white/45">{selectedCurrentMeta.warmth.label}</div>
                      </div>
                    </div>

                    <div className="mt-4 flex flex-wrap gap-2">
                      {(["quick", "breakdown", "profile"] as const).map((mode) => (
                        <button
                          key={mode}
                          type="button"
                          onClick={() => setSelectedCurrentMode(mode)}
                          className="rounded-full border px-3 py-1.5 text-xs transition"
                          style={{
                            borderColor: selectedCurrentMode === mode ? "rgba(212,165,116,0.55)" : "rgba(255,255,255,0.12)",
                            background: selectedCurrentMode === mode ? "rgba(212,165,116,0.1)" : "rgba(255,255,255,0.04)",
                            color: selectedCurrentMode === mode ? "#f6d9b3" : "#efe7db",
                          }}
                        >
                          {mode === "quick" ? "Tap 1 · Quick view" : mode === "breakdown" ? "Tap 2 · Resonance breakdown" : "Tap 3 · Full profile"}
                        </button>
                      ))}
                    </div>

                    <div className="mt-4 grid gap-3 sm:grid-cols-3">
                      {selectedCurrent.featuredItems.map((item) => (
                        <div key={item} className="rounded-2xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-white/80">
                          {item}
                        </div>
                      ))}
                    </div>

                    {selectedCurrentMode === "quick" && (
                      <div className="mt-4 rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/70">
                        {selectedCurrent.name} is {selectedCurrentMeta.warmth.label.toLowerCase()} and appears as {selectedCurrent.floatLevel}. Add to my world if you want to keep watching this resonance.
                      </div>
                    )}

                    {selectedCurrentMode === "breakdown" && (
                      <div className="mt-4 rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/70">
                        Their strongest signal is {selectedCurrentMeta.signalLabel.toLowerCase()}. The last 24 hours are being read passively, not pushed as a match.
                      </div>
                    )}

                    {selectedCurrentMode === "profile" && (
                      <div className="mt-4 rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/70">
                        Full profile unlocked: name, float level, featured items, and cart categories at a glance.
                      </div>
                    )}
                  </div>

                  <div className="grid gap-3">
                    <div className="rounded-[22px] border border-white/10 bg-white/5 p-4">
                      <div className="text-xs uppercase tracking-[0.18em] text-white/45">Float level</div>
                      <div className="mt-1 text-lg font-semibold text-white">{selectedCurrent.floatLevel}</div>
                      <div className="mt-2 text-sm text-white/65">{formatFloatLevel(selectedCurrent.floatLevel)}</div>
                    </div>
                    <div className="rounded-[22px] border border-white/10 bg-white/5 p-4">
                      <div className="text-xs uppercase tracking-[0.18em] text-white/45">Cart summary</div>
                      <div className="mt-3 grid gap-2 text-sm text-white/70">
                        <div><span className="text-[var(--accent)]">Food:</span> {selectedCurrent.cartSummary.food.slice(0, 2).join(" · ")}</div>
                        <div><span className="text-[var(--accent)]">Activities:</span> {selectedCurrent.cartSummary.activities.slice(0, 2).join(" · ")}</div>
                        <div><span className="text-[var(--accent)]">Habitat:</span> {selectedCurrent.cartSummary.habitat.slice(0, 2).join(" · ")}</div>
                      </div>
                    </div>
                    <div className="rounded-[22px] border border-white/10 bg-white/5 p-4">
                      <div className="text-xs uppercase tracking-[0.18em] text-white/45">Actions</div>
                      <div className="mt-3 flex flex-wrap gap-2 text-xs">
                        <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1.5">Add to my world</span>
                        <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1.5">Send care package</span>
                        <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1.5">Dismiss</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <button type="button" onClick={handleBack} className="rounded-full border border-white/10 px-4 py-2 text-sm text-white/70 transition hover:bg-white/5">
                    Back
                  </button>
                  <button type="button" onClick={handleNext} className="ml-auto rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-black transition hover:opacity-90">
                    Finish onboarding
                  </button>
                </div>
              </div>
            )}
          </aside>
        </div>
      </div>
    </main>
  );
}
