import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from "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";

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

function averageScore(people: CurrentSurfacePerson[]) {
  if (people.length === 0) return 0;
  return Math.round(people.reduce((sum, person) => sum + person.resonanceScore, 0) / people.length);
}

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

export default function CurrentSurfacePanel({
  title = "The Current",
  subtitle = "The living surface of Cascade — hourly atmosphere, ambient warmth, and the people currently in your social field.",
  people = DEFAULT_PEOPLE,
}: CurrentSurfacePanelProps) {
  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[]>([]);

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

  const selectedPerson = useMemo(
    () => people.find((person) => person.id === selectedId) ?? people[0],
    [people, selectedId],
  );

  const fieldScore = useMemo(() => averageScore(people), [people]);
  const fieldLabel = scoreLabel(fieldScore);
  const nextRefresh = formatUntilNextHour(now);
  const selectedWarmth = warmthMeta(selectedPerson?.warmth ?? "cool");
  const activeCount = people.length;
  const selectedSignals = useMemo(() => patternSignals(selectedPerson), [selectedPerson]);
  const selectedInWatchlist = Boolean(selectedPerson && watchlistIds.includes(selectedPerson.id));
  const selectedInPackage = Boolean(selectedPerson && packageIds.includes(selectedPerson.id));
  const selectedInLonging = Boolean(selectedPerson && longingIds.includes(selectedPerson.id));
  const selectedInEcho = Boolean(selectedPerson && echoIds.includes(selectedPerson.id));

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

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

    return nodes;
  }, [people]);

  const toggleEntry = (id: string, setter: Dispatch<SetStateAction<string[]>>) => {
    setter((current) => (current.includes(id) ? current.filter((entry) => entry !== 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)",
  };

  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.";

  const actionCard = (active: boolean, label: string, helper: string, onClick: () => void) => (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: "100%",
        borderRadius: 14,
        border: active ? "1px solid rgba(245, 193, 108, 0.28)" : "1px solid rgba(255,255,255,0.12)",
        background: active ? "rgba(245, 193, 108, 0.16)" : "rgba(245, 193, 108, 0.12)",
        color: "#f7efe2",
        textAlign: "left",
        padding: 12,
        cursor: "pointer",
      }}
    >
      <div style={{ fontWeight: 700 }}>{label}</div>
      <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 12, lineHeight: 1.45 }}>{helper}</div>
    </button>
  );

  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 }}>{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 >= 80 ? "#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 }}>
                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.12fr) minmax(340px, 0.88fr)", 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={`${activeCount}/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 }}>
                <PeopleColumn
                  title="Active in Current"
                  hint="These people are still inside the hourly field."
                  items={people.slice(0, 6).map((person) => ({
                    id: person.id,
                    name: person.name,
                    warmth: person.warmth,
                    note: `${person.daysInCurrent}d in field · ${person.floatLevel}`,
                  }))}
                  activeId={selectedPerson?.id}
                  onSelect={(id) => setSelectedId(id)}
                />
              </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 }}>{selectedWarmth.label.toLowerCase()} ambient field</div>
                </div>
              </div>

              <div style={{ display: "grid", gap: 10, marginTop: 16 }}>
                <InfoRow label="Warmth" value={`${selectedWarmth.icon} ${selectedWarmth.label}`} tone={selectedWarmth.color} />
                <InfoRow label="Float level" value={selectedPerson?.floatLevel ?? "—"} tone="#f5d79b" />
                <InfoRow label="Resonance score" value={String(selectedPerson?.resonanceScore ?? 0)} tone="#f5c16c" />
                <InfoRow label="Hearts available" value={`${selectedPerson?.heartsAvailable ?? 0}`} tone="#fb7185" />
                <InfoRow label="Days in Current" value={selectedPerson ? `${selectedPerson.daysInCurrent}d` : "—"} tone="#9ac18a" />
              </div>

              <div style={{ marginTop: 16, display: "grid", gap: 10 }}>
                {actionCard(selectedInWatchlist, selectedInWatchlist ? "Return to My World" : "Add to My World", "The non-committal maybe. It stays in your ambient awareness.", () => toggleEntry(selectedPerson!.id, setWatchlistIds))}
                {actionCard(selectedInPackage, selectedInPackage ? "Care Package Sent" : "Send Care Package", `Requires 3+ Hearts. Current: ${selectedPerson?.heartsAvailable ?? 0}.`, () => toggleEntry(selectedPerson!.id, setPackageIds))}
                {actionCard(selectedInLonging, selectedInLonging ? "Already in Longing" : "Add to Longing", `Monthly slot / warm signal. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`, () => toggleEntry(selectedPerson!.id, setLongingIds))}
                {actionCard(selectedInEcho, selectedInEcho ? "Already in Echo" : "Add to Echo", `Weekly resonance / warm+ and 7+ days. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`, () => toggleEntry(selectedPerson!.id, setEchoIds))}
              </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: "#b6ac9d", fontSize: 13, lineHeight: 1.5 }}>{modeDetail}</div>
              {mode === "breakdown" && selectedWarmth.label === "Cool" ? (
                <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" && selectedWarmth.label !== "Hot" ? (
                <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="Ambient awareness" text={selectedInWatchlist ? "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 PeopleColumn({
  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>
  );
}
