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

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

type ClaimSlot = {
  id: string;
  name: string;
  status: "dim" | "pending";
};

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

const STEP_META: Record<OnboardingStep, { title: string; label: string; icon: typeof Sparkles; detail: string }> = {
  1: { title: "Name + claim your hex", label: "Identity and ownership", icon: Sparkles, detail: "The center hex is yours. It cannot be moved. It cannot be taken." },
  2: { title: "Plant your Inner Circle", label: "Six anchors, chosen once", icon: UserRoundPlus, detail: "You start with 6. Claim them or skip for now — the claim is bidirectional." },
  3: { title: "First cart — Food", label: "How you eat", icon: UtensilsCrossed, detail: "Add at least one food item. The first 3 items are bonus-weighted." },
  4: { title: "First cart — Activities", label: "How you spend energy", icon: Bike, detail: "Add at least one activity item. The first 3 items are bonus-weighted." },
  5: { title: "First cart — Habitat", label: "How your space speaks", icon: Home, detail: "Add at least one habitat item. The first 3 items are bonus-weighted." },
  6: { title: "Your constellation begins", label: "Nine planted seeds", icon: Clock3, detail: "You've planted 9. The cascade begins. Check back in an hour." },
  7: { title: "First return — The Current", label: "Ambient discovery", icon: Sparkles, detail: "Welcome back. Your atmosphere is live — warm hexes, new people, and passive discovery." },
};

const STEP_PILLARS = [
  { title: "Center", text: "Claim the fixed center hex." },
  { title: "Inner Circle", text: "Choose 6 anchors; claims can remain pending." },
  { title: "Cart", text: "Plant 3 Food, 3 Activities, 3 Habitat seeds." },
  { title: "Current", text: "After 9 seeds, the field begins to breathe hourly." },
] as const;

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

const CATEGORY_META: Record<CartCategoryKey, { label: string; icon: string; accent: string; prompt: string; examples: string[] }> = {
  food: {
    label: "Food",
    icon: "🍜",
    accent: "#d4a574",
    prompt: "Tell us how you eat.",
    examples: ["Ramen Bar X", "Farmers market on Saturdays", "My own cooking"],
  },
  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"],
  },
  habitat: {
    label: "Habitat",
    icon: "🪴",
    accent: "#9ac18a",
    prompt: "Tell us about your space.",
    examples: ["My plants (14 and counting)", "Minimalist kitchen", "Bookshelf I actually use"],
  },
};

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

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

function categorySignal(category: CartCategoryKey) {
  if (category === "food") return "hearts" as const;
  if (category === "activities") return "stars" as const;
  return "moons" as const;
}

function warmthTone(warmth: "hot" | "warm" | "cool") {
  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 === "dim" ? "dim" : "person",
      label: slot.name,
    });
  });

  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, 11),
        resonanceSignal: categorySignal(item.category),
      });
    });
  }

  if (step >= 7) {
    CURRENT_PREVIEW.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 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">
        {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 SummaryBadge({ title, text }: { title: string; text: string }) {
  return (
    <div className="rounded-2xl border border-white/10 bg-white/5 p-3">
      <div className="text-xs uppercase tracking-[0.18em] text-white/45">{title}</div>
      <div className="mt-1 text-sm text-white/80">{text}</div>
    </div>
  );
}

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

export default function OnboardingFlow({
  title = "Cascade Onboarding",
  subtitle = "Onboarding is not a tutorial. It is the first act of the game.",
  initialName = "",
  onComplete,
}: OnboardingFlowProps) {
  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 plantedCount = 1 + claimed.length + seeds.length;
  const claimedCount = claimed.length;
  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 activeCategory = step === 3 ? "food" : step === 4 ? "activities" : step === 5 ? "habitat" : selectedCategory;
  const canUnlockNext =
    (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 currentStep = STEP_META[step];
  const nodes = useMemo(
    () => buildNodes(step, name, INNER_CIRCLE.map((slot) => ({ ...slot, status: claimed.includes(slot.id) ? "pending" : "dim" })), seeds),
    [claimed, name, seeds, step],
  );

  const next = () => {
    if (!canUnlockNext) 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 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 currentTone = step >= 7 ? warmthTone("warm") : warmthTone("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">
              <SummaryBadge title="Step" text={`${step}/7`} />
              <SummaryBadge title="Seeds planted" text={`${plantedCount}`} />
              <SummaryBadge title="Inner circle" text={`${claimedCount}/6`} />
              <SummaryBadge title="Current" text={step >= 7 ? "Live" : "Forming"} />
            </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;
              return (
                <StepCard
                  key={key}
                  active={step === number}
                  done={number < step || (number === 1 && name.trim().length > 0) || (number === 2 && claimedCount > 0) || (number === 3 && categoryCounts.food > 0) || (number === 4 && categoryCounts.activities > 0) || (number === 5 && categoryCounts.habitat > 0)}
                  icon={meta.icon}
                  title={`${number}`}
                  label={meta.label}
                  onClick={() => setStep(number)}
                />
              );
            })}
          </div>

          <div className="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            {STEP_PILLARS.map((pillar) => (
              <div key={pillar.title} className="rounded-2xl border border-white/10 bg-white/5 p-4">
                <div className="text-xs uppercase tracking-[0.18em] text-white/45">{pillar.title}</div>
                <div className="mt-1 text-sm text-white/78">{pillar.text}</div>
              </div>
            ))}
          </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)]">
                  <currentStep.icon className="h-4 w-4" />
                  {currentStep.title}
                </div>
                <p className="mt-1 text-sm text-white/65">{currentStep.detail}</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">{claimedCount}/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" : "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 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.status === "pending" ? "claim pending" : "dim slot"}</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 ? <Check className="h-4 w-4" /> : <Clock3 className="h-4 w-4" />}
                          {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).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>
                  ))}
                  {seeds.filter((item) => item.category === activeCategory).length === 0 && (
                    <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={!canUnlockNext}
                    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">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">{categoryCounts.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">{categoryCounts.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">{categoryCounts.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={back} 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={next} disabled={!canUnlockNext} 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_PREVIEW.map((person) => {
                    const tone = warmthTone(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-2">
                          <div className="text-sm font-medium text-white">{person.name}</div>
                          <span className="text-lg">{tone.icon}</span>
                        </div>
                        <div className="mt-2 text-xs uppercase tracking-[0.18em]" style={{ color: tone.color }}>
                          {person.warmth}
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/65">
                  Tap a warm hex, add someone to your world, or send a care package. Breakdown and profile only unlock as warmth increases.
                </div>
                <div className="max-h-[700px] overflow-auto rounded-[24px] border border-white/10 bg-black/20 p-2">
                  <CurrentAtmosphere />
                </div>
                <div className="flex items-center gap-3">
                  <button type="button" onClick={back} 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={onComplete} 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>
  );
}
