// VELOUR dashboard — Efficiency pillar = Terracotta. The synthesis pillar.
// Ties the other three together: spending clarity, time ROI, and tools to live with
// less noise — plus a cross-pillar "what's compounding" summary. Calm, not hustle.
const { Card, Badge } = window.VelourDesignSystem_380ed4;
const FRESH = !!window.VELOUR_FRESH;

function EfficiencyOnboard() {
  return (
    <main style={{ maxWidth: 1240, margin: "0 auto", padding: "36px 32px 64px", fontFamily: "var(--font-sans)" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontSize: 11.5, letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 500, color: "var(--terracotta-text)", background: "var(--terracotta-fill)", borderRadius: 999, padding: "6px 14px" }}><i className="ph ph-currency-circle-dollar" style={{ fontSize: 14 }}></i>Efficiency</span>
      <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 40, lineHeight: 1.08, letterSpacing: "-0.02em", color: "var(--text-primary)", margin: "18px 0 0", textWrap: "balance" }}>A clearer, quieter life.</h1>
      <p style={{ fontSize: 16, lineHeight: 1.65, color: "var(--text-secondary)", margin: "14px 0 28px", maxWidth: 560 }}>Efficiency is the calm dividend of everything else. It builds as your other pillars do — nothing to set up here.</p>
      <Card padding={0} style={{ overflow: "hidden" }}>
        <div style={{ background: "var(--terracotta-fill)", padding: "48px 40px", textAlign: "center" }}>
          <div style={{ width: 56, height: 56, borderRadius: 15, background: "var(--terracotta)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}><i className="ph ph-chart-line-up" style={{ fontSize: 26, color: "#fff" }}></i></div>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 26, color: "var(--terracotta-text)", letterSpacing: "-0.01em" }}>Your efficiency picture is forming.</div>
          <p style={{ fontSize: 15, lineHeight: 1.6, color: "var(--terracotta-text)", opacity: 0.85, maxWidth: 440, margin: "12px auto 0" }}>Hold a few rituals, track a piece or two, set a budget — and the money kept, time returned, and quieter decisions begin to show here, woven from every pillar.</p>
          <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap", marginTop: 24 }}>
            {["Rituals", "Wellness", "Wardrobe"].map((p) => (
              <span key={p} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 13, color: "var(--terracotta-text)", background: "rgba(255,255,255,0.5)", borderRadius: 999, padding: "7px 14px" }}><i className="ph ph-arrow-right" style={{ fontSize: 13 }}></i>Start {p}</span>
            ))}
          </div>
        </div>
      </Card>
    </main>
  );
}

// Cross-pillar signals — each tile is colored to its source pillar so the synthesis reads.
const COMPOUNDING = [
  { pillar: "Rituals", color: "var(--sage)", fill: "var(--sage-fill)", text: "var(--sage-text)", icon: "cooking-pot", label: "Meal-prep days held", value: "5 of 7", note: "Saved ~$190 on dining out" },
  { pillar: "Rituals", color: "var(--sage)", fill: "var(--sage-fill)", text: "var(--sage-text)", icon: "barbell", label: "Workouts held", value: "4 this week", note: "Steadiest month yet" },
  { pillar: "Wellness", color: "var(--teal)", fill: "var(--teal-fill)", text: "var(--teal-text)", icon: "moon", label: "Sleep in rhythm", value: "6 of 7 nights", note: "Better days follow better nights" },
  { pillar: "Wardrobe", color: "var(--amber)", fill: "var(--amber-fill)", text: "var(--amber-text)", icon: "coat-hanger", label: "Shopped your capsule", value: "8 looks", note: "$0 spent, 0 new pieces" },
];

// Spending — calm clarity, tied to the rituals driving it.
const SPEND = { spent: 1930, budget: 2400 };
const SPEND_CATS = [
  { label: "Dining out", amount: 248, icon: "fork-knife", delta: "−18%", dir: "down", note: "following the cooking ritual" },
  { label: "Wardrobe", amount: 0, icon: "coat-hanger", delta: "−$132", dir: "down", note: "shopped the capsule instead" },
  { label: "Wellness", amount: 86, icon: "heart", delta: "—", dir: "flat", note: "supplements + studio" },
  { label: "Subscriptions", amount: 92, icon: "repeat", delta: "+$28", dir: "up", note: "two you don't use" },
];

// Time ROI — what habits and tools quietly return each week.
const TIME = [
  { icon: "cooking-pot", label: "Batch meal prep", invested: "2 hrs Sun", returned: "≈ 4 hrs", note: "of weeknight cooking" },
  { icon: "coat-hanger", label: "Outfit formulas", invested: "—", returned: "≈ 1.5 hrs", note: "fewer morning decisions" },
  { icon: "repeat", label: "Automated routines", invested: "set once", returned: "≈ 2 hrs", note: "no re-planning" },
];

// Tools to live with less noise.
const NOISE = [
  { icon: "repeat", title: "2 subscriptions unused", body: "Meditation app and a styling box — $28/mo, untouched in 60 days.", action: "Review & cancel", saving: "$336/yr" },
  { icon: "bell-slash", title: "Notifications quieted", body: "VELOUR batches nudges into two calm moments a day, not forty pings.", action: "Adjust timing", saving: null },
  { icon: "brain", title: "47 fewer daily decisions", body: "Rituals and outfit formulas remove the small choices that drain a day.", action: "See what's automated", saving: null },
];

function EffRing({ pct, size = 96, stroke = 9, children }) {
  const R = (size - stroke) / 2, C = 2 * Math.PI * R, off = C * (1 - pct / 100);
  return (
    <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size / 2} cy={size / 2} r={R} fill="none" stroke="var(--border)" strokeWidth={stroke} />
        <circle cx={size / 2} cy={size / 2} r={R} fill="none" stroke="var(--terracotta)" strokeWidth={stroke} strokeLinecap="round" strokeDasharray={C} strokeDashoffset={off} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", lineHeight: 1 }}>{children}</div>
    </div>
  );
}

function ScoreHero() {
  const stats = [
    { value: "$340", label: "kept this month", sub: "vs. your 3-month average" },
    { value: "≈ 7.5 hrs", label: "reclaimed weekly", sub: "from rituals + tools" },
    { value: "47", label: "fewer daily decisions", sub: "quietly automated" },
  ];
  return (
    <Card variant="featured" pillar="efficiency" padding={28} style={{ display: "flex", gap: 32, alignItems: "center", flexWrap: "wrap" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 22, flex: "1 1 320px" }}>
        <EffRing pct={82}>
          <span style={{ fontFamily: "var(--font-serif)", fontSize: 30, color: "var(--text-primary)" }}>82</span>
          <span style={{ fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-tertiary)", marginTop: 3 }}>score</span>
        </EffRing>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>Lifestyle efficiency</div>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 26, color: "var(--text-primary)", letterSpacing: "-0.01em", margin: "5px 0 6px", lineHeight: 1.15 }}>Living with less noise</div>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--terracotta-text)", background: "var(--terracotta-fill)", borderRadius: 999, padding: "4px 12px" }}><i className="ph ph-trend-up" style={{ fontSize: 14 }}></i>Up 9 points this season</span>
        </div>
      </div>
      <div style={{ display: "flex", gap: 26, flexWrap: "wrap", flex: "1 1 380px" }}>
        {stats.map((s) => (
          <div key={s.label} style={{ minWidth: 110 }}>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 27, color: "var(--text-primary)", letterSpacing: "-0.01em", whiteSpace: "nowrap" }}>{s.value}</div>
            <div style={{ fontSize: 13, color: "var(--text-primary)", marginTop: 4 }}>{s.label}</div>
            <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 2 }}>{s.sub}</div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function CompoundingGrid() {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 8, margin: "8px 2px 16px" }}>
        <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em" }}>What's compounding</h2>
        <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>Small things held, across every pillar</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 170px), 1fr))", gap: 16 }}>
        {COMPOUNDING.map((c) => (
          <Card key={c.label} padding={20} style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: c.fill, display: "flex", alignItems: "center", justifyContent: "center" }}><i className={`ph ph-${c.icon}`} style={{ fontSize: 19, color: c.color }}></i></span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, color: c.text }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: c.color }}></span>{c.pillar}</span>
            </div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, color: "var(--text-primary)", letterSpacing: "-0.01em" }}>{c.value}</div>
            <div style={{ fontSize: 13.5, color: "var(--text-primary)", marginTop: 5 }}>{c.label}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 6, lineHeight: 1.45 }}>{c.note}</div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function SpendingClarity() {
  const pct = (SPEND.spent / SPEND.budget) * 100;
  const remaining = SPEND.budget - SPEND.spent;
  const dirColor = (d) => (d === "down" ? "var(--teal)" : d === "up" ? "var(--terracotta)" : "var(--text-tertiary)");
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 16 }}>
      <Card padding={24} style={{ display: "flex", flexDirection: "column" }}>
        <span style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>Spending clarity</span>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, margin: "14px 0 4px" }}>
          <span style={{ fontFamily: "var(--font-serif)", fontSize: 38, color: "var(--text-primary)", letterSpacing: "-0.02em" }}>${SPEND.spent.toLocaleString()}</span>
          <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>of ${SPEND.budget.toLocaleString()}</span>
        </div>
        <div style={{ height: 8, borderRadius: 999, background: "var(--surface-sunken)", marginTop: 12, overflow: "hidden" }}>
          <div style={{ height: "100%", width: `${pct}%`, background: "var(--terracotta)", borderRadius: 999 }}></div>
        </div>
        <div style={{ fontSize: 13, color: "var(--text-tertiary)", marginTop: 12 }}>${remaining} of room left · 14 days to go</div>
        <div style={{ display: "flex", gap: 11, alignItems: "flex-start", background: "var(--terracotta-fill)", borderRadius: 13, padding: "14px 16px", marginTop: "auto" }}>
          <i className="ph ph-sparkle" style={{ fontSize: 17, color: "var(--terracotta)", marginTop: 1 }}></i>
          <div style={{ fontSize: 13.5, color: "var(--terracotta-text)", lineHeight: 1.55 }}>Dining out fell 18% — no restriction, no goal set. It simply followed your cooking ritual.</div>
        </div>
      </Card>
      <Card padding={8}>
        {SPEND_CATS.map((c, i) => (
          <div key={c.label} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 16px", borderTop: i === 0 ? "none" : "var(--border-width) solid var(--divider)" }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--terracotta-fill)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><i className={`ph ph-${c.icon}`} style={{ fontSize: 18, color: "var(--terracotta-text)" }}></i></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, color: "var(--text-primary)" }}>{c.label}</div>
              <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 2 }}>{c.note}</div>
            </div>
            <span style={{ fontSize: 13, color: dirColor(c.dir), whiteSpace: "nowrap" }}>{c.delta}</span>
            <span style={{ fontFamily: "var(--font-serif)", fontSize: 18, color: "var(--text-primary)", minWidth: 54, textAlign: "right" }}>${c.amount}</span>
          </div>
        ))}
      </Card>
    </div>
  );
}

function TimeRoi() {
  return (
    <Card padding={26}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 20 }}>
        <div>
          <span style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>Time ROI</span>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, color: "var(--text-primary)", letterSpacing: "-0.01em", marginTop: 6 }}>What your routines hand back</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 26, color: "var(--terracotta-text)", letterSpacing: "-0.01em" }}>≈ 7.5 hrs</div>
          <div style={{ fontSize: 12.5, color: "var(--text-tertiary)" }}>returned each week</div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 200px), 1fr))", gap: 16 }}>
        {TIME.map((t) => (
          <div key={t.label} style={{ background: "var(--surface-sunken)", borderRadius: 14, padding: "18px 18px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <i className={`ph ph-${t.icon}`} style={{ fontSize: 19, color: "var(--terracotta)" }}></i>
              <span style={{ fontSize: 14, color: "var(--text-primary)", fontWeight: 500 }}>{t.label}</span>
            </div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
              <span style={{ fontFamily: "var(--font-serif)", fontSize: 24, color: "var(--text-primary)", letterSpacing: "-0.01em" }}>{t.returned}</span>
              <span style={{ fontSize: 12.5, color: "var(--text-tertiary)" }}>{t.note}</span>
            </div>
            <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 8 }}>Invested: {t.invested}</div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function NoiseTools() {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 8, margin: "8px 2px 16px" }}>
        <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em" }}>Live with less noise</h2>
        <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>Quiet wins VELOUR found for you</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 200px), 1fr))", gap: 16 }}>
        {NOISE.map((n) => (
          <Card key={n.title} padding={22} style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <span style={{ width: 40, height: 40, borderRadius: 11, background: "var(--terracotta-fill)", display: "flex", alignItems: "center", justifyContent: "center" }}><i className={`ph ph-${n.icon}`} style={{ fontSize: 20, color: "var(--terracotta)" }}></i></span>
              {n.saving && <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--terracotta-text)", background: "var(--terracotta-fill)", borderRadius: 999, padding: "4px 11px", whiteSpace: "nowrap" }}>{n.saving}</span>}
            </div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 18, color: "var(--text-primary)", letterSpacing: "-0.01em" }}>{n.title}</div>
            <div style={{ fontSize: 13.5, color: "var(--text-secondary)", marginTop: 8, lineHeight: 1.55, flex: 1 }}>{n.body}</div>
            <button style={{ display: "inline-flex", alignItems: "center", gap: 7, marginTop: 16, alignSelf: "flex-start", background: "none", border: "none", padding: 0, cursor: "pointer", color: "var(--terracotta-text)", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 500 }}>{n.action}<i className="ph ph-arrow-right" style={{ fontSize: 14 }}></i></button>
          </Card>
        ))}
      </div>
    </div>
  );
}

// =============================================================================
// LIVE EFFICIENCY (fresh account) — synthesizes the real data across all pillars.
// Deterministic, no AI: held habits → money/time saved, closet/budget → smart
// spending, plus a subscriptions tracker. The demo (Jennifer) keeps its curated
// static view below.
// =============================================================================
const EFF_K = {
  ritSeq: FRESH ? "velour_fresh_rituals_sequences" : "velour_rituals_sequences",
  ritLog: FRESH ? "velour_fresh_rituals_log" : "velour_rituals_log",
  wellLog: FRESH ? "velour_fresh_wellness_log" : "velour_wellness_log",
  closet: FRESH ? "velour_fresh_closet_v1" : "velour_closet_v1",
  outfits: FRESH ? "velour_fresh_outfits_v1" : "velour_outfits_v1",
  budget: FRESH ? "velour_fresh_budget_v1" : "velour_budget_v1",
  subs: FRESH ? "velour_fresh_subs_v1" : "velour_subs_v1",
};
function effLoad(key, fb) { try { const r = localStorage.getItem(key); if (r) return JSON.parse(r); } catch (e) {} return fb; }
function effToday() { const d = new Date(); const off = Number(window.VELOUR_DAY_OFFSET) || 0; if (off) d.setDate(d.getDate() + off); return window.velourDateISO(d); }
function effAddDays(iso, n) { const d = new Date(iso + "T00:00:00"); d.setDate(d.getDate() + n); return window.velourDateISO(d); }
// Money goes through window.velourMoney — one formatter for the whole product.
// This used to be Math.round(n), which showed a $13.49 subscription as "$13" and
// its $161.88 annual total as "$162": the stored value was right and the screen
// disagreed with it. Same class as the hydration display bug. Kept as a named
// wrapper so the sixteen call sites below read unchanged.
function effMoney(n) { return window.velourMoney(n); }
function effDaysIdle(it) { if (it.lastWornDate) return Math.max(0, Math.round((new Date(effToday() + "T00:00:00") - new Date(it.lastWornDate + "T00:00:00")) / 86400000)); if (it.wears === 0) return 999; return it.lastWorn != null ? it.lastWorn : 999; }
function effIsIdle(it) { return it.wears === 0 || effDaysIdle(it) >= 90; }
function effCpw(it) { return it.wears > 0 ? it.price / it.wears : null; }
function effRoi(items) { if (!items.length) return 0; const a = items.filter((it) => it.wears > 0 && effDaysIdle(it) < 30 && (effCpw(it) ?? 99) < 12).length; return Math.round((a / items.length) * 100); }

// Habits with a measurable money/time return. Estimates are intentionally modest
// and labelled as such. `match` keywords map a user's habit label to a value.
const VALUE_HABITS = [
  { key: "mealprep", label: "Cook dinner at home", match: ["cook", "dinner at home", "meal prep", "meal-prep", "home-cooked"], ritual: "evening", icon: "cooking-pot", kind: "money", per: 14, blurb: "vs. ordering in or eating out" },
  { key: "lunch", label: "Pack tomorrow's lunch", match: ["pack lunch", "bring lunch", "pack tomorrow", "lunch"], ritual: "evening", icon: "bowl-food", kind: "money", per: 11, blurb: "vs. buying lunch out" },
  { key: "coffee", label: "Brew coffee at home", match: ["brew", "coffee at home", "make coffee", "home coffee"], ritual: "morning", icon: "coffee", kind: "money", per: 5, blurb: "vs. a daily cafe stop" },
  { key: "layout", label: "Lay out tomorrow's clothes", match: ["lay out", "outfit ready", "tomorrow's clothes", "clothes"], ritual: "evening", icon: "coat-hanger", kind: "time", per: 8, blurb: "fewer morning decisions" },
  { key: "plan", label: "Plan tomorrow", match: ["plan tomorrow", "tomorrow's plan", "set the day", "day's intention", "intention"], ritual: "evening", icon: "list-checks", kind: "time", per: 10, blurb: "less deciding, more doing" },
  { key: "homeworkout", label: "Move at home", match: ["home workout", "move at home", "exercise at home", "yoga at home", "stretch"], ritual: "morning", icon: "barbell", kind: "money", per: 2, blurb: "vs. a gym or studio drop-in" },
  { key: "waterbottle", label: "Carry a water bottle", match: ["water bottle", "reusable bottle", "refill", "carry water"], ritual: "morning", icon: "drop", kind: "money", per: 3, blurb: "vs. buying drinks while out" },
  { key: "errands", label: "Batch your errands", match: ["batch errand", "errands", "one trip", "errand run"], ritual: "evening", icon: "map-pin", kind: "time", per: 12, blurb: "one trip beats five" },
];

// Seeded subscriptions for the demo (Jennifer) so the live tracker has content.
const DEMO_SUBS = [
  { id: "ds1", name: "Streaming bundle", price: 24, used: true },
  { id: "ds2", name: "Meditation app", price: 13, used: false },
  { id: "ds3", name: "Styling box", price: 15, used: false },
];
// Curated snapshot for the demo account — rendered through the same live components
// as the fresh experience, consistent with Jennifer's stats elsewhere. Subscriptions
// stay live-editable (passed in); the rest is a coherent showcase.
function demoEfficiency(subs) {
  const vh = (k) => VALUE_HABITS.find((v) => v.key === k);
  const matched = [
    { vh: vh("mealprep"), held: 5 },
    { vh: vh("coffee"), held: 7 },
    { vh: vh("layout"), held: 6 },
    { vh: vh("plan"), held: 5 },
  ];
  const habitMoneyWeek = matched.filter((m) => m.vh.kind === "money").reduce((s, m) => s + m.held * m.vh.per, 0);
  const habitTimeWeek = matched.filter((m) => m.vh.kind === "time").reduce((s, m) => s + m.held * m.vh.per, 0);
  const suggestions = VALUE_HABITS.filter((v) => !matched.find((m) => m.vh.key === v.key));
  const subsMonthly = (subs || []).reduce((s, x) => s + (Number(x.price) || 0), 0);
  const unused = (subs || []).filter((x) => !x.used);
  const subsUnusedYearly = unused.reduce((s, x) => s + (Number(x.price) || 0), 0) * 12;
  return {
    anyData: true, score: 82, matched, suggestions, habitMoneyWeek, habitTimeWeek,
    totalHabits: 11, daysActive: 6, longest: 41, wDaysWeek: 6, wScore: 78, wHasData: true,
    closet: new Array(8), idleValue: 435, roi: 72, best: { name: "Black wool blazer", price: 240, wears: 53 }, outfits: [],
    remaining: 470, budgetTotal: 2400, spent: 1930,
    subsMonthly, subsYearly: subsMonthly * 12, subsUnusedYearly, subsUnusedCount: unused.length, decisions: 47,
  };
}

function computeEfficiency(subs) {
  if (!FRESH) return demoEfficiency(subs);
  const today = effToday();
  const last7 = Array.from({ length: 7 }, (_, i) => effAddDays(today, -i));

  // --- Rituals: value habits → savings ---
  const seqs = effLoad(EFF_K.ritSeq, []);
  const rlog = effLoad(EFF_K.ritLog, {});
  const allHabits = (seqs || []).flatMap((s) => s.habits || []);
  const matched = [];
  VALUE_HABITS.forEach((vh) => {
    const h = allHabits.find((hh) => vh.match.some((m) => (hh.label || "").toLowerCase().includes(m)));
    if (h) { const held = last7.filter((d) => (rlog[d] || {})[h.id]).length; matched.push({ vh, held }); }
  });
  const habitMoneyWeek = matched.filter((m) => m.vh.kind === "money").reduce((s, m) => s + m.held * m.vh.per, 0);
  const habitTimeWeek = matched.filter((m) => m.vh.kind === "time").reduce((s, m) => s + m.held * m.vh.per, 0);
  const suggestions = VALUE_HABITS.filter((vh) => !matched.find((m) => m.vh.key === vh.key));
  const totalHabits = allHabits.length;
  const daysActive = last7.filter((d) => rlog[d] && Object.values(rlog[d]).some(Boolean)).length;
  const longest = allHabits.reduce((best, h) => { let s = 0, c = today; while ((rlog[c] || {})[h.id]) { s++; c = effAddDays(c, -1); } return Math.max(best, s); }, 0);

  // --- Wellness ---
  const wlog = effLoad(EFF_K.wellLog, {});
  const wDates = Object.keys(wlog);
  const wDaysWeek = last7.filter((d) => wlog[d]).length;
  let wScore = 0;
  if (wDates.length) { const w = wlog[wDates.sort()[wDates.length - 1]]; const sp = Math.min(100, Math.round(((w.sleepH * 60 + w.sleepM) / 450) * 100)); const hp = Math.min(100, Math.round(((w.hydration || 0) / 2) * 100)); wScore = Math.round((sp + hp) / 2); }

  // --- Wardrobe ---
  const closet = effLoad(EFF_K.closet, []);
  const idleValue = closet.filter(effIsIdle).reduce((s, it) => s + (it.price || 0), 0);
  const roi = effRoi(closet);
  const best = closet.filter((it) => it.wears > 0).sort((a, b) => effCpw(a) - effCpw(b))[0] || null;
  const outfits = effLoad(EFF_K.outfits, []);

  // --- Budget / spending ---
  const budget = effLoad(EFF_K.budget, { total: 0, planned: [] });
  const spent = (budget.planned || []).reduce((s, p) => s + (p.price || 0), 0);
  const remaining = Math.max(0, (budget.total || 0) - spent);

  // --- Subscriptions ---
  const subsMonthly = (subs || []).reduce((s, x) => s + (Number(x.price) || 0), 0);
  const subsYearly = subsMonthly * 12;
  const unused = (subs || []).filter((x) => !x.used);
  const subsUnusedYearly = unused.reduce((s, x) => s + (Number(x.price) || 0), 0) * 12;

  // --- Composite "calm" score (only from pillars that have data) ---
  const parts = [];
  if (totalHabits) parts.push(Math.min(100, Math.round((daysActive / 7) * 100)));
  if (wDates.length) parts.push(wScore);
  if (closet.length) parts.push(roi);
  if (budget.total) parts.push(Math.min(100, Math.round((remaining / budget.total) * 100)));
  if ((subs || []).length) parts.push(Math.max(0, Math.round((1 - unused.length / subs.length) * 100)));
  const score = parts.length ? Math.round(parts.reduce((a, b) => a + b, 0) / parts.length) : 0;
  const decisions = totalHabits + outfits.length + (wDates.length ? 3 : 0);

  const anyData = totalHabits > 0 || wDates.length > 0 || closet.length > 0 || budget.total > 0 || (subs || []).length > 0;
  return { anyData, score, matched, suggestions, habitMoneyWeek, habitTimeWeek, totalHabits, daysActive, longest, wDaysWeek, wScore, wHasData: wDates.length > 0, closet, idleValue, roi, best, outfits, remaining, budgetTotal: budget.total || 0, spent, subsMonthly, subsYearly, subsUnusedYearly, subsUnusedCount: unused.length, decisions };
}

function effScoreBand(s) { return s >= 75 ? "Living with less noise" : s >= 50 ? "Finding its rhythm" : "Just getting started"; }

function EffStat({ value, label, sub }) {
  return (
    <div style={{ minWidth: 110 }}>
      <div style={{ fontFamily: "var(--font-serif)", fontSize: 27, color: "var(--text-primary)", letterSpacing: "-0.01em", whiteSpace: "nowrap" }}>{value}</div>
      <div style={{ fontSize: 13, color: "var(--text-primary)", marginTop: 4 }}>{label}</div>
      <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 2 }}>{sub}</div>
    </div>
  );
}

function EffScoreLive({ data }) {
  return (
    <Card variant="featured" pillar="efficiency" padding={28} style={{ display: "flex", gap: 32, alignItems: "center", flexWrap: "wrap" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 22, flex: "1 1 300px" }}>
        <EffRing pct={data.score}>
          <span style={{ fontFamily: "var(--font-serif)", fontSize: 30, color: "var(--text-primary)" }}>{data.score}</span>
          <span style={{ fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-tertiary)", marginTop: 3 }}>score</span>
        </EffRing>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>Lifestyle efficiency</div>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, color: "var(--text-primary)", letterSpacing: "-0.01em", margin: "5px 0 6px", lineHeight: 1.15 }}>{effScoreBand(data.score)}</div>
          <span style={{ fontSize: 12.5, color: "var(--text-tertiary)" }}>Blended from the pillars you're tracking</span>
        </div>
      </div>
      <div style={{ display: "flex", gap: 26, flexWrap: "wrap", flex: "1 1 360px" }}>
        <EffStat value={effMoney(data.habitMoneyWeek)} label="saved this week" sub="from rituals you held" />
        <EffStat value={`${data.habitTimeWeek} min`} label="returned this week" sub="less deciding & prepping" />
        <EffStat value={String(data.decisions)} label="fewer decisions" sub="quietly automated" />
      </div>
    </Card>
  );
}

// Where the dividend comes from — held value-habits + one-tap suggestions to add.
function EffDividend({ data, onAdd, ritualLimited }) {
  const [expanded, setExpanded] = React.useState(false);
  // Rank by what's actually returning the most: held consistency, then per-day value.
  const sorted = data.matched.slice().sort((a, b) => (b.held - a.held) || (b.vh.per - a.vh.per));
  const visible = expanded ? sorted : sorted.slice(0, 3);
  const hidden = sorted.length - visible.length;
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 8, margin: "8px 2px 16px" }}>
        <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em" }}>Where your dividend comes from</h2>
        <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>Your top sources, turned into money and time</span>
      </div>
      <Card padding={0} style={{ overflow: "hidden" }}>
        {data.matched.length === 0 && (
          <div style={{ padding: "22px 24px", color: "var(--text-tertiary)", fontSize: 14, lineHeight: 1.6 }}>No money-or-time rituals yet. Add one below and check it off — VELOUR will start counting the return.</div>
        )}
        {visible.map((m, i) => {
          const earned = m.vh.kind === "money" ? effMoney(m.held * m.vh.per) : `${m.held * m.vh.per} min`;
          return (
            <div key={m.vh.key} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 24px", borderTop: i === 0 ? "none" : "var(--border-width) solid var(--divider)" }}>
              <span style={{ width: 40, height: 40, borderRadius: 11, background: "var(--terracotta-fill)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><i className={`ph ph-${m.vh.icon}`} style={{ fontSize: 19, color: "var(--terracotta)" }}></i></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, color: "var(--text-primary)" }}>{m.vh.label}</div>
                <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 2 }}>Held {m.held} of the last 7 days · {m.vh.blurb}</div>
              </div>
              <span style={{ fontFamily: "var(--font-serif)", fontSize: 19, color: m.held ? "var(--terracotta-text)" : "var(--text-tertiary)", whiteSpace: "nowrap" }}>{m.held ? earned : "—"}</span>
            </div>
          );
        })}
        {(hidden > 0 || (expanded && sorted.length > 3)) && (
          <button onClick={() => setExpanded((e) => !e)} style={{ width: "100%", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, padding: "13px 24px", background: "none", border: "none", borderTop: "var(--border-width) solid var(--divider)", cursor: "pointer", color: "var(--terracotta-text)", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 500 }}>
            {expanded ? "Show less" : `Show ${hidden} more`}<i className={`ph ph-caret-${expanded ? "up" : "down"}`} style={{ fontSize: 13 }}></i>
          </button>
        )}
        {data.suggestions.length > 0 && (
          <div style={{ background: "var(--surface-sunken)", padding: "18px 24px", borderTop: "var(--border-width) solid var(--divider)" }}>
            <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginBottom: 12 }}>Add an efficiency ritual — it lands with your others and starts counting</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {data.suggestions.map((vh) => (
                <button key={vh.key} onClick={() => onAdd(vh)} style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "9px 13px", borderRadius: 999, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500, border: "var(--border-width) solid var(--border)", background: "var(--surface-card)", color: "var(--text-primary)" }}>
                  <i className={`ph ph-${vh.icon}`} style={{ fontSize: 15, color: "var(--terracotta)" }}></i>
                  {vh.label}
                  <span style={{ fontSize: 11, color: "var(--terracotta-text)", background: "var(--terracotta-fill)", borderRadius: 999, padding: "2px 8px", fontWeight: 500 }}>{vh.kind === "money" ? `~$${vh.per}/day` : `~${vh.per} min/day`}</span>
                  <i className="ph ph-plus" style={{ fontSize: 12, color: "var(--text-tertiary)" }}></i>
                </button>
              ))}
            </div>
            {ritualLimited && (
              <div style={{ marginTop: 14 }}>
                <div style={{ fontSize: 14.5, color: "var(--text-primary)", fontWeight: 500 }}>Your free plan holds {(window.velourPlan ? window.velourPlan.get() : {}).maxRituals} rituals.</div>
                <button onClick={() => window.velourOpenPricing()} style={{ marginTop: 8, background: "none", border: "none", padding: 0, cursor: "pointer", color: "var(--sage-text)", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}>
                  See what Premium adds<i className="ph ph-arrow-right" style={{ fontSize: 13 }}></i>
                </button>
              </div>
            )}
          </div>
        )}
      </Card>
    </div>
  );
}

function EffCompoundingLive({ data, onOpen }) {
  const tiles = [
    { show: data.totalHabits > 0, pillar: "Rituals", color: "var(--sage)", fill: "var(--sage-fill)", text: "var(--sage-text)", icon: "sun", value: data.longest > 0 ? `${data.longest}-day hold` : `${data.daysActive}/7 active`, note: "Consistency compounds quietly." },
    { show: data.wHasData, pillar: "Wellness", color: "var(--teal)", fill: "var(--teal-fill)", text: "var(--teal-text)", icon: "heart", value: `${data.wDaysWeek}/7 logged`, note: "Steady inputs, steadier days." },
    { show: data.closet.length > 0, pillar: "Wardrobe", color: "var(--amber)", fill: "var(--amber-fill)", text: "var(--amber-text)", icon: "coat-hanger", value: `ROI ${data.roi}`, note: data.idleValue > 0 ? `${effMoney(data.idleValue)} sitting idle.` : "Pieces earning their keep." },
    { show: data.budgetTotal > 0 || data.subsMonthly > 0, pillar: "Spending", color: "var(--terracotta)", fill: "var(--terracotta-fill)", text: "var(--terracotta-text)", icon: "currency-circle-dollar", value: data.budgetTotal > 0 ? `${effMoney(data.remaining)} kept` : `${effMoney(data.subsMonthly)}/mo`, note: "Money held, not spent." },
  ].filter((t) => t.show);
  if (!tiles.length) return null;
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 8, margin: "8px 2px 16px" }}>
        <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em" }}>What's compounding</h2>
        <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>Small things held, across every pillar</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${Math.min(4, tiles.length)}, 1fr)`, gap: 16 }}>
        {tiles.map((c) => (
          <Card key={c.pillar} padding={20} style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: c.fill, display: "flex", alignItems: "center", justifyContent: "center" }}><i className={`ph ph-${c.icon}`} style={{ fontSize: 19, color: c.color }}></i></span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, color: c.text }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: c.color }}></span>{c.pillar}</span>
            </div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, color: "var(--text-primary)", letterSpacing: "-0.01em" }}>{c.value}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 6, lineHeight: 1.45 }}>{c.note}</div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function EffInsight({ data }) {
  const money = data.habitMoneyWeek;
  const mins = data.habitTimeWeek;
  return (
    <window.VelourInsight pillar="efficiency"
      // The subscriptions study only when the line above it is naming an
      // untouched subscription; otherwise the card is about money rituals like
      // home coffee and a packed lunch, which the food-away-from-home figure backs.
      cite={money > 0 && mins > 0 && data.subsUnusedCount > 0 ? "subscriptions-forgotten" : "food-away-from-home"}
      headline={money > 0
        ? `${effMoney(money)} kept this week, from rituals you held without thinking about it.`
        : "Hold one money ritual — home coffee, a packed lunch — and the return starts counting."}
      support={money > 0 && mins > 0
        ? `Plus ${mins} minutes handed back — less deciding, less prepping.${data.subsUnusedCount > 0 ? ` And ${data.subsUnusedCount} subscription${data.subsUnusedCount === 1 ? " looks" : "s look"} untouched — ${effMoney(data.subsUnusedYearly)} a year if you let ${data.subsUnusedCount === 1 ? "it" : "them"} go.` : ""}`
        : money > 0
          ? "Nothing dramatic — the same mornings, quietly costing less."
          : "The estimates stay modest on purpose: a few dollars a day, counted honestly."} />
  );
}

function EffSmartSpend({ data }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 260px), 1fr))", gap: 16 }}>
      <Card padding={24} style={{ display: "flex", flexDirection: "column" }}>
        <span style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>Money kept</span>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, margin: "14px 0 4px" }}>
          <span style={{ fontFamily: "var(--font-serif)", fontSize: 36, color: "var(--text-primary)", letterSpacing: "-0.02em" }}>{data.budgetTotal > 0 ? effMoney(data.remaining) : effMoney(data.habitMoneyWeek)}</span>
          <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>{data.budgetTotal > 0 ? `of ${effMoney(data.budgetTotal)} budget` : "saved this week"}</span>
        </div>
        <div style={{ fontSize: 13.5, color: "var(--text-secondary)", marginTop: 10, lineHeight: 1.55 }}>
          {data.idleValue > 0
            ? `${effMoney(data.idleValue)} is tied up in pieces going unworn — the capsule already holds more than it is being asked for.`
            : data.best ? `Your hardest-working piece costs just ${effCpw(data.best) != null ? window.velourMoney(effCpw(data.best)) : "—"} per wear.` : "Track a few pieces and your capsule's value shows here."}
        </div>
      </Card>
      <Card padding={24} style={{ display: "flex", flexDirection: "column" }}>
        <span style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--terracotta-text)", fontWeight: 500 }}>This week, in plain terms</span>
        <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 14 }}>
          {[
            { i: "cooking-pot", t: data.habitMoneyWeek > 0 ? `${effMoney(data.habitMoneyWeek)} saved by rituals you held` : "Hold a money ritual to start saving" },
            { i: "timer", t: data.habitTimeWeek > 0 ? `${data.habitTimeWeek} minutes handed back to you` : "Add a prep ritual to win time back" },
            { i: "repeat", t: data.subsMonthly > 0 ? `${effMoney(data.subsMonthly)}/mo in subscriptions tracked` : "Add subscriptions below to see the drain" },
          ].map((r) => (
            <div key={r.i} style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <i className={`ph ph-${r.i}`} style={{ fontSize: 17, color: "var(--terracotta)", flexShrink: 0 }}></i>
              <span style={{ fontSize: 14, color: "var(--text-primary)" }}>{r.t}</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// Subscriptions tracker — recurring costs, flag unused, see the annual drain.
function EffSubscriptions({ subs, setSubs }) {
  const [adding, setAdding] = React.useState(false);
  const [draft, setDraft] = React.useState({ name: "", price: "" });
  const monthly = subs.reduce((s, x) => s + (Number(x.price) || 0), 0);
  const unusedYr = subs.filter((x) => !x.used).reduce((s, x) => s + (Number(x.price) || 0), 0) * 12;
  const add = () => { const p = Number(draft.price); if (!draft.name.trim() || !(p > 0)) return; setSubs([...subs, { id: "sub" + Math.random().toString(36).slice(2, 7), name: draft.name.trim(), price: p, used: true }]); setDraft({ name: "", price: "" }); setAdding(false); };
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 8, margin: "8px 2px 16px" }}>
        <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em" }}>Subscriptions</h2>
        <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>The quiet monthly drain, made visible</span>
      </div>
      <Card padding={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 24px", borderBottom: subs.length || adding ? "var(--border-width) solid var(--divider)" : "none" }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
            <span style={{ fontFamily: "var(--font-serif)", fontSize: 30, color: "var(--text-primary)", letterSpacing: "-0.01em" }}>{effMoney(monthly)}</span>
            <span style={{ fontSize: 13.5, color: "var(--text-tertiary)" }}>/mo · {effMoney(monthly * 12)}/yr</span>
          </div>
          <button onClick={() => setAdding((v) => !v)} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", cursor: "pointer", color: "var(--terracotta-text)", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 500 }}><i className={`ph ph-${adding ? "x" : "plus"}`} style={{ fontSize: 14 }}></i>{adding ? "Close" : "Add subscription"}</button>
        </div>
        {adding && (
          <div style={{ display: "flex", gap: 8, padding: "16px 24px", background: "var(--surface-sunken)", borderBottom: "var(--border-width) solid var(--divider)" }}>
            <input value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} placeholder="e.g. Streaming, gym, app…" style={{ flex: 1, padding: "10px 13px", borderRadius: 10, border: "var(--border-width) solid var(--border)", background: "var(--surface-card)", fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-primary)", outline: "none" }} />
            <div style={{ position: "relative", width: 110 }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-tertiary)", fontSize: 14 }}>$</span>
              <input type="number" min="0" value={draft.price} onChange={(e) => setDraft({ ...draft, price: e.target.value })} onKeyDown={(e) => { if (e.key === "Enter") add(); }} placeholder="/mo" style={{ width: "100%", boxSizing: "border-box", padding: "10px 13px 10px 24px", borderRadius: 10, border: "var(--border-width) solid var(--border)", background: "var(--surface-card)", fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-primary)", outline: "none" }} />
            </div>
            <button onClick={add} style={{ padding: "0 18px", borderRadius: 10, border: "none", background: "var(--ink)", color: "var(--parchment)", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 500, cursor: "pointer" }}>Add</button>
          </div>
        )}
        {subs.length === 0 && !adding && <div style={{ padding: "22px 24px", color: "var(--text-tertiary)", fontSize: 14, lineHeight: 1.6 }}>Add what recurs each month. Mark anything you've stopped using — VELOUR will total what cancelling would reclaim.</div>}
        {subs.map((x, i) => (
          <div key={x.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 24px", borderTop: i === 0 ? "none" : "var(--border-width) solid var(--divider)" }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, color: "var(--text-primary)", textDecoration: x.used ? "none" : "line-through", opacity: x.used ? 1 : 0.6 }}>{x.name}</div>
              <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 2 }}>{effMoney(x.price)}/mo · {effMoney(x.price * 12)}/yr</div>
            </div>
            <button onClick={() => setSubs(subs.map((s) => (s.id === x.id ? { ...s, used: !s.used } : s)))} style={{ fontSize: 12.5, fontWeight: 500, borderRadius: 999, padding: "6px 12px", cursor: "pointer", border: "var(--border-width) solid " + (x.used ? "var(--border)" : "var(--terracotta)"), background: x.used ? "var(--surface-card)" : "var(--terracotta-fill)", color: x.used ? "var(--text-secondary)" : "var(--terracotta-text)", fontFamily: "var(--font-sans)" }}>{x.used ? "In use" : "Unused"}</button>
            <button onClick={() => setSubs(subs.filter((s) => s.id !== x.id))} aria-label="Remove" style={{ border: "none", background: "none", cursor: "pointer", color: "var(--text-tertiary)", display: "flex", padding: 4 }}><i className="ph ph-x" style={{ fontSize: 14 }}></i></button>
          </div>
        ))}
        {unusedYr > 0 && (
          <div style={{ display: "flex", gap: 11, alignItems: "flex-start", background: "var(--terracotta-fill)", padding: "16px 24px", borderTop: "var(--border-width) solid var(--divider)" }}>
            <i className="ph ph-scissors" style={{ fontSize: 18, color: "var(--terracotta)", marginTop: 1 }}></i>
            <div style={{ fontSize: 13.5, color: "var(--terracotta-text)", lineHeight: 1.55 }}><span style={{ fontWeight: 600 }}>{effMoney(unusedYr)}/year</span> in subscriptions you marked unused. Cancelling reclaims it — quietly, with nothing lost.</div>
          </div>
        )}
      </Card>
    </div>
  );
}

function EfficiencyLive() {
  const [subs, setSubs] = React.useState(() => effLoad(EFF_K.subs, FRESH ? [] : DEMO_SUBS));
  const [tick, setTick] = React.useState(0);
  const [ritualLimited, setRitualLimited] = React.useState(false);
  // Persist on CHANGE, never on mount. `subs` was just read from this key, so the
  // mount write changed nothing locally — but the sync layer notices keys, not
  // intent, so it read as an edit and fired a PUT. On a device that had not
  // reconciled yet that PUT carried an empty list, and a sync write is a whole
  // delete-then-insert: it could tell the account there were no tracked expenses
  // before the pull that would have filled them in had even finished.
  const persisted = React.useRef(false);
  React.useEffect(() => {
    if (!persisted.current) { persisted.current = true; return; }
    try { localStorage.setItem(EFF_K.subs, JSON.stringify(subs)); } catch (e) {}
  }, [subs]);
  React.useEffect(() => { const r = () => setTick((t) => t + 1); window.addEventListener("focus", r); return () => window.removeEventListener("focus", r); }, []);
  // Every pillar, not just this one: the numbers on this screen are computed from
  // rituals, wellness and the wardrobe as well, so any of them landing changes
  // what belongs here. `tick` is already the recompute signal — reuse it.
  if (window.useVelourSynced) window.useVelourSynced(null, () => {
    setSubs(effLoad(EFF_K.subs, FRESH ? [] : DEMO_SUBS));
    setTick((t) => t + 1);
  });
  const data = React.useMemo(() => computeEfficiency(subs), [subs, tick]);

  const addHabit = (vh) => {
    // Same cap, same check as the dashboard's "Add to my rituals". These chips
    // wrote rituals straight past the free-plan limit.
    if (window.velourRitualsAtLimit && window.velourRitualsAtLimit()) { setRitualLimited(true); return; }
    let arr = effLoad(EFF_K.ritSeq, null);
    if (!arr || !arr.length) arr = [{ id: "morning", name: "Morning ritual", time: "7:00 AM", icon: "sun", habits: [] }, { id: "evening", name: "Evening wind-down", time: "9:30 PM", icon: "moon-stars", habits: [] }];
    const target = arr.find((s) => s.id === vh.ritual) || arr[0];
    if (!target) return;
    target.habits = [...(target.habits || []), { id: "h-" + Math.random().toString(36).slice(2, 8), libId: vh.key, label: vh.label, icon: vh.icon || "circle", streak: 0, trackType: null, track: null, isNew: true }];
    try { localStorage.setItem(EFF_K.ritSeq, JSON.stringify(arr)); } catch (e) {}
    setTick((t) => t + 1);
  };

  if (!data.anyData && subs.length === 0) return <EfficiencyOnboard />;
  return (
    <main style={{ maxWidth: 1240, margin: "0 auto", padding: "36px 32px 64px", display: "flex", flexDirection: "column", gap: 24, fontFamily: "var(--font-sans)" }}>
      <div style={{ maxWidth: 600 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontSize: 11.5, letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 500, color: "var(--terracotta-text)", background: "var(--terracotta-fill)", borderRadius: 999, padding: "6px 14px" }}><i className="ph ph-currency-circle-dollar" style={{ fontSize: 14 }}></i>Efficiency</span>
        <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 40, lineHeight: 1.08, letterSpacing: "-0.02em", color: "var(--text-primary)", margin: "18px 0 0", textWrap: "balance" }}>A clearer, quieter life.</h1>
        <p style={{ fontSize: 16, lineHeight: 1.65, color: "var(--text-secondary)", margin: "14px 0 0" }}>Efficiency isn't about doing more — it's the calm dividend of everything else. Your rituals, wellness, and wardrobe quietly compound into money kept, time returned, and decisions you no longer have to make.</p>
      </div>
      <EffInsight data={data} />
      <EffScoreLive data={data} />
      <EffDividend data={data} onAdd={addHabit} ritualLimited={ritualLimited} />
      <EffSmartSpend data={data} />
      <EffSubscriptions subs={subs} setSubs={setSubs} />
      <EffCompoundingLive data={data} />
    </main>
  );
}

function DashEfficiency() {
  return <EfficiencyLive />;
}

window.DashEfficiency = DashEfficiency;
