import { useMemo, useState, type CSSProperties } from "react";
import {
  Bike,
  Check,
  Home,
  Plus,
  RotateCcw,
  Search,
  Star,
  Trash2,
  UtensilsCrossed,
  Sparkles,
} from "lucide-react";
import HexLattice, { type HexNode } from "./HexLattice";
import ResonanceIndicators, { type ResonanceSignal } from "./ResonanceIndicators";

type CartCategoryKey = "food" | "activities" | "habitat";

type CartItem = {
  id: string;
  category: CartCategoryKey;
  name: string;
  note?: string;
  featured?: boolean;
  addedAt: number;
};

type CartHistoryItem = CartItem & {
  removedAt: number;
};

export interface CartConstellationProps {
  title?: string;
  subtitle?: string;
  initialItems?: CartItem[];
  onChange?: (items: CartItem[]) => void;
}

const CATEGORY_META: Record<
  CartCategoryKey,
  {
    label: string;
    icon: JSX.Element;
    accent: string;
    prompt: string;
    examples: string[];
    reveal: string;
  }
> = {
  food: {
    label: "Food",
    icon: <UtensilsCrossed className="h-4 w-4" />,
    accent: "#d4a574",
    prompt: "Tell us how you eat.",
    examples: ["Ramen Bar X", "Farmers market on Saturdays", "My own cooking"],
    reveal: "Social rhythm, adventurousness, values, and domestic investment.",
  },
  activities: {
    label: "Activities",
    icon: <Bike className="h-4 w-4" />,
    accent: "#8ab6d6",
    prompt: "Tell us how you spend your time.",
    examples: ["Rock climbing on weekends", "Jazz vinyl listening", "Language learning apps"],
    reveal: "Energy, social style, creator vs. consumer orientation, planning tendency.",
  },
  habitat: {
    label: "Habitat",
    icon: <Home className="h-4 w-4" />,
    accent: "#9ac18a",
    prompt: "Tell us about your space.",
    examples: ["My plants (14 and counting)", "Minimalist kitchen", "Bookshelf I actually use"],
    reveal: "Nurturing instinct, standards, aesthetic sensibility, and domestic values.",
  },
};

const STARTER_DECK: CartItem[] = [
  { id: "food-1", category: "food", name: "Ramen Bar X", addedAt: Date.now() - 9 * 60_000 },
  { id: "food-2", category: "food", name: "Farmers market on Saturdays", addedAt: Date.now() - 8 * 60_000 },
  { id: "food-3", category: "food", name: "My own cooking", addedAt: Date.now() - 7 * 60_000 },
  { id: "activity-1", category: "activities", name: "Rock climbing on weekends", addedAt: Date.now() - 6 * 60_000 },
  { id: "activity-2", category: "activities", name: "Jazz vinyl listening", addedAt: Date.now() - 5 * 60_000 },
  { id: "activity-3", category: "activities", name: "Language learning apps", addedAt: Date.now() - 4 * 60_000 },
  { id: "habitat-1", category: "habitat", name: "My plants (14 and counting)", addedAt: Date.now() - 3 * 60_000 },
  { id: "habitat-2", category: "habitat", name: "Minimalist kitchen", addedAt: Date.now() - 2 * 60_000 },
  { id: "habitat-3", category: "habitat", name: "Bookshelf I actually use", addedAt: Date.now() - 60_000 },
];

const VISIBILITY_ROWS = [
  { viewer: "Your R1", sees: "Full cart — every item, every category" },
  { viewer: "Your R2", sees: "Category types — Food / Activities / Habitat" },
  { viewer: "Your R3", sees: "Longing patterns — monthly / seasonal trends" },
  { viewer: "Your R4", sees: "Full cart + creative output" },
  { viewer: "Your R5", sees: "Daily sustained patterns" },
  { viewer: "Your R6", sees: "Ambient warmth only (hot / warm / cool)" },
  { viewer: "Non-connected users", sees: "Profile and 3 featured items" },
] as const;

const VALUE_KEYWORDS = ["organic", "local", "sustainable", "creative", "learning", "weekly", "daily", "ritual", "plants", "dog", "home", "music", "climbing", "hiking", "garden", "minimalist", "secondhand"];

function makeId(prefix: string) {
  return `${prefix}-${Math.random().toString(36).slice(2, 8)}-${Date.now().toString(36)}`;
}

function normalize(value: string) {
  return value.trim().toLowerCase();
}

function shortLabel(text: string, max = 12) {
  const compact = text.trim().replace(/\s+/g, " ");
  return compact.length <= max ? compact : `${compact.slice(0, max - 1)}…`;
}

function formatAgo(timestamp: number) {
  const diffMinutes = Math.max(1, Math.round((Date.now() - timestamp) / 60_000));
  if (diffMinutes < 60) return `${diffMinutes}m ago`;
  const diffHours = Math.round(diffMinutes / 60);
  if (diffHours < 24) return `${diffHours}h ago`;
  return `${Math.round(diffHours / 24)}d ago`;
}

function categorySignal(category: CartCategoryKey): ResonanceSignal["key"] {
  if (category === "food") return "hearts";
  if (category === "activities") return "stars";
  return "moons";
}

function categoryIcon(category: CartCategoryKey) {
  return CATEGORY_META[category].icon;
}

function countKeywords(text: string, keywords: string[]) {
  const source = normalize(text);
  return keywords.reduce((count, keyword) => count + (source.includes(keyword) ? 1 : 0), 0);
}

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 warmthFromScore(score: number) {
  if (score >= 80) return { label: "Blazing", emoji: "🔥", color: "#fb7185" };
  if (score >= 61) return { label: "Hot", emoji: "🔥", color: "#f97316" };
  if (score >= 41) return { label: "Warm", emoji: "🌡️", color: "#f59e0b" };
  if (score >= 21) return { label: "Cool", emoji: "🌿", color: "#94a3b8" };
  return { label: "Cold", emoji: "❄️", color: "#7dd3fc" };
}

function barWidth(value: number, cap: number) {
  return `${Math.round(Math.max(0, Math.min(100, (value / cap) * 100)))}%`;
}

function buildNodes(items: CartItem[], selectedId?: string): HexNode[] {
  const nodes: HexNode[] = [
    {
      id: "center",
      ring: 0,
      position: 0,
      type: "you",
      label: "YOU",
    },
  ];

  items.forEach((item, index) => {
    const ring = index < 12 ? 2 : index < 30 ? 3 : 4;
    const position = index < 12 ? index : index < 30 ? index - 12 : index - 30;
    const active = selectedId === item.id;

    nodes.push({
      id: item.id,
      ring,
      position,
      type: active ? "resonance-hot" : item.featured ? "resonance-warm" : "person",
      label: shortLabel(item.name, item.featured ? 10 : 12),
      resonanceSignal: categorySignal(item.category),
    });
  });

  return nodes;
}

export default function CartConstellation({
  title = "Cart Constellation",
  subtitle = "The cart is your identity mirror. The first 9 items shape the initial field.",
  initialItems = STARTER_DECK,
  onChange,
}: CartConstellationProps) {
  const [items, setItems] = useState<CartItem[]>(initialItems);
  const [history, setHistory] = useState<CartHistoryItem[]>([]);
  const [selectedId, setSelectedId] = useState<string | undefined>(initialItems[0]?.id);
  const [drafts, setDrafts] = useState<Record<CartCategoryKey, string>>({ food: "", activities: "", habitat: "" });

  const updateItems = (next: CartItem[]) => {
    setItems(next);
    onChange?.(next);
    setSelectedId((current) => (current && next.some((item) => item.id === current) ? current : next[0]?.id));
  };

  const addItem = (category: CartCategoryKey, value: string) => {
    const name = value.trim();
    if (!name) return;
    if (items.some((item) => normalize(item.name) === normalize(name))) return;

    const next = [...items, { id: makeId(category), category, name, addedAt: Date.now() }];
    updateItems(next);
    setDrafts((current) => ({ ...current, [category]: "" }));
  };

  const addExample = (category: CartCategoryKey, value: string) => addItem(category, value);

  const removeItem = (id: string) => {
    const removed = items.find((item) => item.id === id);
    if (!removed) return;
    setHistory((current) => [{ ...removed, removedAt: Date.now() }, ...current].slice(0, 6));
    updateItems(items.filter((item) => item.id !== id));
  };

  const restoreItem = (historyItem: CartHistoryItem) => {
    if (items.some((item) => normalize(item.name) === normalize(historyItem.name))) return;
    updateItems([...items, { ...historyItem, addedAt: Date.now(), featured: historyItem.featured }]);
    setHistory((current) => current.filter((entry) => entry.id !== historyItem.id));
  };

  const toggleFeatured = (id: string) => {
    const featuredCount = items.filter((item) => item.featured).length;
    const next = items.map((item) => {
      if (item.id !== id) return item;
      if (item.featured) return { ...item, featured: false };
      if (featuredCount >= 3) return item;
      return { ...item, featured: true };
    });
    updateItems(next);
  };

  const resetCart = () => {
    updateItems([]);
    setHistory([]);
    setDrafts({ food: "", activities: "", habitat: "" });
    setSelectedId(undefined);
  };

  const loadStarterDeck = () => {
    updateItems(STARTER_DECK.map((item, index) => ({ ...item, id: `${item.id}-${index}`, addedAt: Date.now() - (STARTER_DECK.length - index) * 45_000 })));
  };

  const selectedItem = items.find((item) => item.id === selectedId) ?? items[0];
  const featuredItems = items.filter((item) => item.featured).slice(0, 3);
  const categoryGroups = {
    food: items.filter((item) => item.category === "food"),
    activities: items.filter((item) => item.category === "activities"),
    habitat: items.filter((item) => item.category === "habitat"),
  };
  const filledCategories = Object.values(categoryGroups).filter((group) => group.length > 0).length;
  const totalItems = items.length;
  const firstNineCount = Math.min(totalItems, 9);
  const firstNineProgress = Math.round((firstNineCount / 9) * 100);
  const exactnessHits = items.filter((item) => item.name.split(/\s+/).filter(Boolean).length >= 2 || /\d/.test(item.name)).length;
  const valueHits = countKeywords(items.map((item) => `${item.name} ${item.note ?? ""}`).join(" "), VALUE_KEYWORDS);
  const spread = Math.abs(categoryGroups.food.length - categoryGroups.activities.length) + Math.abs(categoryGroups.activities.length - categoryGroups.habitat.length) + Math.abs(categoryGroups.habitat.length - categoryGroups.food.length);

  const resonanceScore = Math.round(
    Math.max(
      0,
      Math.min(
        100,
        (filledCategories * 24 + Math.min(totalItems, 12) * 3 + exactnessHits * 8 + featuredItems.length * 10 + valueHits * 12 + (totalItems >= 9 ? 12 : 0) + Math.max(0, 18 - spread * 4)),
      ),
    ),
  );

  const warmth = warmthFromScore(resonanceScore);

  const resonanceSignals: ResonanceSignal[] = useMemo(
    () => [
      {
        key: "hearts",
        score: Math.min(100, exactnessHits * 16 + featuredItems.length * 8 + (totalItems > 0 ? 12 : 0)),
        note: "Specific named places and repeated items",
      },
      {
        key: "stars",
        score: Math.min(100, filledCategories * 28 + Math.min(totalItems * 3, 24)),
        note: "Category coverage across Food / Activities / Habitat",
      },
      {
        key: "moons",
        score: Math.min(100, 100 - spread * 12 + (filledCategories === 3 ? 14 : filledCategories * 4)),
        note: "Balance and complementary spacing across the three categories",
      },
      {
        key: "hourglasses",
        score: Math.min(100, valueHits * 14 + (totalItems >= 6 ? 10 : 0)),
        note: "Values language and repetition over time",
      },
      {
        key: "balloons",
        score: Math.min(100, totalItems * 7 + featuredItems.length * 10 + (totalItems >= 9 ? 12 : 0)),
        note: "Presence, consistency, and the first 9 planted items",
      },
    ],
    [exactnessHits, featuredItems.length, filledCategories, totalItems, valueHits, spread],
  );

  const latticeNodes = useMemo(() => buildNodes(items, selectedItem?.id), [items, selectedItem?.id]);

  const rootStyle: CSSProperties = {
    minHeight: "100%",
    padding: 24,
    background:
      "radial-gradient(circle at top, rgba(212,165,116,0.14), transparent 34%), radial-gradient(circle at 80% 20%, rgba(126,184,201,0.11), transparent 28%), linear-gradient(180deg, #09090d 0%, #101117 100%)",
    color: "#efe7db",
    fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
  };

  const cardStyle: CSSProperties = {
    background: "rgba(21, 22, 28, 0.92)",
    border: "1px solid rgba(255,255,255,0.08)",
    borderRadius: 22,
    boxShadow: "0 20px 50px rgba(0,0,0,0.24)",
  };

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

            <div style={{ minWidth: 320, maxWidth: 400, 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" }}>First 9</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{firstNineCount}/9 planted</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Current score</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: warmth.color }}>{resonanceScore}</div>
                </div>
              </div>
              <div style={{ marginTop: 12, height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
                <div
                  style={{
                    width: `${firstNineProgress}%`,
                    height: "100%",
                    borderRadius: 999,
                    background: "linear-gradient(90deg, #d4a574 0%, #7eb8c9 50%, #d4a8b4 100%)",
                    transition: "width 220ms ease",
                  }}
                />
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13, lineHeight: 1.5 }}>
                The first 9 items are bonus-weighted. Food, Activities, and Habitat are the seed lattice.
              </div>
              <div style={{ marginTop: 12, display: "flex", gap: 8, flexWrap: "wrap" }}>
                <button
                  type="button"
                  onClick={loadStarterDeck}
                  style={{
                    borderRadius: 999,
                    border: `1px solid ${CATEGORY_META.food.accent}55`,
                    background: `${CATEGORY_META.food.accent}18`,
                    color: CATEGORY_META.food.accent,
                    padding: "8px 12px",
                    fontSize: 12,
                    fontWeight: 700,
                    cursor: "pointer",
                  }}
                >
                  Load starter constellation
                </button>
                <button
                  type="button"
                  onClick={resetCart}
                  style={{
                    borderRadius: 999,
                    border: "1px solid rgba(255,255,255,0.12)",
                    background: "rgba(255,255,255,0.04)",
                    color: "#efe7db",
                    padding: "8px 12px",
                    fontSize: 12,
                    fontWeight: 700,
                    cursor: "pointer",
                  }}
                >
                  Clear cart
                </button>
                <span style={{ ...chipStyle(warmth.color), borderColor: `${warmth.color}55` }}>
                  {warmth.emoji} {warmth.label}
                </span>
              </div>
            </div>
          </div>
        </section>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.2fr) minmax(340px, 0.8fr)", 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" }}>Plant the cart</div>
                  <h2 style={{ margin: "6px 0 0", fontSize: 22 }}>Three categories, nine seeds</h2>
                </div>
                <div style={{ color: "#c2b7a8", fontSize: 13 }}>Any item can only appear once.</div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 12 }}>
                {(Object.keys(CATEGORY_META) as CartCategoryKey[]).map((category) => {
                  const meta = CATEGORY_META[category];
                  const count = categoryGroups[category].length;

                  return (
                    <article
                      key={category}
                      style={{
                        borderRadius: 18,
                        padding: 14,
                        background: "rgba(255,255,255,0.03)",
                        border: `1px solid ${meta.accent}22`,
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "flex-start" }}>
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4, color: meta.accent }}>
                            {meta.icon}
                            <div style={{ fontSize: 16, fontWeight: 800 }}>{meta.label}</div>
                          </div>
                          <div style={{ color: "#b8ae9f", fontSize: 13, lineHeight: 1.5 }}>{meta.prompt}</div>
                        </div>
                        <div style={{ textAlign: "right" }}>
                          <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Count</div>
                          <div style={{ fontSize: 20, fontWeight: 800, color: meta.accent }}>{count}</div>
                        </div>
                      </div>

                      <div style={{ marginTop: 12, display: "flex", gap: 8 }}>
                        <input
                          value={drafts[category]}
                          onChange={(event) => setDrafts((current) => ({ ...current, [category]: event.target.value }))}
                          onKeyDown={(event) => {
                            if (event.key === "Enter") {
                              event.preventDefault();
                              addItem(category, drafts[category]);
                            }
                          }}
                          placeholder={meta.examples[0]}
                          className="w-full rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-white placeholder:text-white/35 outline-none focus:border-white/20"
                        />
                        <button
                          type="button"
                          onClick={() => addItem(category, drafts[category])}
                          className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm font-semibold text-white transition hover:bg-white/8"
                          aria-label={`Add ${meta.label} item`}
                        >
                          <Plus className="h-4 w-4" />
                        </button>
                      </div>

                      <div style={{ marginTop: 10, display: "flex", gap: 6, flexWrap: "wrap" }}>
                        {meta.examples.map((example) => (
                          <button
                            key={example}
                            type="button"
                            onClick={() => addExample(category, example)}
                            style={{
                              borderRadius: 999,
                              border: `1px solid ${meta.accent}40`,
                              background: `${meta.accent}18`,
                              color: meta.accent,
                              padding: "5px 10px",
                              fontSize: 12,
                              cursor: "pointer",
                            }}
                          >
                            {shortLabel(example, 18)}
                          </button>
                        ))}
                      </div>

                      <div style={{ marginTop: 12, display: "grid", gap: 8 }}>
                        {categoryGroups[category].length === 0 ? (
                          <div style={{ color: "#8f8a95", fontSize: 13, lineHeight: 1.5 }}>No items yet. This category still needs a seed.</div>
                        ) : (
                          categoryGroups[category].map((item) => (
                            <button
                              key={item.id}
                              type="button"
                              onClick={() => setSelectedId(item.id)}
                              style={{
                                borderRadius: 14,
                                border: selectedId === item.id ? `1px solid ${meta.accent}66` : "1px solid rgba(255,255,255,0.08)",
                                background: selectedId === item.id ? `${meta.accent}12` : "rgba(255,255,255,0.03)",
                                padding: 12,
                                textAlign: "left",
                                cursor: "pointer",
                                display: "grid",
                                gap: 6,
                              }}
                            >
                              <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                                <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                                  <span style={{ color: meta.accent }}>{categoryIcon(category)}</span>
                                  <span style={{ fontWeight: 700, color: "#f7efe2", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.name}</span>
                                </div>
                                <div style={{ display: "flex", gap: 6 }}>
                                  <button
                                    type="button"
                                    onClick={(event) => {
                                      event.stopPropagation();
                                      toggleFeatured(item.id);
                                    }}
                                    style={{
                                      borderRadius: 999,
                                      border: item.featured ? `1px solid ${meta.accent}66` : "1px solid rgba(255,255,255,0.10)",
                                      background: item.featured ? `${meta.accent}20` : "rgba(255,255,255,0.04)",
                                      color: item.featured ? meta.accent : "#efe7db",
                                      padding: "5px 8px",
                                      fontSize: 11,
                                      fontWeight: 700,
                                      cursor: "pointer",
                                    }}
                                  >
                                    <Star className="h-3.5 w-3.5" />
                                  </button>
                                  <button
                                    type="button"
                                    onClick={(event) => {
                                      event.stopPropagation();
                                      removeItem(item.id);
                                    }}
                                    style={{
                                      borderRadius: 999,
                                      border: "1px solid rgba(255,255,255,0.10)",
                                      background: "rgba(255,255,255,0.04)",
                                      color: "#efe7db",
                                      padding: "5px 8px",
                                      fontSize: 11,
                                      fontWeight: 700,
                                      cursor: "pointer",
                                    }}
                                  >
                                    <Trash2 className="h-3.5 w-3.5" />
                                  </button>
                                </div>
                              </div>
                              <div style={{ color: "#b8ae9f", fontSize: 12, lineHeight: 1.45 }}>{CATEGORY_META[category].reveal}</div>
                            </button>
                          ))
                        )}
                      </div>
                    </article>
                  );
                })}
              </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" }}>Lattice preview</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>The first 9 seeds become a constellation</h3>
                </div>
                <div style={{ color: "#c2b7a8", fontSize: 13 }}>Tap a hex to inspect an item.</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={latticeNodes}
                  size="full"
                  activeNodeId={selectedItem?.id}
                  showLabels={true}
                  onNodeClick={(node) => {
                    if (node.id !== "center") setSelectedId(node.id);
                  }}
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10, marginTop: 14 }}>
                <MiniStat label="Planted" value={`${totalItems}`} detail="Any item can only appear once" tone={warmth.color} />
                <MiniStat label="Categories" value={`${filledCategories}/3`} detail="Food / Activities / Habitat" tone={warmth.color} />
                <MiniStat label="Featured" value={`${featuredItems.length}/3`} detail="Three max, by choice" tone={warmth.color} />
                <MiniStat label="Score" value={scoreLabel(resonanceScore)} detail={`${resonanceScore} resonance`} tone={warmth.color} />
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <ResonanceIndicators
                title="Resonance field"
                subtitle="Cart signals become ambient warmth when the field is coherent enough to read."
                score={resonanceScore}
                recentHours={24}
                signals={resonanceSignals}
                ringDistance={6}
              />
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Selected item</div>
              {selectedItem ? (
                <div style={{ marginTop: 12, display: "grid", gap: 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "flex-start" }}>
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, color: CATEGORY_META[selectedItem.category].accent }}>
                        {categoryIcon(selectedItem.category)}
                        <span style={{ fontSize: 14, fontWeight: 700 }}>{CATEGORY_META[selectedItem.category].label}</span>
                      </div>
                      <h3 style={{ margin: "6px 0 0", fontSize: 22, lineHeight: 1.1 }}>{selectedItem.name}</h3>
                      <p style={{ margin: "6px 0 0", color: "#b8ae9f", fontSize: 13, lineHeight: 1.5 }}>{CATEGORY_META[selectedItem.category].reveal}</p>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Added</div>
                      <div style={{ color: "#efe7db", fontWeight: 800 }}>{formatAgo(selectedItem.addedAt)}</div>
                    </div>
                  </div>

                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                    <button
                      type="button"
                      onClick={() => toggleFeatured(selectedItem.id)}
                      style={{
                        borderRadius: 999,
                        border: `1px solid ${CATEGORY_META[selectedItem.category].accent}66`,
                        background: `${CATEGORY_META[selectedItem.category].accent}18`,
                        color: CATEGORY_META[selectedItem.category].accent,
                        padding: "8px 12px",
                        fontSize: 12,
                        fontWeight: 700,
                        cursor: "pointer",
                      }}
                    >
                      {selectedItem.featured ? "Unfeature" : "Feature this item"}
                    </button>
                    <button
                      type="button"
                      onClick={() => removeItem(selectedItem.id)}
                      style={{
                        borderRadius: 999,
                        border: "1px solid rgba(255,255,255,0.12)",
                        background: "rgba(255,255,255,0.04)",
                        color: "#efe7db",
                        padding: "8px 12px",
                        fontSize: 12,
                        fontWeight: 700,
                        cursor: "pointer",
                      }}
                    >
                      Remove
                    </button>
                  </div>

                  <div style={{ display: "grid", gap: 10 }}>
                    <InfoPill label="Featured" value={selectedItem.featured ? "Yes" : "No"} tone={selectedItem.featured ? CATEGORY_META[selectedItem.category].accent : "#94a3b8"} />
                    <InfoPill label="Category signal" value={categorySignal(selectedItem.category)} tone={CATEGORY_META[selectedItem.category].accent} />
                    <InfoPill label="Exactness" value={selectedItem.name.split(/\s+/).filter(Boolean).length >= 2 ? "Specific" : "Simple"} tone={CATEGORY_META[selectedItem.category].accent} />
                  </div>
                </div>
              ) : (
                <div style={{ marginTop: 12, color: "#b8ae9f", fontSize: 14, lineHeight: 1.55 }}>No item selected yet. Add a seed, then tap it in the lattice or list.</div>
              )}
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Visibility ladder</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                {VISIBILITY_ROWS.map((row) => (
                  <div
                    key={row.viewer}
                    style={{
                      borderRadius: 16,
                      padding: 12,
                      background: "rgba(255,255,255,0.03)",
                      border: "1px solid rgba(255,255,255,0.08)",
                      display: "grid",
                      gap: 4,
                    }}
                  >
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                      <div style={{ color: "#f7efe2", fontWeight: 700 }}>{row.viewer}</div>
                      <div style={{ color: "#b8ae9f", fontSize: 12 }}>{row.viewer === "Your R1" ? "Deepest" : row.viewer === "Your R6" ? "Ambient" : "Tiered"}</div>
                    </div>
                    <div style={{ color: "#b8ae9f", fontSize: 13, lineHeight: 1.45 }}>{row.sees}</div>
                  </div>
                ))}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>History</div>
              <div style={{ marginTop: 12, display: "grid", gap: 10 }}>
                {history.length === 0 ? (
                  <div style={{ color: "#8f8a95", fontSize: 14, lineHeight: 1.55 }}>Removed items move here. Nothing has been dismissed yet.</div>
                ) : (
                  history.map((entry) => (
                    <div
                      key={`${entry.id}-${entry.removedAt}`}
                      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>
                        <div style={{ color: "#f7efe2", fontWeight: 700 }}>{entry.name}</div>
                        <div style={{ color: "#b8ae9f", fontSize: 12 }}>{formatAgo(entry.removedAt)} · {CATEGORY_META[entry.category].label}</div>
                      </div>
                      <button
                        type="button"
                        onClick={() => restoreItem(entry)}
                        style={{
                          borderRadius: 999,
                          border: "1px solid rgba(255,255,255,0.12)",
                          background: "rgba(255,255,255,0.04)",
                          color: "#efe7db",
                          padding: "7px 10px",
                          fontSize: 12,
                          fontWeight: 700,
                          cursor: "pointer",
                        }}
                      >
                        Restore
                      </button>
                    </div>
                  ))
                )}
              </div>
            </section>
          </aside>
        </div>
      </div>
    </div>
  );
}

function chipStyle(color: string) {
  return {
    borderRadius: 999,
    border: `1px solid ${color}55`,
    background: `${color}18`,
    color,
    padding: "8px 12px",
    fontSize: 12,
    fontWeight: 700,
  } as CSSProperties;
}

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

function InfoPill({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center", padding: "10px 12px", borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ color: "#c8bfaf", fontSize: 14 }}>{label}</div>
      <div style={{ color: tone, fontWeight: 800, fontSize: 14 }}>{value}</div>
    </div>
  );
}
