import { useMemo, useState, type CSSProperties } from "react";
import { Bike, Check, CircleCheck, CircleDashed, Clock3, Home, 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";

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

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

type CurrentPreviewPerson = {
  name: string;
  warmth: CurrentWarmth;
  signal: "hearts" | "stars" | "moons" | "hourglasses" | "balloons";
};

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

const STEP_META: Record<OnboardingStep, { title: string; action: string; icon: typeof Sparkles }> = {
  1: { title: "Name + Claim Your Hex", action: "Enter your name to anchor the center.", icon: Sparkles },
  2: { title: "Plant Your Inner Circle", action: "Claim or skip your first 6 anchors.", icon: UserRoundPlus },
  3: { title: "First Cart — Food", action: "Add at least one food signal.", icon: UtensilsCrossed },
  4: { title: "First Cart — Activities", action: "Add at least one activity signal.", icon: Bike },
  5: { title: "First Cart — Habitat", action: "Add at least one habitat signal.", icon: Home },
  6: { title: "Your Constellation Begins", action: "You need 9 planted seeds before the cascade begins.", icon: Clock3 },
  7: { title: "First Return — The Current", action: "Your atmosphere is live.", icon: Sparkles },
};

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

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

const CURRENT_PREVIEW: CurrentPreviewPerson[] = [
  { name: "Mira", warmth: "hot", signal: "hearts" },
  { name: "Sol", warmth: "warm", signal: "stars" },
  { name: "Nadia", warmth: "cool", signal: "moons" },
  { name: "Iris", warmth: "warm", signal: "hourglasses" },
  { name: "Jun", warmth: "hot", signal: "balloons" },
  { name: "Luca", warmth: "warm", signal: "stars" },
];

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 = 12) {
  const trimmed = value.trim().replace(/\s+/g, " ");
  return trimmed.length <= limit ? trimmed : `${trimmed.slice(0, limit - 1)}…`;
}

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

function categorySignal(category: CartCategoryKey) {
  return CATEGORY_META[category].signal;
}

function warmthChip(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 buildNodes(step: OnboardingStep, name: string, claims: ClaimSlot[], seeds: SeedItem[]): HexNode[] {
  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: slot.status === "pending" ? "person" : "dim",
      label: slot.name,
      resonanceSignal: slot.signal,
    });
  });

  if (step >= 3) {
    const positions: Record<CartCategoryKey, number[]> = {
      food: [0, 3, 6],
      activities: [1, 7, 13],
      habitat: [2, 8, 14],
    };

    (Object.keys(positions) as CartCategoryKey[]).forEach((category) => {
      seeds
        .filter((item) => item.category === category)
        .slice(0, 3)
        .forEach((item, index) => {
          nodes.push({
            id: item.id,
            ring: 2,
            position: positions[category][index],
            type: "person",
            label: shortLabel(item.name, 12),
            resonanceSignal: categorySignal(category),
          });
        });
    });
  }

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

  return nodes;
}

function StepCard({
  active,
  done,
  icon: Icon,
  title,
  label,
  onClick,
}: {
  active: boolean;
  done: boolean;
  icon: typeof Sparkles;
  title: string;
  label: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex items-center gap-3 rounded-2xl border px-4 py-3 text-left transition hover:scale-[1.01]"
      style={{
        borderColor: active ? "rgba(212,165,116,0.6)" : done ? "rgba(154,193,138,0.45)" : "rgba(255,255,255,0.08)",
        background: active ? "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 text-white">
        {done ? <Check className="h-4 w-4" /> : <Icon className="h-4 w-4" />}
      </span>
      <span className="min-w-0 flex-1">
        <span className="block text-sm font-medium text-white">{title}</span>
        <span className="block text-xs text-white/60">{label}</span>
      </span>
    </button>
  );
}

function StatBox({ label, value, detail }: { label: string; value: string; detail: string }) {
  return (
    <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
      <div className="text-xs uppercase tracking-[0.18em] text-white/45">{label}</div>
      <div className="mt-1 text-sm font-semibold text-white">{value}</div>
      <div className="mt-2 text-xs leading-5 text-white/55">{detail}</div>
    </div>
  );
}

export default function CascadeOnboardingStoryboard({
  title = "Cascade Onboarding",
  subtitle = "Onboarding is not a tutorial. It is the first act of the game.",
  initialName = "",
  onComplete,
}: CascadeOnboardingStoryboardProps) {
  const [step, setStep] = useState<OnboardingStep>(1);
  const [name, setName] = useState(initialName);
  const [claimed, setClaimed] = useState<string[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<CartCategoryKey>("food");
  const [drafts, setDrafts] = useState<Record<CartCategoryKey, string>>({ food: "", activities: "", habitat: "" });
  const [seeds, setSeeds] = useState<SeedItem[]>([]);

  const categoryCounts = {
    food: seeds.filter((item) => item.category === "food").length,
    activities: seeds.filter((item) => item.category === "activities").length,
    habitat: seeds.filter((item) => item.category === "habitat").length,
  };
  const plantedCount = 1 + claimed.length + seeds.length;
  const canContinue =
    (step === 1 && name.trim().length > 0) ||
    step === 2 ||
    (step === 3 && categoryCounts.food > 0) ||
    (step === 4 && categoryCounts.activities > 0) ||
    (step === 5 && categoryCounts.habitat > 0) ||
    (step === 6 && plantedCount >= 9) ||
    step === 7;

  const activeMeta = STEP_META[step];
  const activeCategory = step === 3 ? "food" : step === 4 ? "activities" : step === 5 ? "habitat" : selectedCategory;
  const latticeNodes = useMemo(
    () => buildNodes(step, name, INNER_CIRCLE.map((slot) => ({ ...slot, status: claimed.includes(slot.id) ? "pending" : "dim" })), seeds),
    [claimed, name, seeds, step],
  );

  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 next = () => {
    if (!canContinue) return;
    if (step === 7) {
      onComplete?.();
      return;
    }
    setStep((current) => Math.min(7, (current + 1) as OnboardingStep));
  };

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

  const toggleClaim = (id: string) => {
    setClaimed((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 currentWarmth = warmthChip(step >= 7 ? "hot" : step >= 6 ? "warm" : "cool");

  return (
    <main
      style={{
        "--bg": theme.bg,
        "--panel": theme.panel,
        "--card": theme.card,
        "--border": theme.border,
        "--fg": theme.fg,
        "--muted": theme.muted,
        "--accent": theme.accent,
      } as CSSProperties}
      className="min-h-screen bg-[var(--bg)] px-4 py-6 text-[var(--fg)] sm:px-6 lg:px-8"
    >
      <div className="mx-auto flex max-w-7xl flex-col gap-6">
        <header className="rounded-[28px] border border-[var(--border)] bg-[var(--panel)] p-6 shadow-2xl shadow-black/30 backdrop-blur">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="max-w-2xl">
              <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs uppercase tracking-[0.24em] text-white/70">
                <Sparkles className="h-3.5 w-3.5" />
                Cascade · Onboarding
              </div>
              <h1 className="text-3xl font-semibold tracking-tight text-white sm:text-4xl">{title}</h1>
              <p className="mt-3 max-w-2xl text-sm leading-6 text-white/68">{subtitle}</p>
            </div>
            <div className="grid min-w-[240px] grid-cols-2 gap-3 text-sm">
              <StatBox label="Step" value={`${step}/7`} detail={activeMeta.title} />
              <StatBox label="Seeds planted" value={`${plantedCount}`} detail="Center + claims + cart items" />
              <StatBox label="Inner circle" value={`${claimed.length}/6`} detail="Claiming is bidirectional" />
              <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                <div className="text-xs uppercase tracking-[0.18em] text-white/45">Current</div>
                <div className="mt-1 text-sm font-semibold text-white">{step >= 7 ? "Live" : step >= 6 ? "Forming" : "Dormant"}</div>
                <div className="mt-2 text-xs leading-5 text-white/55">{currentWarmth.icon} {currentWarmth.label}</div>
              </div>
            </div>
          </div>

          <div className="mt-5 grid gap-2 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 && claimed.length > 0) ||
                (number === 3 && categoryCounts.food > 0) ||
                (number === 4 && categoryCounts.activities > 0) ||
                (number === 5 && categoryCounts.habitat > 0);
              return (
                <StepCard
                  key={key}
                  active={step === number}
                  done={done}
                  icon={meta.icon}
                  title={`${number}`}
                  label={meta.title}
                  onClick={() => setStep(number)}
                />
              );
            })}
          </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)]">
                  <activeMeta.icon className="h-4 w-4" />
                  {activeMeta.title}
                </div>
                <p className="mt-1 text-sm text-white/65">{activeMeta.action}</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 ? <Sparkles className="h-3.5 w-3.5" /> : step === 2 ? <UserRoundPlus className="h-3.5 w-3.5" /> : step >= 3 && step <= 5 ? <Clock3 className="h-3.5 w-3.5" /> : step === 6 ? <Clock3 className="h-3.5 w-3.5" /> : <Sparkles 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={latticeNodes} size="full" showLabels focusRing={step === 2 ? 1 : step === 6 ? 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">{claimed.length}/6 claimed</div>
                <div className="mt-2 text-xs text-white/55">Claiming is bidirectional. Pending until mutual.</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" : step >= 6 ? "Forming" : "Dormant"}</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 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 claimedSlot = claimed.includes(slot.id);
                    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: claimedSlot ? "rgba(212,165,116,0.5)" : "rgba(255,255,255,0.08)",
                          background: claimedSlot ? "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 {claimedSlot ? "pending" : "dim"}</div>
                        </div>
                        <div className="flex items-center gap-2 text-xs uppercase tracking-[0.18em]" style={{ color: claimedSlot ? "#d4a574" : "rgba(255,255,255,0.48)" }}>
                          {claimedSlot ? <CircleCheck className="h-4 w-4" /> : <CircleDashed className="h-4 w-4" />}
                          {statusLabel(claimedSlot ? "pending" : "dim")}
                        </div>
                      </button>
                    );
                  })}
                </div>
                <div className="flex gap-3">
                  <button type="button" onClick={() => setClaimed([])} 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={() => setStep(3)} 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].icon}</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 bg-[var(--accent)] p-2 text-black transition hover:opacity-90"
                    >
                      <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={() => setStep((current) => (current === 3 ? 2 : (current - 1) as OnboardingStep))}
                    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={() => setStep((current) => (current === 5 ? 6 : (current + 1) as OnboardingStep))}
                    disabled={!canContinue}
                    className="ml-auto rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-45"
                    style={{ background: "var(--accent)", color: "#050505" }}
                  >
                    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">The Current is forming. Brief hexes appear in R6 as the lattice breathes for the first time.</p>
                </div>
                <div className="grid gap-3 sm:grid-cols-3">
                  <StatBox label="Food" value={`${categoryCounts.food} planted`} detail="Food items sharpen the first resonance signals." />
                  <StatBox label="Activities" value={`${categoryCounts.activities} planted`} detail="Activity items reveal how you spend your energy." />
                  <StatBox label="Habitat" value={`${categoryCounts.habitat} planted`} detail="Habitat items show how your space speaks." />
                </div>
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/65">
                  The center is fixed. The Inner Circle holds. The cart now starts to shape the atmosphere around you.
                </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">These are people whose carts resonate with yours. Tap to investigate, or keep watching.</p>
                </div>
                <div className="grid gap-3">
                  {CURRENT_PREVIEW.map((person) => {
                    const tone = warmthChip(person.warmth);
                    return (
                      <div key={person.name} className="rounded-2xl border border-white/10 bg-white/5 p-4">
                        <div className="flex items-center justify-between gap-3">
                          <div>
                            <div className="text-sm font-medium text-white">{person.name}</div>
                            <div className="text-xs text-white/55">{person.warmth} · {tone.icon} {tone.label}</div>
                          </div>
                          <div className="text-xs uppercase tracking-[0.18em]" style={{ color: tone.color }}>
                            {person.signal}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/65">
                  Tap any warm hex to see quick view, resonance breakdown, and full profile. Add to My World is the only non-committal action.
                </div>
              </div>
            )}

            <div className="mt-6 flex items-center gap-3">
              <button
                type="button"
                onClick={back}
                disabled={step === 1}
                className="rounded-full border border-white/10 px-4 py-2 text-sm text-white/70 transition hover:bg-white/5 disabled:cursor-not-allowed disabled:opacity-40"
              >
                Back
              </button>
              <button
                type="button"
                onClick={next}
                disabled={!canContinue}
                className="ml-auto rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-45"
                style={{ background: "var(--accent)", color: "#050505" }}
              >
                {step === 7 ? "Complete" : step === 6 ? "Enter The Current" : "Continue"}
              </button>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}
