import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { Ban, Clock3, Heart, Plus, Search, Sparkles } from "lucide-react";
import HexLattice, { type HexNode } from "./HexLattice";
import ResonanceIndicators, { type ResonanceSignal } from "./ResonanceIndicators";

type CurrentWarmth = "hot" | "warm" | "cool";
type ResonancePattern = "hearts" | "stars" | "moons" | "hourglasses" | "balloons";
type InvestigationMode = "quick" | "breakdown" | "profile";

type CurrentPerson = {
  id: string;
  name: string;
  warmth: CurrentWarmth;
  floatLevel: "Rising" | "Airy" | "Drifting" | "Cloud Walking";
  resonanceScore: number;
  primarySignal: ResonancePattern;
  featuredItems: string[];
  cartSummary: {
    food: string[];
    activities: string[];
    habitat: string[];
  };
  daysInCurrent: number;
  heartsAvailable: number;
  patterns: Array<{
    key: ResonancePattern;
    label: string;
    detail: string;
    active: boolean;
  }>;
};

export interface CurrentSurfaceSpecProps {
  title?: string;
  subtitle?: string;
  people?: CurrentPerson[];
}

const DEFAULT_PEOPLE: CurrentPerson[] = [
  {
    id: "mira",
    name: "Mira",
    warmth: "hot",
    floatLevel: "Cloud Walking",
    resonanceScore: 88,
    primarySignal: "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"],
    },
    daysInCurrent: 11,
    heartsAvailable: 4,
    patterns: [
      { key: "hearts", label: "Direct overlap", detail: "You both have Ramen Bar X and the same evening ritual.", active: true },
      { key: "hourglasses", label: "Values alignment", detail: "Your patterns over the last 90 days moved together.", active: true },
      { key: "balloons", label: "Presence + growth", detail: "Both of you have shown up consistently without drop-off.", active: true },
      { key: "stars", label: "Category congruence", detail: "Your food and activity categories are both adventurous.", active: true },
    ],
  },
  {
    id: "sol",
    name: "Sol",
    warmth: "warm",
    floatLevel: "Airy",
    resonanceScore: 69,
    primarySignal: "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"],
    },
    daysInCurrent: 8,
    heartsAvailable: 2,
    patterns: [
      { key: "stars", label: "Category congruence", detail: "Creative-night rituals and local food routines line up.", active: true },
      { key: "moons", label: "Complementary rhythm", detail: "Your carts fill each other’s dinner-party gap.", active: true },
      { key: "balloons", label: "Presence + growth", detail: "A steady daily pulse keeps the resonance warm.", active: true },
      { key: "hearts", label: "Direct overlap", detail: "A few exact items match, but not enough for the strongest tier.", active: false },
    ],
  },
  {
    id: "nadia",
    name: "Nadia",
    warmth: "cool",
    floatLevel: "Drifting",
    resonanceScore: 36,
    primarySignal: "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"],
    },
    daysInCurrent: 4,
    heartsAvailable: 1,
    patterns: [
      { key: "moons", label: "Complementary rhythm", detail: "Your cart fills the post-hike meal gap beautifully.", active: true },
      { key: "stars", label: "Category congruence", detail: "You both have a grounded homebody orientation.", active: true },
      { key: "hourglasses", label: "Values alignment", detail: "There are hints of the same values, but the signal is still thin.", active: false },
    ],
  },
  {
    id: "iris",
    name: "Iris",
    warmth: "warm",
    floatLevel: "Rising",
    resonanceScore: 74,
    primarySignal: "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"],
    },
    daysInCurrent: 17,
    heartsAvailable: 3,
    patterns: [
      { key: "hourglasses", label: "Values alignment", detail: "The last 90 days show the same worldview and cadence.", active: true },
      { key: "stars", label: "Category congruence", detail: "Your habits and activity categories point in the same direction.", active: true },
      { key: "balloons", label: "Presence + growth", detail: "You both keep returning without needing a reminder.", active: true },
    ],
  },
  {
    id: "jun",
    name: "Jun",
    warmth: "hot",
    floatLevel: "Cloud Walking",
    resonanceScore: 92,
    primarySignal: "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"],
    },
    daysInCurrent: 12,
    heartsAvailable: 5,
    patterns: [
      { key: "balloons", label: "Presence + growth", detail: "This is a sustained daily pulse. The current has teeth.", active: true },
      { key: "hearts", label: "Direct overlap", detail: "There are multiple exact item matches.", active: true },
      { key: "moons", label: "Complementary rhythm", detail: "Your carts complete each other’s adventure arc.", active: true },
      { key: "hourglasses", label: "Values alignment", detail: "The pattern has held long enough to become worldview.", active: true },
    ],
  },
  {
    id: "wren",
    name: "Wren",
    warmth: "cool",
    floatLevel: "Drifting",
    resonanceScore: 28,
    primarySignal: "stars",
    featuredItems: ["Bookshelf I actually use", "Train rides", "Climbing chalk"],
    cartSummary: {
      food: ["Late breakfast", "Seltzer after work", "Trail mix"],
      activities: ["Train rides", "Climbing chalk", "Weekend errands"],
      habitat: ["Bookshelf I actually use", "Small apartment plants", "Lamp in every room"],
    },
    daysInCurrent: 2,
    heartsAvailable: 0,
    patterns: [
      { key: "stars", label: "Category congruence", detail: "A few category-level signals are aligning, but it is still early.", active: true },
      { key: "balloons", label: "Presence + growth", detail: "The signal is still forming and needs more showing up.", active: false },
      { key: "hearts", label: "Direct overlap", detail: "No exact overlaps yet.", active: false },
    ],
  },
  {
    id: "luca",
    name: "Luca",
    warmth: "warm",
    floatLevel: "Airy",
    resonanceScore: 61,
    primarySignal: "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"],
    },
    daysInCurrent: 9,
    heartsAvailable: 2,
    patterns: [
      { key: "moons", label: "Complementary rhythm", detail: "Your timing complements their slower, more spacious rhythm.", active: true },
      { key: "stars", label: "Category congruence", detail: "The two carts are moving in the same general direction.", active: true },
      { key: "hourglasses", label: "Values alignment", detail: "The pattern is repeating enough to matter.", active: false },
    ],
  },
  {
    id: "aya",
    name: "Aya",
    warmth: "hot",
    floatLevel: "Drifting",
    resonanceScore: 81,
    primarySignal: "hourglasses",
    featuredItems: ["Shared dinners", "Museum afternoons", "Plants near every window"],
    cartSummary: {
      food: ["Shared dinners", "Seasonal soups", "Coffee after walks"],
      activities: ["Museum afternoons", "Quiet concerts", "Long calls with friends"],
      habitat: ["Plants near every window", "Secondhand art", "Open shelves"],
    },
    daysInCurrent: 21,
    heartsAvailable: 3,
    patterns: [
      { key: "hourglasses", label: "Values alignment", detail: "The pattern has held long enough to feel like worldview.", active: true },
      { key: "hearts", label: "Direct overlap", detail: "Some exact items are shared and still keep appearing.", active: true },
      { key: "balloons", label: "Presence + growth", detail: "The field brightens every time they show up.", active: true },
      { key: "stars", label: "Category congruence", detail: "The broader categories are resonant as well.", active: true },
    ],
  },
];

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

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 scoreLabel(score: number) {
  if (score >= 81) return "Resonant";
  if (score >= 61) return "Blazing";
  if (score >= 41) return "Hot";
  if (score >= 21) return "Warm";
  return "Cool";
}

function formatUntilNextHour(now: number) {
  const minutes = 60 - new Date(now).getMinutes();
  return `${minutes === 60 ? 0 : minutes}m`;
}

function formatDuration(hours: number) {
  if (hours < 1) return `${Math.max(1, Math.round(hours * 60))}m`;
  if (hours < 24) return `${hours.toFixed(1)}h`;
  return `${Math.round(hours / 24)}d`;
}

function formatClock(now: number) {
  return new Intl.DateTimeFormat("en-US", {
    hour: "numeric",
    minute: "2-digit",
    hour12: false,
  }).format(now);
}

function hashString(value: string) {
  let hash = 0;
  for (let index = 0; index < value.length; index += 1) {
    hash = (hash * 31 + value.charCodeAt(index)) >>> 0;
  }
  return hash;
}

function patternSignals(person?: CurrentPerson): ResonanceSignal[] {
  if (!person) return [];
  return person.patterns.map((pattern, index) => ({
    key: pattern.key,
    score: pattern.active ? Math.max(34, person.resonanceScore - index * 8) : 18,
    note: pattern.detail,
  }));
}

function categoryTone(category: keyof CurrentPerson["cartSummary"]) {
  if (category === "food") return "#d4a574";
  if (category === "activities") return "#8ab6d6";
  return "#9ac18a";
}

function modeLabel(mode: InvestigationMode) {
  if (mode === "quick") return "Tap 1 · Quick view";
  if (mode === "breakdown") return "Tap 2 · Resonance breakdown";
  return "Tap 3 · Full profile";
}

function QueueColumn({
  title,
  hint,
  items,
  activeId,
  onSelect,
  subdued = false,
}: {
  title: string;
  hint: string;
  items: Array<{ id: string; name: string; warmth: CurrentWarmth; note: string }>;
  activeId?: string;
  onSelect: (id: string) => void;
  subdued?: boolean;
}) {
  const warmthColor = (warmth: CurrentWarmth) => (warmth === "hot" ? "#fb7185" : warmth === "warm" ? "#f59e0b" : "#94a3b8");

  return (
    <div style={{ borderRadius: 18, padding: 14, background: subdued ? "rgba(255,255,255,0.02)" : "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 style={{ fontWeight: 700 }}>{title}</div>
        <div style={{ color: "#a7a1b3", fontSize: 12 }}>{items.length} shown</div>
      </div>
      <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 12, lineHeight: 1.5 }}>{hint}</div>
      <div style={{ marginTop: 10, display: "grid", gap: 8 }}>
        {items.length > 0 ? (
          items.map((item) => {
            const color = warmthColor(item.warmth);
            const active = activeId === item.id;
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => onSelect(item.id)}
                style={{
                  borderRadius: 14,
                  border: active ? `1px solid ${color}` : "1px solid rgba(255,255,255,0.08)",
                  background: active ? `${color}14` : "rgba(255,255,255,0.03)",
                  color: "#efe7db",
                  textAlign: "left",
                  padding: 10,
                  cursor: "pointer",
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                  <div style={{ fontWeight: 700 }}>{item.name}</div>
                  <div style={{ color, fontSize: 14 }}>{item.warmth === "hot" ? "🔥" : item.warmth === "warm" ? "🌡️" : "🌿"}</div>
                </div>
                <div style={{ marginTop: 4, color: "#a7a1b3", fontSize: 12, lineHeight: 1.45 }}>{item.note}</div>
              </button>
            );
          })
        ) : (
          <div style={{ borderRadius: 14, padding: 12, background: "rgba(255,255,255,0.02)", border: "1px dashed rgba(255,255,255,0.10)", color: "#a7a1b3", fontSize: 12, lineHeight: 1.5 }}>
            No one is circulating here yet.
          </div>
        )}
      </div>
    </div>
  );
}

function InfoRow({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center" }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{label}</div>
      <div style={{ fontWeight: 700, color: tone, textAlign: "right" }}>{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 ModeButton({ active, label, locked = false, onClick }: { active: boolean; label: string; locked?: boolean; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={locked}
      style={{
        borderRadius: 999,
        border: active ? "1px solid rgba(245, 193, 108, 0.36)" : "1px solid rgba(255,255,255,0.12)",
        background: active ? "rgba(245, 193, 108, 0.16)" : "rgba(255,255,255,0.04)",
        color: locked ? "#8b93a0" : active ? "#ffdca2" : "#efe7db",
        padding: "8px 12px",
        fontSize: 12,
        cursor: locked ? "not-allowed" : "pointer",
        opacity: locked ? 0.6 : 1,
      }}
    >
      {label}
    </button>
  );
}

function ActionButton({
  label,
  helper,
  color,
  active = false,
  disabled = false,
  onClick,
}: {
  label: string;
  helper: string;
  color: string;
  active?: boolean;
  disabled?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      disabled={disabled}
      onClick={onClick}
      style={{
        width: "100%",
        borderRadius: 14,
        border: active ? `1px solid ${color}` : "1px solid rgba(255,255,255,0.12)",
        background: disabled ? "rgba(255,255,255,0.02)" : active ? `${color}20` : "rgba(245, 193, 108, 0.10)",
        color: disabled ? "#87909f" : "#f7efe2",
        textAlign: "left",
        padding: 12,
        cursor: disabled ? "not-allowed" : "pointer",
      }}
    >
      <div style={{ fontWeight: 700 }}>{label}</div>
      <div style={{ marginTop: 4, color: disabled ? "#7e8794" : "#b6ac9d", fontSize: 12, lineHeight: 1.45 }}>{helper}</div>
    </button>
  );
}

export default function CurrentSurfaceSpec({
  title = "The Current",
  subtitle = "The living surface of Cascade — hourly atmosphere, ambient warmth, and the people currently in your social field.",
  people = DEFAULT_PEOPLE,
}: CurrentSurfaceSpecProps) {
  const [now, setNow] = useState(() => Date.now());
  const [selectedId, setSelectedId] = useState(people[0]?.id ?? "");
  const [mode, setMode] = useState<InvestigationMode>("quick");
  const [watchlistIds, setWatchlistIds] = useState<string[]>([]);
  const [packageIds, setPackageIds] = useState<string[]>([]);
  const [longingIds, setLongingIds] = useState<string[]>([]);
  const [echoIds, setEchoIds] = useState<string[]>([]);
  const [dismissedIds, setDismissedIds] = useState<string[]>([]);

  useEffect(() => {
    const interval = setInterval(() => setNow(Date.now()), 60_000);
    return () => clearInterval(interval);
  }, []);

  const hourSeed = Math.floor(now / 3_600_000);
  const selectedPerson = useMemo(() => people.find((person) => person.id === selectedId) ?? people[0], [people, selectedId]);

  const rotationRows = useMemo(
    () =>
      people.map((person, index) => {
        const seed = hashString(person.id) + hourSeed * 17 + index * 13;
        const ageMinutes = seed % (8 * 60);
        const hoursInCurrent = ageMinutes / 60;
        const hoursRemaining = Math.max(0, 6 - hoursInCurrent);
        const autoExpired = ageMinutes >= 6 * 60;
        const dismissed = dismissedIds.includes(person.id);

        return {
          ...person,
          hoursInCurrent,
          hoursRemaining,
          autoExpired,
          dismissed,
          status: dismissed ? "dismissed" : autoExpired ? "circulating" : "active",
          slotRank: (person.warmth === "hot" ? 3 : person.warmth === "warm" ? 2 : 1) * 1000 - hoursInCurrent * 100 - person.resonanceScore,
        };
      }),
    [dismissedIds, hourSeed, people],
  );

  const activePeople = useMemo(
    () => rotationRows.filter((person) => !person.autoExpired && !person.dismissed).sort((a, b) => b.slotRank - a.slotRank),
    [rotationRows],
  );

  const circulatingPeople = useMemo(
    () => rotationRows.filter((person) => person.autoExpired || person.dismissed).sort((a, b) => b.slotRank - a.slotRank),
    [rotationRows],
  );

  const fieldScore = useMemo(() => {
    if (activePeople.length === 0) return 0;
    return Math.round(activePeople.reduce((sum, person) => sum + person.resonanceScore, 0) / activePeople.length);
  }, [activePeople]);

  const expiringSoon = useMemo(
    () => activePeople.filter((person) => person.hoursRemaining > 0 && person.hoursRemaining <= 1).length,
    [activePeople],
  );

  const fieldLabel = scoreLabel(fieldScore);
  const nextRefresh = formatUntilNextHour(now);
  const localClock = formatClock(now);
  const selectedWarmth = warmthMeta(selectedPerson?.warmth ?? "cool");
  const selectedSignals = useMemo(() => (selectedPerson ? patternSignals(selectedPerson) : []), [selectedPerson]);
  const selectedWatch = Boolean(selectedPerson && watchlistIds.includes(selectedPerson.id));
  const selectedPackage = Boolean(selectedPerson && packageIds.includes(selectedPerson.id));
  const selectedLonging = Boolean(selectedPerson && longingIds.includes(selectedPerson.id));
  const selectedEcho = Boolean(selectedPerson && echoIds.includes(selectedPerson.id));
  const selectedDismissed = Boolean(selectedPerson && dismissedIds.includes(selectedPerson.id));
  const fieldStatus = `${activePeople.length}/36 active · ${circulatingPeople.length} circulating · ${expiringSoon} expiring soon`;
  const selectedRow = rotationRows.find((person) => person.id === selectedPerson?.id);

  const currentNodes = useMemo<HexNode[]>(() => {
    const nodes: HexNode[] = [{ id: "center-you", ring: 0, position: 0, label: "CURRENT", type: "you" }];
    const positions = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34];

    activePeople.slice(0, 36).forEach((person, index) => {
      nodes.push({
        id: person.id,
        ring: 6,
        position: positions[index] ?? index,
        label: initials(person.name),
        type: person.warmth === "hot" ? "resonance-hot" : person.warmth === "warm" ? "resonance-warm" : "resonance-cool",
        resonanceSignal: person.primarySignal,
      });
    });

    return nodes;
  }, [activePeople]);

  const toggleId = (setter: Dispatch<SetStateAction<string[]>>, id?: string) => {
    if (!id) return;
    setter((current) => (current.includes(id) ? current.filter((value) => value !== id) : [...current, id]));
  };

  const toggleDismiss = () => {
    if (!selectedPerson) return;

    const nextDismissed = dismissedIds.includes(selectedPerson.id)
      ? dismissedIds.filter((id) => id !== selectedPerson.id)
      : [...dismissedIds, selectedPerson.id];

    setDismissedIds(nextDismissed);

    if (nextDismissed.includes(selectedPerson.id)) {
      const fallback = people.find((person) => person.id !== selectedPerson.id && !nextDismissed.includes(person.id));
      if (fallback) setSelectedId(fallback.id);
    }
  };

  const theme = {
    panel: "rgba(21, 22, 28, 0.92)",
    border: "rgba(255,255,255,0.08)",
    accent: "#d4a574",
    muted: "#b6ac9d",
    background: "linear-gradient(180deg, #09090d 0%, #111117 100%)",
  };

  const rootStyle: CSSProperties = {
    minHeight: "100%",
    padding: 24,
    background: theme.background,
    color: "#efe7db",
    fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
  };

  const cardStyle: CSSProperties = {
    background: theme.panel,
    border: `1px solid ${theme.border}`,
    borderRadius: 22,
    boxShadow: "0 20px 50px rgba(0,0,0,0.24)",
  };

  const modeDetail =
    mode === "quick"
      ? "Quick view shows warmth, float level, and featured items."
      : mode === "breakdown"
        ? "Breakdown unlocks the active resonance patterns and recent signal."
        : "Full profile expands the cart categories and the person's life texture.";

  return (
    <section 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: 300 }}>
              <div style={{ fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "#9ca3af" }}>Cascade / R6</div>
              <h1 style={{ margin: "8px 0 8px", fontSize: 34, lineHeight: 1.05, color: "#f6d9b3" }}>{title}</h1>
              <p style={{ margin: 0, color: "#aca7b6", maxWidth: 820, fontSize: 15, lineHeight: 1.55 }}>{subtitle}</p>
            </div>

            <div style={{ minWidth: 300, maxWidth: 390, flex: 1, padding: 16, borderRadius: 18, background: "rgba(255,255,255,0.03)", border: `1px solid ${theme.border}` }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Hourly refresh</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{localClock} · {nextRefresh} until turn</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Average warmth</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: fieldScore >= 81 ? "#ffdca2" : "#f5c16c" }}>{fieldLabel}</div>
                </div>
              </div>
              <div style={{ height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden", marginTop: 14 }}>
                <div style={{ width: `${fieldScore}%`, height: "100%", borderRadius: 999, background: "linear-gradient(90deg, #94a3b8 0%, #f59e0b 50%, #fb7185 100%)", transition: "width 240ms ease" }} />
              </div>
              <div style={{ marginTop: 10, color: "#c3b8a9", fontSize: 13, lineHeight: 1.5 }}>
                The field refreshes hourly. Hexes without interaction fall back to circulation after roughly six hours.
              </div>
            </div>
          </div>
        </section>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.15fr) minmax(340px, 0.85fr)", 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" }}>The living surface</div>
                  <h2 style={{ margin: "6px 0 0", fontSize: 22 }}>Who is in your world right now?</h2>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap", color: "#d8d0c2", fontSize: 12 }}>
                  <LegendChip color="#fb7185" icon="🔥" label="Hot" />
                  <LegendChip color="#f59e0b" icon="🌡️" label="Warm" />
                  <LegendChip color="#94a3b8" icon="🌿" label="Cool" />
                </div>
              </div>

              <div style={{ borderRadius: 18, overflow: "hidden", border: `1px solid ${theme.border}`, background: "rgba(10, 10, 14, 0.72)" }}>
                <HexLattice
                  nodes={currentNodes}
                  showLabels
                  activeNodeId={selectedPerson?.id}
                  size="medium"
                  centerLabel="CURRENT"
                  focusRing={6}
                  onNodeClick={(node) => setSelectedId(node.id)}
                />
              </div>

              <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10 }}>
                <StatTile label="Visible slots" value={`${activePeople.length}/36`} detail="People currently inside the hourly field." />
                <StatTile label="Average score" value={String(fieldScore)} detail="Recent resonance only; not the full long-term score." />
                <StatTile label="Expiring soon" value={`${expiringSoon}`} detail="Active hexes with less than an hour before circulation." />
                <StatTile label="Next refresh" value={nextRefresh} detail="The Current turns with the hour." />
              </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" }}>Rotation queue</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>Active now and moving back to circulation</h3>
                </div>
                <div style={{ color: theme.muted, fontSize: 12 }}>Tap a hex to inspect it, or dismiss it from the field.</div>
              </div>

              <div style={{ display: "grid", gap: 12 }}>
                <QueueColumn
                  title="Active in Current"
                  hint="These people are still inside the hourly field."
                  items={activePeople.slice(0, 6).map((person) => ({
                    id: person.id,
                    name: person.name,
                    warmth: person.warmth,
                    note: `${formatDuration(person.hoursInCurrent)} in field · ${person.status}`,
                  }))}
                  activeId={selectedPerson?.id}
                  onSelect={(id) => setSelectedId(id)}
                />
                <QueueColumn
                  title="Circulating"
                  hint="These people rotated out or were dismissed locally."
                  items={circulatingPeople.slice(0, 6).map((person) => ({
                    id: person.id,
                    name: person.name,
                    warmth: person.warmth,
                    note: person.dismissed ? "dismissed locally" : `${formatDuration(person.hoursInCurrent)} since entry · hourly exit`,
                  }))}
                  activeId={selectedPerson?.id}
                  onSelect={(id) => setSelectedId(id)}
                  subdued
                />
              </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 hex</div>
              <div style={{ marginTop: 12, display: "flex", gap: 14, alignItems: "center" }}>
                <div style={{ width: 60, height: 60, borderRadius: 18, display: "grid", placeItems: "center", background: `${selectedWarmth.color}22`, border: `1px solid ${selectedWarmth.color}55`, color: selectedWarmth.color, fontSize: 20, fontWeight: 800 }}>{initials(selectedPerson?.name ?? "")}</div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.05 }}>{selectedPerson?.name ?? "—"}</div>
                  <div style={{ color: "#a6a0b1", fontSize: 13, marginTop: 4 }}>{selectedPerson ? `${selectedPerson.floatLevel} · ${selectedPerson.daysInCurrent}d in Current` : "No selection"}</div>
                </div>
              </div>

              <div style={{ display: "grid", gap: 10, marginTop: 16 }}>
                <InfoRow label="Warmth" value={`${selectedWarmth.icon} ${selectedWarmth.label}`} tone={selectedWarmth.color} />
                <InfoRow label="Resonance score" value={String(selectedPerson?.resonanceScore ?? 0)} tone="#f5c16c" />
                <InfoRow label="Float level" value={selectedPerson?.floatLevel ?? "—"} tone="#f5d79b" />
                <InfoRow label="Hearts available" value={`${selectedPerson?.heartsAvailable ?? 0}`} tone="#fb7185" />
                <InfoRow label="Rotation status" value={selectedRow ? (selectedDismissed ? "dismissed" : selectedRow.hoursRemaining <= 1 ? "leaving soon" : "active") : "—"} tone={selectedDismissed ? "#f59e0b" : "#94a3b8"} />
              </div>

              <div style={{ marginTop: 16, display: "grid", gap: 10 }}>
                <ActionButton
                  label={selectedWatch ? "Added to My World" : "Add to My World"}
                  helper="The non-committal maybe. No notify, no move — just keep watching the signal."
                  color="#f5c16c"
                  active={selectedWatch}
                  onClick={() => toggleId(setWatchlistIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedPackage ? "Care Package Sent" : "Send Care Package"}
                  helper={`Requires 3+ Hearts. Current: ${selectedPerson?.heartsAvailable ?? 0}.`}
                  color="#fb7185"
                  active={selectedPackage}
                  disabled={(selectedPerson?.heartsAvailable ?? 0) < 3}
                  onClick={() => toggleId(setPackageIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedLonging ? "In Longing" : "Add to Longing"}
                  helper={`Monthly slot / warm signal. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`}
                  color="#7eb8c9"
                  active={selectedLonging}
                  disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 30}
                  onClick={() => toggleId(setLongingIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedEcho ? "In Echo" : "Add to Echo"}
                  helper={`Weekly resonance / warm+ and 7+ days. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`}
                  color="#c9a8d4"
                  active={selectedEcho}
                  disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 7}
                  onClick={() => toggleId(setEchoIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedDismissed ? "Return to Current" : "Dismiss from Current"}
                  helper={selectedDismissed ? "Put this hex back into the active field if it still has room." : "Move this hex back to circulation for the rest of the session."}
                  color="#8b93a0"
                  active={selectedDismissed}
                  disabled={!selectedPerson}
                  onClick={toggleDismiss}
                />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Investigate</div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
                <ModeButton active={mode === "quick"} onClick={() => setMode("quick")} label="Quick" />
                <ModeButton active={mode === "breakdown"} onClick={() => selectedWarmth.label !== "Cool" && setMode("breakdown")} label="Breakdown" locked={selectedWarmth.label === "Cool"} />
                <ModeButton active={mode === "profile"} onClick={() => selectedWarmth.label === "Hot" && setMode("profile")} label="Profile" locked={selectedWarmth.label !== "Hot"} />
              </div>
              <div style={{ marginTop: 10, color: theme.muted, fontSize: 13, lineHeight: 1.5 }}>{modeLabel(mode)}</div>
              {mode === "breakdown" && selectedWarmth.label === "Cool" ? (
                <div style={{ marginTop: 10, padding: 12, borderRadius: 14, background: "rgba(255,255,255,0.03)", border: `1px solid ${theme.border}`, color: "#d8d0c2", fontSize: 13, lineHeight: 1.55 }}>
                  Breakdown unlocks at Warm or above.
                </div>
              ) : null}
              {mode === "profile" && selectedWarmth.label !== "Hot" ? (
                <div style={{ marginTop: 10, padding: 12, borderRadius: 14, background: "rgba(255,255,255,0.03)", border: `1px solid ${theme.border}`, color: "#d8d0c2", fontSize: 13, lineHeight: 1.55 }}>
                  Full profile unlocks at Hot or above.
                </div>
              ) : null}
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <ResonanceIndicators
                compact
                title="Ambient warmth"
                subtitle={`Recent signal from ${selectedPerson?.name ?? "the field"}.`}
                score={selectedPerson?.resonanceScore ?? fieldScore}
                recentHours={24}
                signals={selectedSignals}
                ringDistance={selectedWarmth.label === "Hot" ? 6 : selectedWarmth.label === "Warm" ? 5 : 3}
              />
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Field mechanics</div>
              <div style={{ marginTop: 12, display: "grid", gap: 10 }}>
                <DetailCard
                  title="Hourly pulse"
                  text={`The Current recalculates every hour. ${fieldStatus}.`}
                />
                <DetailCard
                  title="Who enters"
                  text="R5 drop-downs, circulation entries, and new users whose cart patterns rise above the R6 threshold."
                />
                <DetailCard
                  title="Who leaves"
                  text="Hexes with fading resonance, hexes that sit untouched for 6+ hours, and people who move up into R5."
                />
                <DetailCard
                  title="What you see"
                  text="Ambient warmth first. Tap a hex for Quick view, then open the breakdown or profile only when the signal justifies it."
                />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Warmth scale</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                <DetailCard title="Hot" text="Resonance score 61-80+ · strong, sustained signal with visible overlap." />
                <DetailCard title="Warm" text="Resonance score 41-60 · active signal and a reason to keep looking." />
                <DetailCard title="Cool" text="Resonance score 21-40 · ambient signal that may still become something." />
                <DetailCard title="What it means" text="Warmth is the last 24 hours of signal, not the full long-term score." />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>At a glance</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                <DetailCard title="Who enters" text="R5 drop-downs, circulation entries, and new users whose carts resonate right now." />
                <DetailCard title="Who leaves" text="People whose resonance fades below threshold, or who rotate out after 6+ hours without interaction." />
                <DetailCard title="What you see" text="Ambient warmth first. Tap deeper only when the signal justifies it." />
              </div>
            </section>
          </aside>
        </div>
      </div>
    </section>
  );
}

function LegendChip({ color, icon, label }: { color: string; icon: string; label: string }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 10px", borderRadius: 999, background: `${color}18`, border: `1px solid ${color}44` }}>
      <span style={{ color, fontSize: 14 }}>{icon}</span>
      <span>{label}</span>
    </div>
  );
}

function StatTile({ label, value, detail }: { label: string; value: string; detail: 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: 22, fontWeight: 800, color: "#f5d79b" }}>{value}</div>
      <div style={{ marginTop: 6, color: "#b6ac9d", fontSize: 13, lineHeight: 1.45 }}>{detail}</div>
    </div>
  );
}
