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

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

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

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

const DEFAULT_PEOPLE: CurrentPerson[] = [
  {
    id: "mira",
    name: "Mira",
    warmth: "hot",
    floatLevel: "Cloud Walking",
    resonanceScore: 88,
    primarySignal: "hearts",
    featuredItems: ["Ramen Bar X", "Bike rides after sunset", "Ceramic mugs"],
    cartSummary: {
      food: ["Ramen Bar X", "Sour cherries", "Sunday pastries"],
      activities: ["Bike rides after sunset", "Late-night walks", "Film scores on vinyl"],
      habitat: ["Plants near every window", "Soft lighting", "A well-used kitchen"],
    },
    daysInCurrent: 11,
    heartsAvailable: 4,
    patterns: [
      { key: "hearts", label: "Direct overlap", detail: "You both have Ramen Bar X and the same evening ritual.", active: true },
      { key: "hourglasses", label: "Values alignment", detail: "Your patterns over the last 90 days have 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: "You both orbit creative-night rituals and local food routines.", 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 is keeping 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", scoreBand: "61-80+", description: "resonance is immediate" };
  if (warmth === "warm") return { label: "Warm", icon: "🌡️", color: "#f59e0b", scoreBand: "41-60", description: "resonance is active" };
  return { label: "Cool", icon: "🌿", color: "#94a3b8", scoreBand: "21-40", description: "resonance is ambient" };
}

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 formatAgo(msSince: number) {
  const minutes = Math.max(1, Math.round(msSince / 60000));
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.max(1, Math.round(minutes / 60));
  if (hours < 24) return `${hours}h ago`;
  const days = Math.max(1, Math.round(hours / 24));
  return `${days}d ago`;
}

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

export default function CurrentAtmosphere({
  people = DEFAULT_PEOPLE,
  title = "The Current",
  subtitle = "The living surface of Cascade — hourly atmosphere, ambient warmth, and the people currently in your social field.",
}: CurrentAtmosphereProps) {
  const [selectedId, setSelectedId] = useState(people[0]?.id ?? "");
  const [mode, setMode] = useState<InvestigationMode>("quick");
  const [refreshTick, setRefreshTick] = useState(() => Date.now());
  const [refreshAt] = useState(() => Date.now() - 18 * 60 * 1000);

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

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

  const gridNodes = useMemo<HexNode[]>(() => {
    const slotPositions = [0, 6, 12, 18, 24, 30];
    return people.map((person, index) => ({
      id: person.id,
      ring: 6,
      position: slotPositions[index] ?? index,
      label: initials(person.name),
      type: person.warmth === "hot" ? "resonance-hot" : person.warmth === "warm" ? "resonance-warm" : "resonance-cool",
      resonanceSignal: person.primarySignal,
    }));
  }, [people]);

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

  const occupied = people.length;
  const averageWarmth = totalScore >= 81 ? "Resonant" : totalScore >= 61 ? "Blazing" : totalScore >= 41 ? "Hot" : totalScore >= 21 ? "Warm" : "Cool";
  const selectedWarmth = warmthMeta(selectedPerson?.warmth ?? "cool");
  const canViewBreakdown = selectedPerson?.warmth !== "cool";
  const canViewProfile = selectedPerson?.warmth === "hot";
  const freshness = formatAgo(refreshTick - refreshAt);

  const modeUnavailableText =
    mode === "breakdown" && !canViewBreakdown
      ? "Breakdown unlocks at Warm or above."
      : mode === "profile" && !canViewProfile
        ? "Full profile unlocks at Hot or above."
        : "";

  return (
    <div
      style={{
        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",
      }}
    >
      <div style={{ maxWidth: 1260, margin: "0 auto", display: "grid", gap: 18 }}>
        <section style={{ borderRadius: 24, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 28px 60px rgba(0,0,0,0.24)", 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 }}>{subtitle}</p>
            </div>

            <div style={{ minWidth: 290, maxWidth: 360, 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 }}>{freshness}</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: "#f5c16c" }}>{averageWarmth}</div>
                </div>
              </div>
              <div style={{ height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden", marginTop: 14 }}>
                <div style={{ width: `${totalScore}%`, 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 }}>R6 is the ambient surface: 36 slots, hourly updates, warmth only until you investigate.</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={{ borderRadius: 22, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 20px 50px rgba(0,0,0,0.24)", 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={gridNodes}
                  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="Occupied slots" value={`${occupied}/36`} detail="R6 fills from circulation and daily drop-downs." />
                <StatTile label="Current score" value={String(totalScore)} detail="Recent resonance only; not the full long-term score." />
                <StatTile label="Updated" value={freshness} detail="The field refreshes hourly." />
              </div>
            </section>

            <section style={{ borderRadius: 22, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 20px 50px rgba(0,0,0,0.24)", 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" }}>Investigation flow</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>{modeLabel(mode)}</h3>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <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>

              <div style={{ padding: 14, borderRadius: 16, background: "rgba(255,255,255,0.03)", color: "#d8d0c2", lineHeight: 1.55, marginBottom: 14 }}>
                {modeUnavailableText || "Tap once for the quick view, tap again for the resonance breakdown, and tap a hot hex for the full profile."}
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
                {people.map((person) => {
                  const meta = warmthMeta(person.warmth);
                  return (
                    <button key={person.id} type="button" onClick={() => { setSelectedId(person.id); setMode("quick"); }} style={{ borderRadius: 16, padding: 12, border: selectedPerson?.id === person.id ? `1px solid ${meta.color}` : "1px solid rgba(255,255,255,0.08)", background: selectedPerson?.id === person.id ? `color-mix(in srgb, ${meta.color} 12%, rgba(255,255,255,0.03))` : "rgba(255,255,255,0.03)", color: "#efe7db", textAlign: "left", cursor: "pointer" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
                        <div style={{ fontWeight: 700 }}>{person.name}</div>
                        <div style={{ color: meta.color, fontSize: 14 }}>{meta.icon}</div>
                      </div>
                      <div style={{ color: "#a7a1b3", fontSize: 12, marginTop: 4 }}>{person.floatLevel}</div>
                    </button>
                  );
                })}
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ borderRadius: 22, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 20px 50px rgba(0,0,0,0.24)", 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.description}</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" />
              </div>

              <div style={{ marginTop: 16, display: "grid", gap: 10 }}>
                <ActionButton label="Add to My World" helper="The non-committal maybe. It stays in your ambient awareness." />
                <ActionButton label="Send Care Package" helper={`Requires 3+ Hearts. Current: ${selectedPerson?.heartsAvailable ?? 0}.`} disabled={(selectedPerson?.heartsAvailable ?? 0) < 3} />
                <ActionButton label="Add to Longing" helper={`Monthly slot / warm signal. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`} disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 30} />
                <ActionButton label="Add to Echo" helper={`Weekly resonance / warm+ and 7+ days. ${selectedPerson?.daysInCurrent ?? 0} days in Current.`} disabled={(selectedPerson?.warmth ?? "cool") === "cool" || (selectedPerson?.daysInCurrent ?? 0) < 7} />
              </div>
            </section>

            <section style={{ borderRadius: 22, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 20px 50px rgba(0,0,0,0.24)", padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Selected hex details</div>
              <div style={{ marginTop: 12 }}>
                {mode === "quick" && selectedPerson && (
                  <div style={{ display: "grid", gap: 10 }}>
                    <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." />
                  </div>
                )}

                {mode === "breakdown" && selectedPerson && (
                  <div style={{ display: "grid", gap: 10 }}>
                    {selectedPerson.patterns.map((pattern) => (
                      <PatternRow key={pattern.key} pattern={pattern} />
                    ))}
                    <DetailCard title="What this means" text="This is the pattern layer: Hearts, Stars, Moons, Hourglasses, and Balloons are only about recent resonance. They are not the full score." />
                  </div>
                )}

                {mode === "profile" && selectedPerson && (
                  <div style={{ display: "grid", gap: 12 }}>
                    <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={canViewProfile ? "Hot or above unlocks full profile. This one is open." : "Full profile stays locked until warmth reaches Hot."} />
                  </div>
                )}
              </div>
            </section>

            <section style={{ borderRadius: 22, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(21, 22, 28, 0.92)", boxShadow: "0 20px 50px rgba(0,0,0,0.24)", 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>
    </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 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 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 PatternRow({ pattern }: { pattern: CurrentPerson["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 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 ActionButton({ label, helper, disabled = false }: { label: string; helper: string; disabled?: boolean }) {
  return <button type="button" disabled={disabled} style={{ width: "100%", borderRadius: 14, border: "1px solid rgba(255,255,255,0.12)", background: disabled ? "rgba(255,255,255,0.02)" : "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>;
}
