import { useMemo, useState, type CSSProperties } from "react";
import ResonanceIndicators, { type ResonanceSignal } from "./ResonanceIndicators";

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

export interface CartItem {
  id: string;
  category: CartCategoryKey;
  name: string;
  note?: string;
  featured?: boolean;
}

interface CartHistoryItem extends CartItem {
  removedAt: number;
}

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

const CATEGORY_META: Record<
  CartCategoryKey,
  {
    label: string;
    emoji: string;
    prompt: string;
    accent: string;
    examples: string[];
    reveal: string;
  }
> = {
  food: {
    label: "Food",
    emoji: "🍜",
    prompt: "How you eat, where you eat, how you return.",
    accent: "#d4a574",
    examples: ["Ramen Bar X", "Farmers market on Saturdays", "My own cooking"],
    reveal: "social rhythm, adventurousness, values, and domestic investment",
  },
  activities: {
    label: "Activities",
    emoji: "⛰️",
    prompt: "How you spend energy when nobody is asking.",
    accent: "#8ab6d6",
    examples: ["Rock climbing on weekends", "Jazz vinyl listening", "Language learning apps"],
    reveal: "energy, social style, creator vs. consumer orientation, planning tendency",
  },
  habitat: {
    label: "Habitat",
    emoji: "🪴",
    prompt: "What your space says when nobody is watching.",
    accent: "#9ac18a",
    examples: ["My plants (14 and counting)", "Minimalist kitchen", "Bookshelf I actually use"],
    reveal: "nurturing instinct, standards, aesthetic sensibility, and domestic values",
  },
};

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" },
];

const DEFAULT_RECENT_SIGNALS = [
  { label: "Exact overlap", detail: "Ramen Bar X matched across two carts.", delta: "+1 Hearts" },
  { label: "Category congruence", detail: "Outdoor activities aligned on both sides.", delta: "+1 Stars" },
  { label: "Weekly presence", detail: "A 7-day streak pushed the field brighter.", delta: "+3 Balloons" },
];

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

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

function isDuplicateItem(name: string, items: CartItem[]) {
  const target = normalize(name);
  return items.some((item) => normalize(item.name) === target);
}

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

function clamp(value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value));
}

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 floatLabel(count: number) {
  if (count >= 5) return { label: "Cloud Walking", range: "500+" };
  if (count >= 3) return { label: "Drifting", range: "150-499" };
  if (count >= 2) return { label: "Airy", range: "50-149" };
  if (count >= 1) return { label: "Rising", range: "10-49" };
  return { label: "Grounded", range: "0-9" };
}

function categoryCounts(items: CartItem[]) {
  return {
    food: items.filter((item) => item.category === "food"),
    activities: items.filter((item) => item.category === "activities"),
    habitat: items.filter((item) => item.category === "habitat"),
  };
}

function formatRemovedAt(timestamp: number) {
  const diff = Date.now() - timestamp;
  const minutes = Math.max(1, Math.round(diff / 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 itemText(item: CartItem) {
  return `${item.name} ${item.note ?? ""}`.trim();
}

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

export default function CartSystemPanel({
  title = "Cart UI",
  subtitle = "Your cart is an identity mirror. Plant the first 9 and let resonance grow.",
  initialItems = [],
  onChange,
}: CartSystemPanelProps) {
  const [items, setItems] = useState<CartItem[]>(initialItems);
  const [history, setHistory] = useState<CartHistoryItem[]>([]);
  const [drafts, setDrafts] = useState<Record<CartCategoryKey, { name: string; note: string }>>({
    food: { name: "", note: "" },
    activities: { name: "", note: "" },
    habitat: { name: "", note: "" },
  });
  const [selectedCategory, setSelectedCategory] = useState<CartCategoryKey>("food");

  const updateItems = (next: CartItem[]) => {
    setItems(next);
    onChange?.(next);
  };

  const grouped = useMemo(() => categoryCounts(items), [items]);
  const featuredItems = useMemo(() => items.filter((item) => item.featured).slice(0, 3), [items]);
  const recentHistory = useMemo(() => history.slice(0, 6), [history]);
  const firstNineProgress = clamp((items.length / 9) * 100, 0, 100);
  const filledCategories = Object.values(grouped).filter((group) => group.length > 0).length;
  const specificityHits = items.filter((item) => item.name.trim().split(/\s+/).filter(Boolean).length >= 2 || /\d/.test(item.name)).length;
  const valueHits = countKeywords(
    items.map(itemText).join(" "),
    ["organic", "local", "sustainable", "creative", "learning", "weekly", "daily", "ritual", "plants", "dog", "home", "music", "climbing", "hiking", "garden", "minimalist", "secondhand"],
  );
  const spread = Math.abs(grouped.food.length - grouped.activities.length) + Math.abs(grouped.activities.length - grouped.habitat.length) + Math.abs(grouped.habitat.length - grouped.food.length);
  const featuredCount = featuredItems.length;
  const resonanceScore = Math.round(
    clamp(
      (
        (specificityHits * 18 + featuredCount * 6 + (items.length > 0 ? 8 : 0)) * 1.5 +
        (filledCategories * 28 + Math.min(items.length * 3, 24)) * 1.0 +
        (100 - spread * 14 + (filledCategories === 3 ? 12 : filledCategories * 5)) * 1.2 +
        (valueHits * 14 + (items.length >= 6 ? 16 : 0)) * 1.5 +
        (items.length * 8 + featuredCount * 10) * 0.8
      ) /
        6,
      0,
      100,
    ),
  );
  const resonanceLabel = scoreLabel(resonanceScore);
  const float = floatLabel(items.filter((item) => item.category === "habitat").length + featuredCount + Math.floor(items.length / 3));

  const signalScores: ResonanceSignal[] = [
    {
      key: "hearts",
      score: clamp(specificityHits * 18 + featuredCount * 6 + (items.length > 0 ? 8 : 0), 0, 100),
      note: "Exact items, featured items, and specificity",
    },
    {
      key: "stars",
      score: clamp(filledCategories * 28 + Math.min(items.length * 3, 24), 0, 100),
      note: "Category coverage across Food / Activities / Habitat",
    },
    {
      key: "moons",
      score: clamp(100 - spread * 14 + (filledCategories === 3 ? 12 : filledCategories * 5), 0, 100),
      note: "Balance across the three categories",
    },
    {
      key: "hourglasses",
      score: clamp(valueHits * 14 + (items.length >= 6 ? 16 : 0), 0, 100),
      note: "Values language and repetition over time",
    },
    {
      key: "balloons",
      score: clamp(items.length * 8 + featuredCount * 10, 0, 100),
      note: "Presence, consistency, and tenure",
    },
  ];

  const addItem = (category: CartCategoryKey) => {
    const draft = drafts[category];
    const name = draft.name.trim();
    if (!name) return;
    if (isDuplicateItem(name, items)) return;

    const next = [
      ...items,
      {
        id: makeId(category),
        category,
        name,
        note: draft.note.trim() || undefined,
      },
    ];

    updateItems(next);
    setDrafts((current) => ({
      ...current,
      [category]: { name: "", note: "" },
    }));
  };

  const removeItem = (id: string) => {
    const removed = items.find((item) => item.id === id);
    if (!removed) return;

    setHistory((current) => [{ ...removed, removedAt: Date.now() }, ...current].slice(0, 12));
    updateItems(items.filter((item) => item.id !== id));
  };

  const restoreItem = (historyItem: CartHistoryItem) => {
    if (isDuplicateItem(historyItem.name, items)) return;
    const { removedAt: _removedAt, ...item } = historyItem;
    updateItems([...items, item]);
    setHistory((current) => current.filter((entry) => entry.id !== historyItem.id));
  };

  const toggleFeatured = (id: string) => {
    const featuredLimit = 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 (featuredLimit >= 3) return item;
      return { ...item, featured: true };
    });

    updateItems(next);
  };

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

  const inputStyle: CSSProperties = {
    width: "100%",
    borderRadius: 14,
    border: "1px solid rgba(255,255,255,0.12)",
    background: "rgba(7, 7, 10, 0.75)",
    color: "#f7efe2",
    padding: "12px 12px",
    outline: "none",
    fontSize: 14,
  };

  const chipStyle: CSSProperties = {
    borderRadius: 999,
    border: "1px solid rgba(255,255,255,0.12)",
    background: "rgba(255,255,255,0.04)",
    color: "#f4ede2",
    padding: "7px 12px",
    fontSize: 12,
    cursor: "pointer",
  };

  return (
    <section
      style={{
        minHeight: "100%",
        padding: 24,
        background:
          "radial-gradient(circle at top, rgba(212,165,116,0.12), transparent 36%), radial-gradient(circle at 80% 20%, rgba(126,184,201,0.10), transparent 30%), linear-gradient(180deg, #09090d 0%, #111117 100%)",
        color: "#efe7db",
        fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
      }}
    >
      <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: 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: 300, maxWidth: 390, flex: 1, padding: 16, borderRadius: 18, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Resonance score</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{resonanceLabel}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Float level</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: CATEGORY_META.habitat.accent }}>{float.label}</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: `${resonanceScore}%`,
                      height: "100%",
                      borderRadius: 999,
                      background: "linear-gradient(90deg, #d4a574 0%, #7eb8c9 50%, #d4a8b4 100%)",
                      transition: "width 220ms ease",
                    }}
                  />
                </div>
                <div style={{ color: "#d8d0c2", fontSize: 13, minWidth: 44, textAlign: "right" }}>{resonanceScore}</div>
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13, lineHeight: 1.5 }}>
                Credits are contribution, not access. The only thing you can buy is a clearer reading of your field.
              </div>
            </div>
          </div>
        </section>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.35fr) minmax(320px, 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 first 9</div>
                  <h2 style={{ margin: "6px 0 0", fontSize: 22 }}>{items.length}/9 planted</h2>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {(Object.keys(CATEGORY_META) as CartCategoryKey[]).map((category) => {
                    const meta = CATEGORY_META[category];
                    const active = selectedCategory === category;
                    return (
                      <button
                        key={category}
                        type="button"
                        onClick={() => setSelectedCategory(category)}
                        style={{
                          ...chipStyle,
                          background: active ? `${meta.accent}22` : chipStyle.background,
                          borderColor: active ? `${meta.accent}55` : "rgba(255,255,255,0.12)",
                          color: active ? meta.accent : chipStyle.color,
                        }}
                      >
                        {meta.label}
                      </button>
                    );
                  })}
                </div>
              </div>
              <div style={{ 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 }}>
                First 3 items per category are bonus-weighted. They define the initial resonance field.
              </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" }}>Categories</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>Food, Activities, Habitat</h3>
                </div>
                <div style={{ color: "#bdb3a5", fontSize: 12 }}>Any item can appear once. Removed items move to history.</div>
              </div>

              <div style={{ display: "grid", gap: 14 }}>
                {(Object.keys(CATEGORY_META) as CartCategoryKey[]).map((category) => {
                  const meta = CATEGORY_META[category];
                  const itemsForCategory = grouped[category];
                  const seeded = itemsForCategory.slice(0, 3);
                  const active = selectedCategory === category;
                  const featuredHere = featuredItems.filter((item) => item.category === category);

                  return (
                    <section key={category} style={{ borderRadius: 18, padding: 16, border: active ? `1px solid ${meta.accent}66` : "1px solid rgba(255,255,255,0.08)", background: active ? `${meta.accent}14` : "rgba(255,255,255,0.03)" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 12 }}>
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                            <div style={{ fontSize: 24 }}>{meta.emoji}</div>
                            <div style={{ fontWeight: 800, fontSize: 18 }}>{meta.label}</div>
                          </div>
                          <div style={{ color: "#a9a3b8", fontSize: 13, maxWidth: 680, lineHeight: 1.45 }}>{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 }}>{itemsForCategory.length}</div>
                        </div>
                      </div>

                      <div style={{ display: "grid", gap: 10, gridTemplateColumns: "minmax(0, 1fr) auto" }}>
                        <input
                          value={drafts[category].name}
                          onChange={(event) =>
                            setDrafts((current) => ({
                              ...current,
                              [category]: { ...current[category], name: event.target.value },
                            }))
                          }
                          onKeyDown={(event) => {
                            if (event.key === "Enter") {
                              event.preventDefault();
                              addItem(category);
                            }
                          }}
                          placeholder={`Add a ${meta.label.toLowerCase()} item`}
                          style={inputStyle}
                        />
                        <button
                          type="button"
                          onClick={() => addItem(category)}
                          style={{
                            borderRadius: 14,
                            border: "none",
                            background: `linear-gradient(180deg, ${meta.accent}, ${meta.accent}cc)`,
                            color: "#111117",
                            fontWeight: 700,
                            padding: "12px 16px",
                            cursor: "pointer",
                            minWidth: 104,
                          }}
                        >
                          Plant
                        </button>
                      </div>

                      <input
                        value={drafts[category].note}
                        onChange={(event) =>
                          setDrafts((current) => ({
                            ...current,
                            [category]: { ...current[category], note: event.target.value },
                          }))
                        }
                        onKeyDown={(event) => {
                          if (event.key === "Enter") {
                            event.preventDefault();
                            addItem(category);
                          }
                        }}
                        placeholder="Optional note"
                        style={{ ...inputStyle, marginTop: 10, fontSize: 13, color: "#d8d0c2" }}
                      />

                      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
                        {meta.examples.map((example) => (
                          <button
                            key={example}
                            type="button"
                            onClick={() =>
                              setDrafts((current) => ({
                                ...current,
                                [category]: { ...current[category], name: example },
                              }))
                            }
                            style={chipStyle}
                          >
                            {example}
                          </button>
                        ))}
                      </div>

                      <div style={{ marginTop: 12, display: "grid", gap: 12, gridTemplateColumns: "repeat(auto-fit, minmax(82px, 1fr))" }}>
                        {[0, 1, 2].map((slot) => {
                          const seededItem = seeded[slot];
                          return (
                            <div key={slot} style={{ minHeight: 60, borderRadius: 14, border: `1px solid ${seededItem ? meta.accent : "rgba(255,255,255,0.12)"}`, background: seededItem ? `${meta.accent}18` : "rgba(255,255,255,0.03)", padding: 8, display: "flex", alignItems: "center", justifyContent: "center", color: seededItem ? "#f7efe2" : "#6b7280", fontSize: 12, textAlign: "center", lineHeight: 1.35 }}>
                              {seededItem ? seededItem.name : `Seed ${slot + 1}`}
                            </div>
                          );
                        })}
                      </div>
                      <div style={{ marginTop: 8, color: "#c0b5a7", fontSize: 12 }}>{seeded.length}/3 planted in this category.</div>

                      <div style={{ marginTop: 12, display: "grid", gap: 10 }}>
                        {itemsForCategory.length === 0 ? (
                          <div style={{ borderRadius: 16, border: "1px dashed rgba(255,255,255,0.12)", padding: 16, color: "#8f95a3", background: "rgba(255,255,255,0.02)" }}>
                            No items yet. Add the first seed here.
                          </div>
                        ) : (
                          itemsForCategory.map((item) => (
                            <article key={item.id} style={{ borderRadius: 16, padding: 14, background: item.featured ? `${meta.accent}16` : "rgba(255,255,255,0.03)", border: item.featured ? `1px solid ${meta.accent}66` : "1px solid rgba(255,255,255,0.08)" }}>
                              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "flex-start" }}>
                                <div>
                                  <div style={{ fontWeight: 700, fontSize: 15 }}>{item.name}</div>
                                  {item.note && <div style={{ color: "#b6ac9f", marginTop: 4, fontSize: 13, lineHeight: 1.45 }}>{item.note}</div>}
                                </div>
                                <button
                                  type="button"
                                  onClick={() => toggleFeatured(item.id)}
                                  style={{
                                    borderRadius: 999,
                                    border: "1px solid rgba(255,255,255,0.12)",
                                    background: item.featured ? `${meta.accent}22` : "rgba(255,255,255,0.03)",
                                    color: item.featured ? "#f5d79b" : "#d8d0c2",
                                    padding: "6px 10px",
                                    fontSize: 12,
                                    cursor: "pointer",
                                    whiteSpace: "nowrap",
                                  }}
                                >
                                  {item.featured ? "★ Featured" : "Feature"}
                                </button>
                              </div>

                              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, flexWrap: "wrap", marginTop: 10 }}>
                                <div style={{ fontSize: 12, color: "#a7a1b3" }}>{meta.reveal}</div>
                                <button
                                  type="button"
                                  onClick={() => removeItem(item.id)}
                                  style={{ border: "none", background: "transparent", color: "#a9afbc", cursor: "pointer", fontSize: 12 }}
                                >
                                  Remove
                                </button>
                              </div>
                            </article>
                          ))
                        )}
                      </div>

                      {featuredHere.length > 0 && (
                        <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 8 }}>
                          {featuredHere.map((item) => (
                            <span key={item.id} style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: `${meta.accent}22`, color: "#f7efe2", border: `1px solid ${meta.accent}44` }}>
                              Featured · {item.name}
                            </span>
                          ))}
                        </div>
                      )}
                    </section>
                  );
                })}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Cart history</div>
              <p style={{ margin: "8px 0 0", color: "#a8a8b3", fontSize: 14, lineHeight: 1.5 }}>
                Removed items move to history instead of disappearing. They still carry signal, so change stays readable.
              </p>

              <div style={{ display: "grid", gap: 10, marginTop: 14 }}>
                {recentHistory.length === 0 ? (
                  <div style={{ borderRadius: 16, border: "1px dashed rgba(255,255,255,0.12)", padding: 16, color: "#8f95a3", background: "rgba(255,255,255,0.02)" }}>
                    No removals yet. When you prune an item, it will appear here.
                  </div>
                ) : (
                  recentHistory.map((item) => (
                    <div key={item.id} style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                        <div>
                          <div style={{ fontWeight: 700, fontSize: 14 }}>{item.name}</div>
                          <div style={{ color: "#a6a1b0", fontSize: 12, marginTop: 3 }}>
                            {CATEGORY_META[item.category].label} · removed {formatRemovedAt(item.removedAt)}
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => restoreItem(item)}
                          style={{
                            borderRadius: 999,
                            border: "1px solid rgba(255,255,255,0.12)",
                            background: "rgba(255,255,255,0.03)",
                            color: "#f5d79b",
                            padding: "6px 10px",
                            fontSize: 12,
                            cursor: "pointer",
                            whiteSpace: "nowrap",
                          }}
                        >
                          Restore
                        </button>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <ResonanceIndicators
                compact
                title="Cart resonance"
                subtitle="A passive field readout for the last 24 hours of signal."
                score={resonanceScore}
                recentHours={24}
                signals={signalScores}
                ringDistance={items.length >= 9 ? 6 : items.length >= 6 ? 5 : items.length >= 3 ? 4 : 2}
              />
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Visibility</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)" }}>
                    <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{row.viewer}</div>
                    <div style={{ marginTop: 6, color: "#d8d0c2", fontSize: 14, lineHeight: 1.55 }}>{row.sees}</div>
                  </div>
                ))}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Shape of the cart</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                <SummaryRow label="Filled categories" value={`${filledCategories}/3`} tone="#f5d79b" />
                <SummaryRow label="Specific items" value={`${specificityHits}`} tone="#d4a574" />
                <SummaryRow label="Featured items" value={`${featuredCount}/3`} tone="#ff9f43" />
                <SummaryRow label="First 9 progress" value={`${items.length}/9`} tone="#9ac18a" />
              </div>

              <div style={{ marginTop: 16, padding: 14, borderRadius: 16, background: "rgba(255,255,255,0.03)", color: "#d8d0c2", lineHeight: 1.55 }}>
                {items.length === 0
                  ? "Start with a few concrete things you actually do, eat, and live with. The lattice gets sharper from specificity, not aspiration."
                  : items.length < 9
                    ? "You are still planting the first 9. These are the bonus-weighted seeds that define the initial resonance field."
                    : "The first 9 are planted. The cart can now broadcast a fuller pattern into the Current."}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>How the cart reads</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                <SummaryCard title="Food" text="Social rhythm, adventurousness, values, health orientation, domestic investment, and budget priorities." tone={CATEGORY_META.food.accent} />
                <SummaryCard title="Activities" text="Energy level, social style, creator vs. consumer orientation, physical balance, and planning style." tone={CATEGORY_META.activities.accent} />
                <SummaryCard title="Habitat" text="Nurturing instinct, standards, aesthetic sensibility, and who you are when nobody is visiting." tone={CATEGORY_META.habitat.accent} />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Recent signals</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                {DEFAULT_RECENT_SIGNALS.map((signal) => (
                  <div key={signal.label} style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
                      <div style={{ fontWeight: 800 }}>{signal.label}</div>
                      <div style={{ color: "#f5d79b", fontSize: 12 }}>{signal.delta}</div>
                    </div>
                    <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 13, lineHeight: 1.5 }}>{signal.detail}</div>
                  </div>
                ))}
              </div>
            </section>
          </aside>
        </div>
      </div>
    </section>
  );
}

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

function SummaryCard({ title, text, tone }: { title: string; text: string; tone: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: `1px solid ${tone}44` }}>
      <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>
  );
}
