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 ResonanceFieldPerson {
  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 ResonanceFieldProps {
  title?: string;
  subtitle?: string;
  people?: ResonanceFieldPerson[];
}

const DEFAULT_PEOPLE: ResonanceFieldPerson[] = [
  {
    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 },
    ],
  },
];

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 formatDuration(days: number) {
  if (days < 1) return `${Math.max(1, Math.round(days * 24))}h`;
  return `${days}d`;
}

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?: ResonanceFieldPerson): 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 ResonanceFieldPerson["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 maxByWarmth(people: ResonanceFieldPerson[]) {
  if (people.length === 0) return 0;
  return Math.round(people.reduce((sum, person) => sum + person.resonanceScore, 0) / people.length);
}

export default function ResonanceField({
  title = "Resonance Field",
  subtitle = "Passive discovery for The Current: ambient warmth, ring attenuation, and the people who just entered your social weather.",
  people = DEFAULT_PEOPLE,
}: ResonanceFieldProps) {
  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(() => maxByWarmth(people), [people]);
  const fieldLabel = scoreLabel(fieldScore);
  const nextRefresh = formatUntilNextHour(now);
  const selectedWarmth = warmthMeta(selectedPerson?.warmth ?? "cool");

  const canViewBreakdown = selectedPerson?.warmth !== "cool";
  const canViewProfile = selectedPerson?.warmth === "hot";

  const sortedPeople = useMemo(
    () => [...people].sort((a, b) => b.resonanceScore - a.resonanceScore),
    [people],
  );

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

    sortedPeople.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;
  }, [sortedPeople]);

  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 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 activePeople = sortedPeople.filter((person) => person.warmth !== "cool");
  const circulatingPeople = sortedPeople.filter((person) => person.warmth === "cool");

  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: 380, flex: 1, padding: 16, borderRadius: 18, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Hourly refresh</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{nextRefresh}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Field warmth</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: fieldScore >= 61 ? "#f5c16c" : "#94a3b8" }}>{fieldLabel}</div>
                </div>
              </div>
              <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "minmax(0, 1fr) auto", gap: 10, alignItems: "center" }}>
                <div style={{ height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
                  <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={{ color: "#d8d0c2", fontSize: 13, minWidth: 44, textAlign: "right" }}>{fieldScore}</div>
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13, lineHeight: 1.5 }}>
                The field recalculates every hour. Hexes without interaction drift back into circulation.
              </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);
                    setMode("quick");
                  }}
                />
              </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="Circulating" value={`${circulatingPeople.length}`} detail="Cooler signals waiting for the next turn." />
                <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={activePeople.slice(0, 6).map((person) => ({
                    id: person.id,
                    name: person.name,
                    warmth: person.warmth,
                    note: `${formatDuration(person.daysInCurrent)} in field · ${person.floatLevel}`,
                  }))}
                  activeId={selectedPerson?.id}
                  onSelect={(id) => {
                    setSelectedId(id);
                    setMode("quick");
                  }}
                />
                <PeopleColumn
                  title="Circulating"
                  hint="These people are cooler or waiting for the next turn."
                  items={circulatingPeople.slice(0, 6).map((person) => ({
                    id: person.id,
                    name: person.name,
                    warmth: person.warmth,
                    note: `${formatDuration(person.daysInCurrent)} since entry · ambient only`,
                  }))}
                  activeId={selectedPerson?.id}
                  onSelect={(id) => {
                    setSelectedId(id);
                    setMode("quick");
                  }}
                  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 }}>{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="Time in Current" value={selectedPerson ? formatDuration(selectedPerson.daysInCurrent) : "—"} tone="#9ac18a" />
              </div>

              <div style={{ marginTop: 16, display: "grid", gap: 10 }}>
                <ActionButton
                  label={selectedInWatchlist ? "Remove from My World" : "Add to My World"}
                  helper={selectedInWatchlist ? "You are already holding this person in ambient awareness." : "The non-committal maybe. It stays in your ambient awareness."}
                  active={selectedInWatchlist}
                  onClick={() => selectedPerson && toggleEntry(selectedPerson.id, setWatchlistIds)}
                />
                <ActionButton
                  label={selectedInPackage ? "Care Package Sent" : "Send Care Package"}
                  helper={`Requires 3+ Hearts. Current: ${selectedPerson?.heartsAvailable ?? 0}.`}
                  active={selectedInPackage}
                  disabled={(selectedPerson?.heartsAvailable ?? 0) < 3 && !selectedInPackage}
                  onClick={() => selectedPerson && toggleEntry(selectedPerson.id, setPackageIds)}
                />
                <ActionButton
                  label={selectedInLonging ? "Remove from Longing" : "Add to Longing"}
                  helper={`Monthly slot / warm signal. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`}
                  active={selectedInLonging}
                  disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 30 && !selectedInLonging}
                  onClick={() => selectedPerson && toggleEntry(selectedPerson.id, setLongingIds)}
                />
                <ActionButton
                  label={selectedInEcho ? "Remove from Echo" : "Add to Echo"}
                  helper={`Weekly resonance / warm+ and 7+ days. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`}
                  active={selectedInEcho}
                  disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 7 && !selectedInEcho}
                  onClick={() => selectedPerson && toggleEntry(selectedPerson.id, setEchoIds)}
                />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center" }}>
                <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Investigate</div>
                <div style={{ color: "#bdb3a5", fontSize: 12 }}>{modeLabel(mode)}</div>
              </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 }}>
                {mode === "quick"
                  ? "Quick view shows warmth, float level, and featured items."
                  : mode === "breakdown"
                    ? "Breakdown unlocks the active resonance patterns and the last 24 hours of signal."
                    : "Full profile expands the cart categories and the person's life texture."}
              </div>
              {(!canViewBreakdown && mode === "breakdown") || (!canViewProfile && mode === "profile") ? (
                <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 }}>
                  {mode === "breakdown"
                    ? "Breakdown unlocks at Warm or above."
                    : "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={patternSignals(selectedPerson)}
                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 && canViewBreakdown && (
                  <>
                    {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 && canViewProfile && (
                  <>
                    <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 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,
  active = false,
  disabled = false,
  onClick,
}: {
  label: string;
  helper: string;
  active?: boolean;
  disabled?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      disabled={disabled}
      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: disabled ? "rgba(255,255,255,0.02)" : active ? "rgba(245, 193, 108, 0.16)" : "rgba(245, 193, 108, 0.12)",
        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>
  );
}
