import { useMemo, useState, type CSSProperties } from "react";

export type CartCategoryKey = "food" | "activities" | "habitat";
export type ResonanceKey = "hearts" | "stars" | "moons" | "hourglasses" | "balloons";

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

interface CartHistoryItem extends CartItem {
  removedAt: number;
}

export interface CartMirrorProps {
  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[];
  }
> = {
  food: {
    label: "Food",
    emoji: "🍜",
    prompt: "How you eat, where you eat, what you return to.",
    accent: "#d4a574",
    examples: ["Ramen Bar X", "Farmers market on Saturdays", "My own cooking"],
  },
  activities: {
    label: "Activities",
    emoji: "⛰️",
    prompt: "How you spend energy when nobody is asking for it.",
    accent: "#8ab6d6",
    examples: ["Rock climbing on weekends", "Jazz vinyl listening", "Language learning apps"],
  },
  habitat: {
    label: "Habitat",
    emoji: "🪴",
    prompt: "What your space says about you when nobody is watching.",
    accent: "#9ac18a",
    examples: ["My plants (14 and counting)", "Minimalist kitchen", "Bookshelf I actually use"],
  },
};

const SIGNAL_META: Record<
  ResonanceKey,
  {
    label: string;
    emoji: string;
    description: string;
    color: string;
  }
> = {
  hearts: {
    label: "Hearts",
    emoji: "❤",
    description: "Direct overlap potential: specific items that can meet exactly.",
    color: "#ff6b8a",
  },
  stars: {
    label: "Stars",
    emoji: "⭐",
    description: "Category congruence: the same kind of life in different forms.",
    color: "#ffd66b",
  },
  moons: {
    label: "Moons",
    emoji: "☾",
    description: "Complementary rhythm: one cart completes a gap in another.",
    color: "#a8d4ff",
  },
  hourglasses: {
    label: "Hourglasses",
    emoji: "⏳",
    description: "Values alignment: repeated patterns reveal worldview.",
    color: "#c9a8d4",
  },
  balloons: {
    label: "Balloons",
    emoji: "🎈",
    description: "Presence and continuity: how steadily the cart is tended.",
    color: "#ff9f43",
  },
};

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 "Hot";
  if (score >= 41) return "Warm";
  if (score >= 21) return "Cool";
  return "Quiet";
}

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

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

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 makeId(prefix: string) {
  return `${prefix}-${Math.random().toString(36).slice(2, 9)}-${Date.now().toString(36)}`;
}

function isSpecificItem(name: string) {
  const words = name.trim().split(/\s+/).filter(Boolean);
  return words.length >= 2 || /\d/.test(name) || /[A-Z].*[A-Z]/.test(name);
}

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

function seedItemCount(items: CartItem[], category: CartCategoryKey) {
  return items.filter((item) => item.category === category).slice(0, 3).length;
}

function itemText(item: CartItem) {
  return `${item.name} ${item.note ?? ""}`.trim();
}

export default function CartMirror({
  title = "Cart Mirror",
  subtitle = "Your cart is an identity field. Plant the first 9 and let resonance grow.",
  initialItems = [],
  onChange,
}: CartMirrorProps) {
  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 updateItems = (next: CartItem[]) => {
    setItems(next);
    onChange?.(next);
  };

  const categoryItems = useMemo(
    () => ({
      food: items.filter((item) => item.category === "food"),
      activities: items.filter((item) => item.category === "activities"),
      habitat: items.filter((item) => item.category === "habitat"),
    }),
    [items],
  );

  const featuredItems = useMemo(() => items.filter((item) => item.featured).slice(0, 3), [items]);
  const filledCategories = Object.values(categoryItems).filter((group) => group.length > 0).length;
  const firstNineProgress = clamp((items.length / 9) * 100, 0, 100);
  const firstNineRemaining = Math.max(9 - items.length, 0);
  const totalFeatured = featuredItems.length;
  const recentHistory = useMemo(() => history.slice(0, 5), [history]);

  const joinedText = items.map(itemText).join(" ");
  const valueHits = countKeywords(joinedText, [
    "organic",
    "local",
    "sustainable",
    "creative",
    "learning",
    "weekly",
    "daily",
    "ritual",
    "plants",
    "dog",
    "home",
    "music",
    "climbing",
    "hiking",
    "garden",
    "minimalist",
    "secondhand",
  ]);

  const specificityHits = items.filter((item) => isSpecificItem(item.name)).length;
  const categoryCounts = Object.values(categoryItems).map((group) => group.length);
  const spread =
    Math.abs(categoryCounts[0] - categoryCounts[1]) +
    Math.abs(categoryCounts[1] - categoryCounts[2]) +
    Math.abs(categoryCounts[2] - categoryCounts[0]);

  const signalScores: Record<ResonanceKey, number> = {
    hearts: clamp(specificityHits * 18 + totalFeatured * 6 + (items.length > 0 ? 8 : 0), 0, 100),
    stars: clamp(filledCategories * 28 + Math.min(items.length * 3, 24), 0, 100),
    moons: clamp(100 - spread * 14 + (filledCategories === 3 ? 12 : filledCategories * 5), 0, 100),
    hourglasses: clamp(valueHits * 14 + (items.length >= 6 ? 16 : 0), 0, 100),
    balloons: clamp(items.length * 8 + totalFeatured * 10, 0, 100),
  };

  const resonanceSummary = useMemo(
    () =>
      (Object.keys(SIGNAL_META) as ResonanceKey[]).map((key) => ({
        key,
        score: signalScores[key],
        label: scoreLabel(signalScores[key]),
      })),
    [signalScores],
  );

  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 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 visibilityRows = [
    { viewer: "R1 · Inner Circle", sees: "Full cart — every item, every category" },
    { viewer: "R2 · Archetypes", sees: "Category types — Food / Activities / Habitat" },
    { viewer: "R3 · The Longing", sees: "Longing patterns — seasonal and monthly trends" },
    { viewer: "R4 · The Echo", sees: "Full cart + creative output" },
    { viewer: "R5 · The Wave", sees: "Daily sustained patterns" },
    { viewer: "R6 · The Current", sees: "Ambient warmth only (hot / warm / cool)" },
    { viewer: "Non-connected users", sees: "Profile and 3 featured items only" },
  ];

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

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

  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: "11px 12px",
    outline: "none",
    fontSize: 14,
  };

  const sectionLabel: CSSProperties = {
    fontSize: 12,
    letterSpacing: "0.12em",
    textTransform: "uppercase",
    color: "#9ca3af",
    marginBottom: 6,
  };

  return (
    <div
      style={{
        minHeight: "100%",
        padding: 24,
        background:
          "radial-gradient(circle at top, rgba(212,165,116,0.12), transparent 36%), linear-gradient(180deg, #09090d 0%, #111117 100%)",
        color: "#efe7db",
        fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
      }}
    >
      <div style={{ maxWidth: 1180, margin: "0 auto", display: "grid", gap: 18 }}>
        <div style={{ ...cardStyle, padding: 22 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 18, flexWrap: "wrap" }}>
            <div style={{ minWidth: 260, flex: 1 }}>
              <div style={sectionLabel}>Cascade / Cart System</div>
              <h2 style={{ fontSize: 32, lineHeight: 1.1, margin: 0, color: "#f6d9b3" }}>{title}</h2>
              <p style={{ margin: "10px 0 0", color: "#a8a8b3", maxWidth: 700, 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" }}>First 9</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{items.length}/9 planted</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af" }}>Featured 3</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: "#f5c16c" }}>{totalFeatured}</div>
                </div>
              </div>
              <div style={{ height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden", marginTop: 14 }}>
                <div
                  style={{
                    width: `${firstNineProgress}%`,
                    height: "100%",
                    borderRadius: 999,
                    background: "linear-gradient(90deg, #d4a574 0%, #f5c16c 50%, #ff9f43 100%)",
                    transition: "width 220ms ease",
                  }}
                />
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13 }}>
                {firstNineRemaining > 0
                  ? `${firstNineRemaining} seed${firstNineRemaining === 1 ? "" : "s"} left before the field sharpens.`
                  : "Your first 9 are planted. The constellation can start broadcasting."}
              </div>
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(320px, 0.95fr)", gap: 18, alignItems: "start" }}>
          <div style={{ display: "grid", gap: 18 }}>
            {(
              Object.keys(CATEGORY_META) as CartCategoryKey[]
            ).map((category) => {
              const meta = CATEGORY_META[category];
              const seeded = seedItemCount(items, category);
              const itemsForCategory = categoryItems[category];

              return (
                <section key={category} style={{ ...cardStyle, padding: 18, borderTop: `4px solid ${meta.accent}` }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 14 }}>
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                        <div style={{ fontSize: 26 }}>{meta.emoji}</div>
                        <div>
                          <h3 style={{ margin: 0, fontSize: 22 }}>{meta.label}</h3>
                          <div style={{ color: "#a9a3b8", fontSize: 14, marginTop: 2 }}>{meta.prompt}</div>
                        </div>
                      </div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Seed slots</div>
                      <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", marginTop: 8 }}>
                        {[0, 1, 2].map((slot) => {
                          const seededItem = itemsForCategory[slot];
                          return (
                            <div
                              key={slot}
                              style={{
                                width: 88,
                                minHeight: 56,
                                borderRadius: 14,
                                border: `1px solid ${seededItem ? meta.accent : "rgba(255,255,255,0.12)"}`,
                                background: seededItem ? `color-mix(in srgb, ${meta.accent} 18%, transparent)` : "rgba(255,255,255,0.03)",
                                padding: 8,
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                                color: seededItem ? "#f7efe2" : "#6b7280",
                                fontSize: 12,
                                textAlign: "center",
                              }}
                            >
                              {seededItem ? seededItem.name : `Seed ${slot + 1}`}
                            </div>
                          );
                        })}
                      </div>
                      <div style={{ marginTop: 8, color: "#c0b5a7", fontSize: 12 }}>{seeded}/3 planted in this category.</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: "11px 16px",
                        cursor: "pointer",
                        minWidth: 96,
                      }}
                    >
                      Plant
                    </button>
                  </div>

                  <div style={{ marginTop: 8, color: "#b6ac9f", fontSize: 12, lineHeight: 1.45 }}>
                    Duplicate names are ignored across the whole cart so the mirror stays honest.
                  </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: why this matters, where it sits, how it feels"
                    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: 14, display: "grid", gap: 10 }}>
                    {itemsForCategory.length === 0 ? (
                      <div style={{ borderRadius: 16, border: "1px dashed rgba(255,255,255,0.12)", padding: 18, color: "#8f95a3", background: "rgba(255,255,255,0.02)" }}>
                        No items yet. Add the first seed here — the first three in each category are bonus-weighted.
                      </div>
                    ) : (
                      itemsForCategory.map((item) => (
                        <article
                          key={item.id}
                          style={{
                            borderRadius: 16,
                            border: item.featured ? `1px solid ${meta.accent}` : "1px solid rgba(255,255,255,0.08)",
                            background: item.featured ? `color-mix(in srgb, ${meta.accent} 16%, transparent)` : "rgba(255,255,255,0.03)",
                            padding: 14,
                            display: "grid",
                            gap: 10,
                          }}
                        >
                          <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 }}>{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" }}>
                            <div style={{ fontSize: 12, color: "#a7a1b3" }}>Broadcasts from the identity mirror.</div>
                            <button
                              type="button"
                              onClick={() => removeItem(item.id)}
                              style={{
                                border: "none",
                                background: "transparent",
                                color: "#a9afbc",
                                cursor: "pointer",
                                fontSize: 12,
                              }}
                            >
                              Remove
                            </button>
                          </div>
                        </article>
                      ))
                    )}
                  </div>
                </section>
              );
            })}
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={sectionLabel}>Resonance field</div>
              <h3 style={{ margin: 0, fontSize: 22 }}>What this cart emits</h3>
              <p style={{ margin: "8px 0 0", color: "#a8a8b3", fontSize: 14 }}>
                These signals don&apos;t find people for you. They tell you what kind of pattern your cart is broadcasting.
              </p>

              <div style={{ display: "grid", gap: 12, marginTop: 16 }}>
                {resonanceSummary.map((entry) => {
                  const meta = SIGNAL_META[entry.key];
                  return (
                    <div
                      key={entry.key}
                      style={{
                        borderRadius: 16,
                        border: `1px solid color-mix(in srgb, ${meta.color} 36%, rgba(255,255,255,0.12))`,
                        background: `color-mix(in srgb, ${meta.color} 10%, rgba(255,255,255,0.02))`,
                        padding: 14,
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                          <div style={{ width: 28, height: 28, borderRadius: 999, background: `${meta.color}22`, display: "grid", placeItems: "center", color: meta.color, fontSize: 14 }}>
                            {meta.emoji}
                          </div>
                          <div>
                            <div style={{ fontWeight: 700 }}>{meta.label}</div>
                            <div style={{ color: "#a7a0b2", fontSize: 12 }}>{meta.description}</div>
                          </div>
                        </div>
                        <div style={{ textAlign: "right" }}>
                          <div style={{ fontSize: 11, color: "#98a0ad", textTransform: "uppercase", letterSpacing: "0.1em" }}>{entry.label}</div>
                          <div style={{ fontSize: 20, fontWeight: 800, color: meta.color }}>{entry.score}</div>
                        </div>
                      </div>

                      <div style={{ marginTop: 10, height: 8, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
                        <div
                          style={{
                            width: `${entry.score}%`,
                            height: "100%",
                            borderRadius: 999,
                            background: `linear-gradient(90deg, ${meta.color}, color-mix(in srgb, ${meta.color} 72%, white))`,
                            transition: "width 220ms ease",
                          }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={sectionLabel}>Pattern read</div>
              <h3 style={{ margin: 0, fontSize: 22 }}>The cart&apos;s shape</h3>

              <div style={{ display: "grid", gap: 10, marginTop: 14 }}>
                <Row label="Filled categories" value={`${filledCategories}/3`} />
                <Row label="Specific items" value={`${specificityHits}`} />
                <Row label="Featured items" value={`${totalFeatured}/3`} />
                <Row label="First 9 progress" value={`${items.length}/9`} />
              </div>

              <div style={{ marginTop: 16, padding: 14, borderRadius: 16, background: "rgba(255,255,255,0.03)", color: "#d8d0c2", lineHeight: 1.5 }}>
                {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>

              {featuredItems.length > 0 && (
                <div style={{ marginTop: 16 }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em", marginBottom: 8 }}>Featured 3</div>
                  <div style={{ display: "grid", gap: 8 }}>
                    {featuredItems.map((item) => (
                      <div key={item.id} style={{ borderRadius: 14, padding: 12, border: "1px solid rgba(255,255,255,0.08)", background: "rgba(255,255,255,0.03)" }}>
                        <div style={{ fontWeight: 700, fontSize: 14 }}>{item.name}</div>
                        <div style={{ color: "#a6a1b0", fontSize: 12, marginTop: 3 }}>{CATEGORY_META[item.category].label}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={sectionLabel}>Cart visibility</div>
              <h3 style={{ margin: 0, fontSize: 22 }}>Who sees what</h3>
              <div style={{ display: "grid", gap: 10, marginTop: 14 }}>
                {visibilityRows.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.5 }}>{row.sees}</div>
                  </div>
                ))}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={sectionLabel}>Cart history</div>
              <h3 style={{ margin: 0, fontSize: 22 }}>Removed items still matter</h3>
              <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 the story of 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>
          </aside>
        </div>
      </div>
    </div>
  );
}

function Row({ label, value }: { label: string; value: 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: "#f5d79b", fontWeight: 700, fontSize: 14 }}>{value}</div>
    </div>
  );
}
