import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import HexLattice, { type HexNode } from "./HexLattice";
import ResonanceIndicators, { type ResonanceSignal } from "./ResonanceIndicators";

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

export interface CurrentSurfacePerson {
  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 CurrentSurfaceExplorerProps {
  title?: string;
  subtitle?: string;
  people?: CurrentSurfacePerson[];
}

const DEFAULT_PEOPLE: CurrentSurfacePerson[] = [
  {
    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 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 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 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 formatUntilNextHour(now: number) {
  const minutes = 60 - (Math.floor(now / 60000) % 60);
  return `${minutes === 60 ? 0 : minutes}m`;
}

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

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 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 categoryTone(category: keyof CurrentSurfacePerson["cartSummary"]) {
  if (category === "food") return "#d4a574";
  if (category === "activities") return "#8ab6d6";
  return "#9ac18a";
}

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

function buildPositionIndex(count: number) {
  const slots = [
    0, 6, 12, 18, 24, 30,
    1, 7, 13, 19, 25, 31,
    2, 8, 14, 20, 26, 32,
    3, 9, 15, 21, 27, 33,
    4, 10, 16, 22, 28, 34,
    5, 11, 17, 23, 29, 35,
  ];
  return slots.slice(0, count);
}

function actionRingColor(kind: "world" | "care" | "longing" | "echo" | "dismiss") {
  if (kind === "world") return "#f5c16c";
  if (kind === "care") return "#fb7185";
  if (kind === "longing") return "#a8d4ff";
  if (kind === "echo") return "#c9a8d4";
  return "#94a3b8";
}

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

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

  const dismissedSet = useMemo(() => new Set(dismissedIds), [dismissedIds]);
  const worldSet = useMemo(() => new Set(worldIds), [worldIds]);
  const careSet = useMemo(() => new Set(carePackageIds), [carePackageIds]);
  const longingSet = useMemo(() => new Set(longingIds), [longingIds]);
  const echoSet = useMemo(() => new Set(echoIds), [echoIds]);

  const rotationRows = useMemo(
    () =>
      people.map((person, index) => {
        const seed = hashString(person.id) + Math.floor(now / 3_600_000) * 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 = dismissedSet.has(person.id);

        return {
          ...person,
          hoursInCurrent,
          hoursRemaining,
          autoExpired,
          dismissed,
          status: dismissed ? "dismissed locally" : autoExpired ? "rotated out" : hoursInCurrent >= 5.5 ? "leaving soon" : "active",
          slotRank: (person.warmth === "hot" ? 3 : person.warmth === "warm" ? 2 : 1) * 1000 - hoursInCurrent * 100 - person.resonanceScore,
        };
      }),
    [dismissedSet, now, 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) => a.hoursRemaining - b.hoursRemaining),
    [rotationRows],
  );

  const selectedPerson =
    rotationRows.find((person) => person.id === selectedId) ??
    activePeople[0] ??
    rotationRows[0];

  const selectedWarmth = selectedPerson ? warmthMeta(selectedPerson.warmth) : warmthMeta("cool");
  const fieldScore = activePeople.length === 0 ? 0 : Math.round(activePeople.reduce((sum, person) => sum + person.resonanceScore, 0) / activePeople.length);
  const fieldLabel = scoreLabel(fieldScore);
  const nextRefresh = formatUntilNextHour(now);
  const localClock = formatClock(now);
  const canViewBreakdown = selectedPerson ? selectedPerson.warmth !== "cool" : false;
  const canViewProfile = selectedPerson ? selectedPerson.warmth === "hot" : false;

  const currentNodes = useMemo<HexNode[]>(() => {
    const nodes: HexNode[] = [
      { id: "center-you", ring: 0, position: 0, label: "CURRENT", type: "you" },
    ];

    const positions = buildPositionIndex(activePeople.length);
    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 selectedSignals = useMemo(() => (selectedPerson ? patternSignals(selectedPerson).filter((signal) => signal.score > 0) : []), [selectedPerson]);
  const selectedDismissed = selectedPerson ? dismissedSet.has(selectedPerson.id) : false;
  const selectedWorld = selectedPerson ? worldSet.has(selectedPerson.id) : false;
  const selectedCare = selectedPerson ? careSet.has(selectedPerson.id) : false;
  const selectedLonging = selectedPerson ? longingSet.has(selectedPerson.id) : false;
  const selectedEcho = selectedPerson ? echoSet.has(selectedPerson.id) : false;

  const toggleDismiss = () => {
    if (!selectedPerson) return;
    setDismissedIds((current) =>
      current.includes(selectedPerson.id)
        ? current.filter((id) => id !== selectedPerson.id)
        : [...current, selectedPerson.id],
    );
  };

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

  const rootStyle: CSSProperties = {
    minHeight: "100%",
    padding: 24,
    background:
      "radial-gradient(circle at top, rgba(145, 160, 255, 0.12), transparent 32%), radial-gradient(circle at 80% 20%, rgba(245, 158, 11, 0.10), transparent 28%), 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.92)",
    border: "1px solid rgba(255,255,255,0.08)",
    borderRadius: 22,
    boxShadow: "0 20px 50px rgba(0,0,0,0.24)",
  };

  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 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" }}>Hourly refresh</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{localClock} · {nextRefresh}</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 rgba(255,255,255,0.08)", 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="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: "#bdb3a5", 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={selectedPerson ? selectedPerson.status : "—"} tone={selectedDismissed ? "#f59e0b" : "#94a3b8"} />
              </div>

              <div style={{ marginTop: 16, display: "grid", gap: 10 }}>
                <ActionButton
                  label={selectedWorld ? "Added to My World" : "Add to My World"}
                  helper="The non-committal maybe. No notify, no move — just keep watching the signal."
                  color={actionRingColor("world")}
                  active={selectedWorld}
                  onClick={() => toggleId(setWorldIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedCare ? "Care Package Sent" : "Send Care Package"}
                  helper={`Requires 3+ Hearts. Current: ${selectedPerson?.heartsAvailable ?? 0}.`}
                  color={actionRingColor("care")}
                  active={selectedCare}
                  disabled={(selectedPerson?.heartsAvailable ?? 0) < 3}
                  onClick={() => toggleId(setCarePackageIds, selectedPerson?.id)}
                />
                <ActionButton
                  label={selectedLonging ? "In Longing" : "Add to Longing"}
                  helper={`Monthly slot / warm signal. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`}
                  color={actionRingColor("longing")}
                  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={actionRingColor("echo")}
                  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={actionRingColor("dismiss")}
                  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={() => canViewBreakdown && setMode("breakdown")} label="Breakdown" locked={!canViewBreakdown} />
                <ModeButton active={mode === "profile"} onClick={() => canViewProfile && setMode("profile")} label="Profile" locked={!canViewProfile} />
              </div>
              <div style={{ marginTop: 10, color: "#b6ac9d", fontSize: 13, lineHeight: 1.5 }}>
                {modeLabel(mode)}
              </div>
              {mode === "breakdown" && !canViewBreakdown ? (
                <div style={{ marginTop: 10, padding: 12, borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", color: "#d8d0c2", fontSize: 13, lineHeight: 1.55 }}>
                  Breakdown unlocks at Warm or above.
                </div>
              ) : null}
              {mode === "profile" && !canViewProfile ? (
                <div style={{ marginTop: 10, padding: 12, borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", 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" }}>Selected hex details</div>
              <div style={{ marginTop: 12, display: "grid", gap: 10 }}>
                {mode === "quick" && selectedPerson && (
                  <>
                    <DetailCard title="Featured items" text={selectedPerson.featuredItems.join(" · ")} />
                    <DetailCard title="Current note" text="Tap again to open the resonance breakdown. Warm and hot hexes unlock deeper visibility." />
                  </>
                )}
                {mode === "breakdown" && selectedPerson && selectedWarmth.label !== "Cool" && (
                  <>
                    {selectedPerson.patterns.map((pattern) => (
                      <PatternRow key={pattern.key} pattern={pattern} />
                    ))}
                    <DetailCard title="What this means" text="Hearts, Stars, Moons, Hourglasses, and Balloons are recent resonance only. They are not the full score." />
                  </>
                )}
                {mode === "profile" && selectedPerson && selectedWarmth.label === "Hot" && (
                  <>
                    <DetailCard title="Full profile" text={`${selectedPerson.name} has been in the Current for ${selectedPerson.daysInCurrent} days.`} />
                    {(["food", "activities", "habitat"] as const).map((category) => (
                      <div key={category} 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" }}>{category}</div>
                        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
                          {selectedPerson.cartSummary[category].map((item) => (
                            <span key={item} style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: `${categoryTone(category)}22`, color: "#f7efe2", border: `1px solid ${categoryTone(category)}44` }}>
                              {item}
                            </span>
                          ))}
                        </div>
                      </div>
                    ))}
                    <DetailCard title="Profile access" text="Hot or above unlocks the fuller profile view. This one is open." />
                  </>
                )}
                <DetailCard title="Ambient awareness" text={selectedWorld ? "This hex is in your ambient awareness. It stays in the Current for easy revisiting." : "Add to My World is the non-committal maybe: no move, no notify, just hold the signal."} />
              </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>
  );
}

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 isActive = activeId === item.id;
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => onSelect(item.id)}
                style={{
                  borderRadius: 14,
                  border: isActive ? `1px solid ${color}` : "1px solid rgba(255,255,255,0.08)",
                  background: isActive ? `${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 PatternRow({ pattern }: { pattern: CurrentSurfacePerson["patterns"][number] }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: pattern.active ? "rgba(245, 193, 108, 0.10)" : "rgba(255,255,255,0.03)", border: pattern.active ? "1px solid rgba(245, 193, 108, 0.22)" : "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
        <div style={{ fontWeight: 700 }}>{pattern.label}</div>
        <div style={{ fontSize: 12, color: pattern.active ? "#f5c16c" : "#8b93a0" }}>{pattern.active ? "Active" : "Quiet"}</div>
      </div>
      <div style={{ marginTop: 6, color: "#b6ac9d", fontSize: 13, lineHeight: 1.45 }}>{pattern.detail}</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>
  );
}

function SummaryRow({ 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: 700, fontSize: 14 }}>{value}</div>
    </div>
  );
}

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 FieldMetric({ 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>
  );
}

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 isActive = activeId === item.id;
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => onSelect(item.id)}
                style={{
                  borderRadius: 14,
                  border: isActive ? `1px solid ${color}` : "1px solid rgba(255,255,255,0.08)",
                  background: isActive ? `${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 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 SetStateToggle({
  label,
  active,
  onToggle,
  onColor,
  helper,
}: {
  label: string;
  active: boolean;
  onToggle: () => void;
  onColor: string;
  helper: string;
}) {
  return (
    <button
      type="button"
      onClick={onToggle}
      style={{
        width: "100%",
        borderRadius: 14,
        border: active ? `1px solid ${onColor}` : "1px solid rgba(255,255,255,0.12)",
        background: active ? `${onColor}20` : "rgba(245, 193, 108, 0.10)",
        color: "#f7efe2",
        textAlign: "left",
        padding: 12,
        cursor: "pointer",
      }}
    >
      <div style={{ fontWeight: 700 }}>{active ? `${label} added` : label}</div>
      <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 12, lineHeight: 1.45 }}>{helper}</div>
    </button>
  );
}

function HexIcon({ color, label }: { color: string; label: string }) {
  return (
    <div style={{ width: 56, height: 56, borderRadius: 16, display: "grid", placeItems: "center", background: `${color}22`, border: `1px solid ${color}55`, color, fontSize: 18, fontWeight: 800 }}>
      {label}
    </div>
  );
}
