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

export type CurrencyKey = "hearts" | "stars" | "moons" | "hourglasses" | "balloons";

export interface CurrencyLedgerProps {
  title?: string;
  subtitle?: string;
  balances?: Partial<Record<CurrencyKey, number>>;
  recentSignals?: Array<{
    label: string;
    detail: string;
    delta: string;
  }>;
}

const DEFAULT_BALANCES: Record<CurrencyKey, number> = {
  hearts: 24,
  stars: 31,
  moons: 14,
  hourglasses: 9,
  balloons: 86,
};

const CURRENCY_META: Record<
  CurrencyKey,
  {
    label: string;
    shape: string;
    color: string;
    earnedWhen: string;
    spentOn: string;
    cap: number;
  }
> = {
  hearts: {
    label: "Hearts",
    shape: "❤",
    color: "#ff6b8a",
    earnedWhen: "Exact item overlap, care packages, shared confirmation.",
    spentOn: "Care packages, shared notes, featured shared items.",
    cap: 30,
  },
  stars: {
    label: "Stars",
    shape: "⭐",
    color: "#ffd66b",
    earnedWhen: "Category congruence and sustained category match.",
    spentOn: "Boost item visibility, reveal resonance types.",
    cap: 20,
  },
  moons: {
    label: "Moons",
    shape: "☾",
    color: "#a8d4ff",
    earnedWhen: "Complementary rhythm — your cart fills their gap.",
    spentOn: "Complementary filter, complement map, intro requests.",
    cap: 20,
  },
  hourglasses: {
    label: "Hourglasses",
    shape: "⏳",
    color: "#c9a8d4",
    earnedWhen: "Values-alignment quiz and long-term worldview match.",
    spentOn: "Reveal deeper resonance and worldview profiles.",
    cap: 15,
  },
  balloons: {
    label: "Balloons",
    shape: "🎈",
    color: "#ff9f43",
    earnedWhen: "Weekly presence, daily check-ins, streaks, events.",
    spentOn: "Float level is determined by accumulation, not payment.",
    cap: 500,
  },
};

const FLOAT_LEVELS = [
  { label: "Grounded", range: "0-9", description: "Default new user, minimal visibility." },
  { label: "Rising", range: "10-49", description: "Visible to other Rising+ users." },
  { label: "Airy", range: "50-149", description: "Visible to Airy+ users." },
  { label: "Drifting", range: "150-499", description: "Visible to Drifting+ users." },
  { label: "Cloud Walking", range: "500+", description: "Top tier, most visible, most trusted." },
] as const;

const SIGNALS = [
  {
    label: "Resonance is contribution",
    detail: "You earn by improving the field, not by buying attention.",
  },
  {
    label: "Visibility is bounded",
    detail: "The ledger can grow, but the lattice stays finite.",
  },
  {
    label: "Presence matters",
    detail: "Balloons measure how consistently you actually show up.",
  },
];

const RECENT_DEFAULT = [
  {
    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 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 floatMeta(balloons: number) {
  if (balloons >= 500) return FLOAT_LEVELS[4];
  if (balloons >= 150) return FLOAT_LEVELS[3];
  if (balloons >= 50) return FLOAT_LEVELS[2];
  if (balloons >= 10) return FLOAT_LEVELS[1];
  return FLOAT_LEVELS[0];
}

function normalize(value: number, cap: number) {
  return clamp(value / cap, 0, 1);
}

function deriveResonanceScore(balances: Record<CurrencyKey, number>) {
  const weighted =
    normalize(balances.hearts, CURRENCY_META.hearts.cap) * 1.5 +
    normalize(balances.stars, CURRENCY_META.stars.cap) * 1.0 +
    normalize(balances.moons, CURRENCY_META.moons.cap) * 1.2 +
    normalize(balances.hourglasses, CURRENCY_META.hourglasses.cap) * 1.5 +
    normalize(balances.balloons, CURRENCY_META.balloons.cap) * 0.8;

  return Math.round((weighted / 6) * 100);
}

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

export default function CurrencyLedger({
  title = "Five Currencies",
  subtitle = "Contribution-based currency for resonance, trust, and visibility.",
  balances,
  recentSignals = RECENT_DEFAULT,
}: CurrencyLedgerProps) {
  const ledger = useMemo(
    () => ({ ...DEFAULT_BALANCES, ...balances }),
    [balances],
  );

  const resonanceScore = deriveResonanceScore(ledger);
  const resonanceLabel = scoreLabel(resonanceScore);
  const float = floatMeta(ledger.balloons);

  const rootStyle: CSSProperties = {
    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",
  };

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

  return (
    <section style={rootStyle}>
      <div style={{ maxWidth: 1240, margin: "0 auto", display: "grid", gap: 18 }}>
        <div 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 / Currency System</div>
              <h1 style={{ margin: "8px 0 8px", fontSize: 34, lineHeight: 1.05, color: "#f6d9b3" }}>{title}</h1>
              <p style={{ margin: 0, color: "#ada8b6", maxWidth: 780, fontSize: 15, lineHeight: 1.55 }}>{subtitle}</p>
            </div>

            <div style={{ minWidth: 300, maxWidth: 380, 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: CURRENCY_META.balloons.color }}>{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 = contribution, not access. The only thing you can buy is a clearer reading of your own field.
              </div>
            </div>
          </div>
        </div>

        <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: "grid", gap: 12 }}>
                {(Object.keys(CURRENCY_META) as CurrencyKey[]).map((key) => {
                  const meta = CURRENCY_META[key];
                  const value = ledger[key];
                  return (
                    <article
                      key={key}
                      style={{
                        borderRadius: 18,
                        border: `1px solid color-mix(in srgb, ${meta.color} 30%, rgba(255,255,255,0.12))`,
                        background: `color-mix(in srgb, ${meta.color} 10%, rgba(255,255,255,0.03))`,
                        padding: 16,
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
                        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                          <div style={{ width: 38, height: 38, borderRadius: 999, background: `${meta.color}22`, display: "grid", placeItems: "center", color: meta.color, fontSize: 18 }}>
                            {meta.shape}
                          </div>
                          <div>
                            <div style={{ fontWeight: 800, fontSize: 16 }}>{meta.label}</div>
                            <div style={{ color: "#a7a0b2", fontSize: 12, marginTop: 2 }}>{meta.earnedWhen}</div>
                          </div>
                        </div>
                        <div style={{ textAlign: "right" }}>
                          <div style={{ fontSize: 11, color: "#98a0ad", textTransform: "uppercase", letterSpacing: "0.1em" }}>Balance</div>
                          <div style={{ fontSize: 24, fontWeight: 800, color: meta.color }}>{value}</div>
                        </div>
                      </div>

                      <div style={{ marginTop: 12, display: "grid", gap: 8 }}>
                        <div style={{ display: "grid", gap: 6 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                            <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Capacity</div>
                            <div style={{ fontSize: 12, color: meta.color }}>{barWidth(value, meta.cap)}</div>
                          </div>
                          <div style={{ height: 8, borderRadius: 999, overflow: "hidden", background: "rgba(255,255,255,0.08)" }}>
                            <div
                              style={{
                                width: barWidth(value, meta.cap),
                                height: "100%",
                                borderRadius: 999,
                                background: `linear-gradient(90deg, ${meta.color}, color-mix(in srgb, ${meta.color} 72%, white))`,
                                boxShadow: `0 0 18px ${meta.color}44`,
                                transition: "width 220ms ease",
                              }}
                            />
                          </div>
                        </div>

                        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 10 }}>
                          <InfoCard label="Earned when" text={meta.earnedWhen} tone={meta.color} />
                          <InfoCard label="Spent on" text={meta.spentOn} tone={meta.color} />
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Contribution rules</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                {SIGNALS.map((signal) => (
                  <div key={signal.label} style={{ borderRadius: 16, padding: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
                    <div style={{ fontWeight: 800, fontSize: 14 }}>{signal.label}</div>
                    <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 13, lineHeight: 1.5 }}>{signal.detail}</div>
                  </div>
                ))}
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Float thresholds</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                {FLOAT_LEVELS.map((level, index) => {
                  const active = index === floatIndex(float.label);
                  return (
                    <div
                      key={level.label}
                      style={{
                        borderRadius: 16,
                        padding: 12,
                        background: active ? `${CURRENCY_META.balloons.color}18` : "rgba(255,255,255,0.03)",
                        border: active ? `1px solid ${CURRENCY_META.balloons.color}44` : "1px solid rgba(255,255,255,0.08)",
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
                        <div style={{ fontWeight: 800 }}>{level.label}</div>
                        <div style={{ fontSize: 12, color: active ? CURRENCY_META.balloons.color : "#9ca3af" }}>{level.range}</div>
                      </div>
                      <div style={{ marginTop: 4, color: "#b6ac9d", fontSize: 13, lineHeight: 1.5 }}>{level.description}</div>
                    </div>
                  );
                })}
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>How the score reads</div>
              <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
                <InfoCard label="Hearts" text="Direct overlap, strongest signal." tone={CURRENCY_META.hearts.color} />
                <InfoCard label="Stars" text="Category congruence, same orientation." tone={CURRENCY_META.stars.color} />
                <InfoCard label="Moons" text="Complementary rhythm, missing-piece fit." tone={CURRENCY_META.moons.color} />
                <InfoCard label="Hourglasses" text="Values alignment, worldview over time." tone={CURRENCY_META.hourglasses.color} />
                <InfoCard label="Balloons" text="Presence and tenure, not payment." tone={CURRENCY_META.balloons.color} />
              </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 }}>
                {recentSignals.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 floatIndex(label: string) {
  return FLOAT_LEVELS.findIndex((level) => level.label === label);
}

function InfoCard({ label, text, tone }: { label: string; text: string; tone: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: `1px solid color-mix(in srgb, ${tone} 24%, rgba(255,255,255,0.08))` }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{label}</div>
      <div style={{ marginTop: 6, color: "#d8d0c2", fontSize: 14, lineHeight: 1.55 }}>{text}</div>
    </div>
  );
}
