import { useMemo, useState, type CSSProperties } from "react";
import HexLattice, { type HexNode } from "./HexLattice";

export type RingIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;

export interface RingVisualizationProps {
  title?: string;
  subtitle?: string;
  initialRing?: RingIndex;
  occupancy?: Partial<Record<RingIndex, number>>;
  onRingChange?: (ring: RingDescriptor) => void;
}

interface RingDescriptor {
  ring: RingIndex;
  name: string;
  size: number;
  tempo: string;
  assignment: string;
  root: string;
  nature: string;
  sees: string;
  color: string;
  summary: string;
}

const RINGS: RingDescriptor[] = [
  {
    ring: 0,
    name: "YOU",
    size: 1,
    tempo: "—",
    assignment: "Fixed",
    root: "—",
    nature: "The center. Your identity, your cart, your full resonance profile.",
    sees: "Yourself.",
    color: "#d4a574",
    summary: "The fixed center hex. It cannot be moved or taken.",
  },
  {
    ring: 1,
    name: "Inner Circle",
    size: 6,
    tempo: "Yearly",
    assignment: "Manual claim · bidirectional",
    root: "6",
    nature: "The 6 people who anchor your world. Nearly permanent.",
    sees: "Full cart resonance.",
    color: "#e8c4a0",
    summary: "Claim once. The bond holds until both parties release.",
  },
  {
    ring: 2,
    name: "Archetypes",
    size: 12,
    tempo: "Quarterly",
    assignment: "Manual curation",
    root: "3",
    nature: "Roles, not people. A single person can fill multiple slots.",
    sees: "Category-level resonance.",
    color: "#a8d4a8",
    summary: "Seasonal review. The roles you want present in your life.",
  },
  {
    ring: 3,
    name: "The Longing",
    size: 18,
    tempo: "Monthly",
    assignment: "Auto-fill from circulation",
    root: "9",
    nature: "What you are reaching for in this chapter.",
    sees: "Monthly longing patterns.",
    color: "#7eb8c9",
    summary: "A living list of what your season is asking for.",
  },
  {
    ring: 4,
    name: "The Echo",
    size: 24,
    tempo: "Weekly",
    assignment: "Auto from creative output",
    root: "6",
    nature: "People who reflect your creative output back at you.",
    sees: "Cart + weekly creative output.",
    color: "#c9a8d4",
    summary: "The first ring where what you make is part of the signal.",
  },
  {
    ring: 5,
    name: "The Wave",
    size: 30,
    tempo: "Daily",
    assignment: "Auto from Echo convergence",
    root: "3",
    nature: "People moving in your direction, daily and sustained.",
    sees: "Sustained cart complementarity.",
    color: "#d4a8b4",
    summary: "A pulse of daily confirmation. Momentum becomes visible.",
  },
  {
    ring: 6,
    name: "The Current",
    size: 36,
    tempo: "Hourly",
    assignment: "Auto from Wave alignment",
    root: "9",
    nature: "Ambient social atmosphere. Discovery in real time.",
    sees: "Ambient warmth only.",
    color: "#8a9ba8",
    summary: "The living surface of Cascade. New people enter hourly.",
  },
];

const DEFAULT_OCCUPANCY: Record<RingIndex, number> = {
  0: 1,
  1: 4,
  2: 5,
  3: 7,
  4: 9,
  5: 12,
  6: 16,
};

const RING_COPY: Record<RingIndex, string> = {
  0: "The center is fixed. Everything else grows outward from here.",
  1: "Manual claim. Mutual confirmation. A bond you do not churn.",
  2: "Archetypes are roles. One person can fill several at once.",
  3: "Monthly longing. What the season is asking you to hold close.",
  4: "Weekly echo. The first ring where your output starts to matter.",
  5: "Daily wave. Sustained motion, not a one-off spike.",
  6: "Hourly current. The atmosphere changes as the hour turns.",
};

const RING_SIGNAL_MATRIX: Record<RingIndex, { badge: string; detail: string }> = {
  0: {
    badge: "Center profile",
    detail: "Your cart, your ring, and your full resonance profile live at the center.",
  },
  1: {
    badge: "Full cart",
    detail: "Inner Circle sees every item, every category, and the full resonance field.",
  },
  2: {
    badge: "Category",
    detail: "Archetypes read the type of thing you carry, not just the exact item.",
  },
  3: {
    badge: "Longing",
    detail: "The Longing reads seasonal and monthly patterns that keep returning.",
  },
  4: {
    badge: "Double signal",
    detail: "The Echo sees both your cart and the creative output it reflects.",
  },
  5: {
    badge: "Pulse",
    detail: "The Wave sees sustained daily complementarity and consistent motion.",
  },
  6: {
    badge: "Ambient warmth",
    detail: "The Current sees only hot, warm, or cool atmosphere at a glance.",
  },
};

const RING_MECHANICS: Record<
  RingIndex,
  {
    trigger: string;
    persistence: string;
    governance: string;
  }
> = {
  0: {
    trigger: "Identity is established once and held in place.",
    persistence: "Fixed center",
    governance: "Cannot be moved or taken",
  },
  1: {
    trigger: "Manual claim from both sides.",
    persistence: "Yearly cadence",
    governance: "Bidirectional, nearly permanent",
  },
  2: {
    trigger: "Manual curation of roles and archetypes.",
    persistence: "Quarterly review",
    governance: "One person may fill multiple slots",
  },
  3: {
    trigger: "Auto-fill from circulation when longing rises.",
    persistence: "Monthly cadence",
    governance: "Living list, seasonally updated",
  },
  4: {
    trigger: "Auto from creative output and reflection.",
    persistence: "Weekly cadence",
    governance: "Emerges from what you make",
  },
  5: {
    trigger: "Auto from Echo convergence.",
    persistence: "Daily cadence",
    governance: "Sustained motion, not a spike",
  },
  6: {
    trigger: "Auto from Wave alignment.",
    persistence: "Hourly refresh",
    governance: "Ambient atmosphere, ephemeral",
  },
};

function clamp(value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value));
}

function ringFill(selected: number, total: number) {
  return Math.round(clamp((selected / total) * 100, 0, 100));
}

function slotSummary(ring: RingDescriptor, occupied: number) {
  const empty = Math.max(ring.size - occupied, 0);
  const slotLabel = ring.ring === 1 ? "dim" : "empty";
  return `${occupied}/${ring.size} occupied · ${empty} ${slotLabel}`;
}

function ringDistanceLabel(ring: RingIndex) {
  if (ring === 0) return "Fixed center";
  if (ring === 1) return "Adjacent claim";
  if (ring === 2) return "Quarterly curation";
  if (ring === 3) return "Monthly longing";
  if (ring === 4) return "Weekly echo";
  if (ring === 5) return "Daily wave";
  return "Hourly current";
}

function buildPreviewNodes(ring: RingIndex, occupied: number): HexNode[] {
  const nodes: HexNode[] = [
    {
      id: "ring-center",
      ring: 0,
      position: 0,
      label: "YOU",
      type: "you",
    },
  ];

  if (ring === 0) return nodes;

  const ringMeta = RINGS[ring];
  const count = clamp(occupied, 0, ringMeta.size);

  for (let position = 0; position < ringMeta.size; position += 1) {
    const occupiedSlot = position < count;
    const dimSlot = ring === 1 && !occupiedSlot;

    nodes.push({
      id: `ring-${ring}-${position}`,
      ring,
      position,
      type: occupiedSlot
        ? ring === 6
          ? position % 3 === 0
            ? "resonance-hot"
            : position % 3 === 1
              ? "resonance-warm"
              : "resonance-cool"
          : "person"
        : dimSlot
          ? "dim"
          : "empty",
      label: occupiedSlot ? (ring === 6 ? undefined : `${ring}.${position + 1}`) : dimSlot ? `Dim ${position + 1}` : undefined,
      resonanceSignal: occupiedSlot && ring === 6 ? (position % 3 === 0 ? "hearts" : position % 3 === 1 ? "stars" : "moons") : undefined,
    });
  }

  return nodes;
}

function statTone(ring: RingIndex) {
  return RINGS[ring].color;
}

export default function RingVisualization({
  title = "Ring Visualization",
  subtitle = "A ring-by-ring readout of Cascade — fixed center, mutual claims, and hourly atmosphere.",
  initialRing = 6,
  occupancy,
  onRingChange,
}: RingVisualizationProps) {
  const [selectedRing, setSelectedRing] = useState<RingIndex>(initialRing);

  const counts = useMemo(
    () => ({ ...DEFAULT_OCCUPANCY, ...occupancy }),
    [occupancy],
  );

  const selected = RINGS[selectedRing];
  const selectedCount = counts[selectedRing] ?? DEFAULT_OCCUPANCY[selectedRing];
  const selectedFill = ringFill(selectedCount, selected.size);
  const ringSignal = RING_SIGNAL_MATRIX[selectedRing];
  const previewNodes = useMemo(() => buildPreviewNodes(selectedRing, selectedCount), [selectedCount, selectedRing]);

  const totalCapacity = 126;
  const filledCapacity = RINGS.reduce((sum, ring) => sum + (counts[ring.ring] ?? DEFAULT_OCCUPANCY[ring.ring]), 0) - 1;
  const activeTempo = selected.ring === 6 ? "Fresh every hour" : selected.ring === 1 ? "Set once, held long" : `${selected.tempo} cadence`;
  const dimmedSlots = Math.max(selected.size - selectedCount, 0);
  const dimmedLabel = selectedRing === 1 ? "Dim hexes" : "Empty slots";

  const handleSelect = (ring: RingIndex) => {
    setSelectedRing(ring);
    onRingChange?.(RINGS[ring]);
  };

  const rootStyle: CSSProperties = {
    minHeight: "100%",
    padding: 24,
    background:
      "radial-gradient(circle at top, rgba(212,165,116,0.12), transparent 36%), radial-gradient(circle at 80% 20%, rgba(126,184,201,0.10), transparent 30%), linear-gradient(180deg, #09090d 0%, #111117 100%)",
    color: "#efe7db",
    fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
  };

  const cardStyle: CSSProperties = {
    background: "rgba(21, 22, 28, 0.9)",
    border: "1px solid rgba(255,255,255,0.08)",
    borderRadius: 22,
    boxShadow: "0 20px 50px rgba(0,0,0,0.24)",
  };

  return (
    <div style={rootStyle}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "grid", gap: 18 }}>
        <section style={{ ...cardStyle, padding: 22 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 18, flexWrap: "wrap", alignItems: "flex-start" }}>
            <div style={{ flex: 1, minWidth: 280 }}>
              <div style={{ fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "#9ca3af" }}>Cascade / Ring System</div>
              <h1 style={{ margin: "8px 0 8px", fontSize: 34, lineHeight: 1.05, color: "#f6d9b3" }}>{title}</h1>
              <p style={{ margin: 0, color: "#ada8b6", maxWidth: 820, fontSize: 15, lineHeight: 1.55 }}>{subtitle}</p>
            </div>

            <div style={{ minWidth: 300, maxWidth: 380, flex: 1, padding: 16, borderRadius: 18, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Capacity</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{filledCapacity}/{totalCapacity} outer nodes</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Selected ring</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: selected.color }}>{selected.name}</div>
                </div>
              </div>
              <div style={{ marginTop: 12, height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
                <div
                  style={{
                    width: `${clamp((filledCapacity / totalCapacity) * 100, 0, 100)}%`,
                    height: "100%",
                    borderRadius: 999,
                    background: "linear-gradient(90deg, #d4a574 0%, #7eb8c9 50%, #d4a8b4 100%)",
                    transition: "width 220ms ease",
                  }}
                />
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13, lineHeight: 1.5 }}>
                Room for 126. Grown from 6. Every ring turns on its own tempo.
              </div>
            </div>
          </div>
        </section>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.18fr) minmax(340px, 0.82fr)", gap: 18, alignItems: "start" }}>
          <div style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Select a ring</div>
                  <h2 style={{ margin: "6px 0 0", fontSize: 22 }}>{selected.name}</h2>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {RINGS.map((ring) => (
                    <button
                      key={ring.ring}
                      type="button"
                      onClick={() => handleSelect(ring.ring)}
                      style={{
                        borderRadius: 999,
                        border: ring.ring === selectedRing ? `1px solid ${ring.color}66` : "1px solid rgba(255,255,255,0.12)",
                        background: ring.ring === selectedRing ? `${ring.color}22` : "rgba(255,255,255,0.04)",
                        color: ring.ring === selectedRing ? ring.color : "#efe7db",
                        padding: "8px 12px",
                        fontSize: 12,
                        cursor: "pointer",
                        fontWeight: ring.ring === selectedRing ? 700 : 500,
                      }}
                    >
                      R{ring.ring}
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ borderRadius: 18, overflow: "hidden", border: "1px solid rgba(255,255,255,0.08)", background: "rgba(10, 10, 14, 0.72)" }}>
                <HexLattice
                  nodes={previewNodes}
                  showLabels={selectedRing === 6}
                  size="full"
                  activeNodeId={selectedRing === 0 ? "ring-center" : `ring-${selectedRing}-0`}
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10, marginTop: 14 }}>
                <StatTile label="Size" value={`${selected.size}`} detail={`${selected.root} root · ${selected.tempo} tempo`} tone={selected.color} />
                <StatTile label="Filled" value={`${selectedCount}`} detail={`${selectedFill}% of this ring`} tone={selected.color} />
                <StatTile label={dimmedLabel} value={`${dimmedSlots}`} detail={selectedRing === 1 ? "Markers for dissolved or dormant claims." : "Empty slots wait as part of the lattice."} tone={selected.color} />
                <StatTile label="Assignment" value={selected.assignment} detail={activeTempo} tone={selected.color} />
                <StatTile label="Sees" value={selected.sees} detail={selected.summary} tone={selected.color} />
                <StatTile label="Signal" value={ringSignal.badge} detail={ringSignal.detail} tone={selected.color} />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Outer ring map</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>All seven rings, one lattice</h3>
                </div>
                <div style={{ color: "#c2b7a8", fontSize: 13 }}>Tap a ring to focus its tempo and assignment.</div>
              </div>

              <div style={{ display: "grid", gap: 10 }}>
                {RINGS.map((ring) => {
                  const count = counts[ring.ring] ?? DEFAULT_OCCUPANCY[ring.ring];
                  const fill = ringFill(count, ring.size);
                  const active = ring.ring === selectedRing;

                  return (
                    <button
                      key={ring.ring}
                      type="button"
                      onClick={() => handleSelect(ring.ring)}
                      style={{
                        borderRadius: 18,
                        border: active ? `1px solid ${ring.color}66` : "1px solid rgba(255,255,255,0.08)",
                        background: active ? `${ring.color}14` : "rgba(255,255,255,0.03)",
                        padding: 14,
                        display: "grid",
                        gap: 10,
                        cursor: "pointer",
                        textAlign: "left",
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "flex-start" }}>
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                            <div style={{ width: 14, height: 14, borderRadius: 999, background: ring.color, boxShadow: `0 0 12px ${ring.color}88` }} />
                            <div style={{ fontWeight: 700, fontSize: 15 }}>{ring.name}</div>
                          </div>
                          <div style={{ color: "#a9a3b8", fontSize: 13 }}>{ring.summary}</div>
                        </div>
                        <div style={{ textAlign: "right" }}>
                          <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>R{ring.ring}</div>
                          <div style={{ fontSize: 18, fontWeight: 800, color: ring.color }}>{fill}%</div>
                        </div>
                      </div>

                      <div style={{ height: 8, borderRadius: 999, overflow: "hidden", background: "rgba(255,255,255,0.06)" }}>
                        <div
                          style={{
                            width: `${fill}%`,
                            height: "100%",
                            borderRadius: 999,
                            background: `linear-gradient(90deg, ${ring.color}, rgba(255,255,255,0.82))`,
                            boxShadow: `0 0 18px ${ring.color}55`,
                          }}
                        />
                      </div>
                    </button>
                  );
                })}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Tempo ladder</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>How the lattice slows down toward the center</h3>
                </div>
                <div style={{ color: "#c2b7a8", fontSize: 13 }}>R6 is hourly. R1 is nearly permanent.</div>
              </div>

              <div style={{ display: "grid", gap: 10 }}>
                {RINGS.slice(1).map((ring) => {
                  const mechanics = RING_MECHANICS[ring.ring];
                  const active = ring.ring === selectedRing;

                  return (
                    <div
                      key={ring.ring}
                      style={{
                        borderRadius: 16,
                        padding: 14,
                        background: active ? `${ring.color}14` : "rgba(255,255,255,0.03)",
                        border: active ? `1px solid ${ring.color}66` : "1px solid rgba(255,255,255,0.08)",
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", flexWrap: "wrap" }}>
                        <div>
                          <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>R{ring.ring} · {ring.tempo}</div>
                          <div style={{ marginTop: 4, fontWeight: 700, color: ring.color }}>{ring.name}</div>
                        </div>
                        <div style={{ color: "#d8d0c2", fontSize: 13 }}>{ring.assignment}</div>
                      </div>
                      <div style={{ marginTop: 8, color: "#b6ac9d", fontSize: 13, lineHeight: 1.55 }}>{mechanics.trigger}</div>
                      <div style={{ marginTop: 8, display: "flex", flexWrap: "wrap", gap: 8 }}>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: `${ring.color}18`, color: "#f7efe2", border: `1px solid ${ring.color}44` }}>
                          Root {ring.root}
                        </span>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: "rgba(255,255,255,0.04)", color: "#f7efe2", border: "1px solid rgba(255,255,255,0.12)" }}>
                          {mechanics.persistence}
                        </span>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: "rgba(255,255,255,0.04)", color: "#f7efe2", border: "1px solid rgba(255,255,255,0.12)" }}>
                          {mechanics.governance}
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Selected ring</div>
              <div style={{ marginTop: 12, display: "flex", gap: 14, alignItems: "center" }}>
                <div
                  style={{
                    width: 64,
                    height: 64,
                    borderRadius: 18,
                    display: "grid",
                    placeItems: "center",
                    background: `${selected.color}22`,
                    border: `1px solid ${selected.color}55`,
                    color: selected.color,
                    fontSize: 20,
                    fontWeight: 800,
                  }}
                >
                  R{selected.ring}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.05 }}>{selected.name}</div>
                  <div style={{ color: "#a6a0b1", fontSize: 13, marginTop: 4 }}>{selected.nature}</div>
                </div>
              </div>

              <div style={{ display: "grid", gap: 10, marginTop: 16 }}>
                <InfoRow label="Tempo" value={selected.tempo} tone={selected.color} />
                <InfoRow label="Assignment" value={selected.assignment} tone={selected.color} />
                <InfoRow label="Root" value={selected.root} tone={selected.color} />
                <InfoRow label="Sees" value={selected.sees} tone={selected.color} />
                <InfoRow label={dimmedLabel} value={`${dimmedSlots}`} tone={selected.color} />
              </div>

              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Mechanics</div>
                <div style={{ display: "grid", gap: 10, marginTop: 10 }}>
                  <MechanicRow label="Trigger" value={RING_MECHANICS[selected.ring].trigger} tone={selected.color} />
                  <MechanicRow label="Persistence" value={RING_MECHANICS[selected.ring].persistence} tone={selected.color} />
                  <MechanicRow label="Governance" value={RING_MECHANICS[selected.ring].governance} tone={selected.color} />
                </div>
              </div>

              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Cart signal</div>
                <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
                  <DetailCard title={ringSignal.badge} text={ringSignal.detail} />
                  <DetailCard
                    title="What the signal means"
                    text={selected.ring === 1 ? "R1 sees everything in the cart because trust lives closest to the center." : selected.ring === 6 ? "R6 only sees the temperature of recent signal, not the whole cart." : `Each ring sees a narrower slice of the cart and a slower tempo of trust — ${ringDistanceLabel(selected.ring)}.`}
                  />
                </div>
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>What the ring means</div>
              <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
                <DetailCard
                  title="Selection"
                  text="Tap any ring to focus the lattice. The preview now fills every slot, so you can see occupancy and empty space in context."
                />
                <DetailCard
                  title="Permanence"
                  text="R1 is nearly permanent. R2-R6 can demote or refresh on their own cadence. The ring map keeps that truth visible."
                />
                <DetailCard
                  title="Ghost slots"
                  text={selectedRing === 1 ? "Dim hexes mark the places that were claimed and then released. They stay visible as history." : "Empty slots stay visible in the lattice so the ring never forgets what it can still hold."}
                />
                <DetailCard
                  title="Discovery"
                  text="R6 is the current atmosphere: hourly, ambient, and ephemeral. It is the surface you open first."
                />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Permanence and release</div>
              <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
                <DetailCard
                  title="R1"
                  text="Claimed once, held nearly permanently, and only dissolved by mutual release. Empty R1 hexes stay dim."
                />
                <DetailCard
                  title="R2-R3"
                  text="Roles and longing are reviewed on a slower cadence. They can settle, shift, or return to circulation."
                />
                <DetailCard
                  title="R4-R6"
                  text="Echo, Wave, and Current move quickly enough to feel alive — weekly, daily, and hourly respectively."
                />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Reference</div>
              <div style={{ marginTop: 10, color: "#d8d0c2", lineHeight: 1.6, fontSize: 14 }}>
                {selected.summary}
              </div>
            </section>
          </aside>
        </div>
      </div>
    </div>
  );
}

function StatTile({ label, value, detail, tone }: { label: string; value: string; detail: string; tone: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{label}</div>
      <div style={{ marginTop: 6, fontSize: 20, fontWeight: 800, color: tone, lineHeight: 1.1 }}>{value}</div>
      <div style={{ marginTop: 6, color: "#b6ac9d", fontSize: 13, lineHeight: 1.45 }}>{detail}</div>
    </div>
  );
}

function InfoRow({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center", padding: "10px 12px", borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ color: "#c8bfaf", fontSize: 14 }}>{label}</div>
      <div style={{ color: tone, fontWeight: 800, fontSize: 14 }}>{value}</div>
    </div>
  );
}

function DetailCard({ title, text }: { title: string; text: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{title}</div>
      <div style={{ marginTop: 6, color: "#d8d0c2", fontSize: 14, lineHeight: 1.55 }}>{text}</div>
    </div>
  );
}

function MechanicRow({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "auto 1fr",
        gap: 10,
        alignItems: "center",
        padding: "10px 12px",
        borderRadius: 14,
        background: "rgba(255,255,255,0.03)",
        border: "1px solid rgba(255,255,255,0.08)",
      }}
    >
      <div style={{ fontWeight: 700, color: tone }}>{label}</div>
      <div style={{ color: "rgba(247,239,226,0.72)", fontSize: 12, lineHeight: 1.45 }}>{value}</div>
    </div>
  );
}