// "Find your ring" — interactive membership depth gauge.
// A weighted scrub track drives:
//   - animated price counter (3 styles)
//   - live stats (essays/mo, minutes/wk, credits)
//   - a flow curve from handle into the recommended tier card
//   - tier cards re-stack: the matching tier lifts, others recede
//   - subtle ambient bg motion
//
// Motion is gated by the global tweak `motion` (subtle / standard / showy).

const {
  useState: useStateMC,
  useEffect: useEffectMC,
  useRef: useRefMC,
  useMemo: useMemoMC,
  useCallback: useCallbackMC,
} = React;

// ---------- math helpers ----------
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
const lerp = (a, b, t) => a + (b - a) * t;
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);

// Depth in [0..1] -> recommended tier id
function tierFor(depth) {
  if (depth < 0.34) return "free";
  if (depth < 0.72) return "loop";
  return "inner";
}

// Depth -> live stats (deterministic, smooth)
function statsFor(depth) {
  // essays/mo: 1 -> 16
  const essays = Math.round(lerp(1, 16, easeOutCubic(depth)));
  // minutes/wk: 6 -> 140
  const minutes = Math.round(lerp(6, 140, easeOutCubic(depth)) / 2) * 2;
  // credits: 10 -> 320 (just a flavor metric)
  const credits = Math.round(lerp(10, 320, easeOutCubic(depth)) / 5) * 5;
  // price (matches tier definition exactly at thresholds)
  const t = tierFor(depth);
  const price = t === "free" ? 0 : t === "loop" ? 15 : 50;
  return { essays, minutes, credits, price, tier: t };
}

// ---------- odometer-style digit column ----------
function OdoDigit({ digit }) {
  // digit is 0..9 (or "$"/","/"."/" " which we pass-through)
  const isNum = /^\d$/.test(String(digit));
  if (!isNum) {
    return <span className="mc-digit mc-digit-static">{digit}</span>;
  }
  const d = parseInt(digit, 10);
  return (
    <span className="mc-digit">
      <span
        className="mc-digit-track"
        style={{ transform: `translateY(${-d * 10}%)` }}
      >
        {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
          <span key={n} className="mc-digit-cell">{n}</span>
        ))}
      </span>
    </span>
  );
}

// scramble counter: animates a number with brief glyph flicker
function ScrambleNumber({ value, prefix = "", suffix = "" }) {
  const [shown, setShown] = useStateMC(value);
  const targetRef = useRefMC(value);
  const rafRef = useRefMC(0);
  useEffectMC(() => {
    targetRef.current = value;
    let start = performance.now();
    const from = shown;
    const dur = 320;
    cancelAnimationFrame(rafRef.current);
    const tick = (now) => {
      const t = clamp((now - start) / dur, 0, 1);
      const eased = easeOutCubic(t);
      const cur = Math.round(lerp(from, value, eased));
      setShown(cur);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
    // eslint-disable-next-line
  }, [value]);
  // brief scramble overlay characters using random glyphs
  const chars = String(shown).split("");
  return (
    <span className="mc-scramble">
      {prefix}
      {chars.map((c, i) => (
        <span key={i} className="mc-scramble-ch">{c}</span>
      ))}
      {suffix}
    </span>
  );
}

// Odometer wrapper: e.g. "$15" or "16"
function Odometer({ value, prefix = "", suffix = "" }) {
  const str = `${prefix}${value}${suffix}`;
  return (
    <span className="mc-odo">
      {str.split("").map((ch, i) => (
        <OdoDigit key={i + ":" + ch} digit={ch} />
      ))}
    </span>
  );
}

// Plain counter that just animates the number with no flair
function PlainCounter({ value, prefix = "", suffix = "" }) {
  const [shown, setShown] = useStateMC(value);
  const rafRef = useRefMC(0);
  useEffectMC(() => {
    let start = performance.now();
    const from = shown;
    const dur = 280;
    cancelAnimationFrame(rafRef.current);
    const tick = (now) => {
      const t = clamp((now - start) / dur, 0, 1);
      const cur = Math.round(lerp(from, value, easeOutCubic(t)));
      setShown(cur);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
    // eslint-disable-next-line
  }, [value]);
  return <span className="mc-plain">{prefix}{shown}{suffix}</span>;
}

function Counter({ value, style = "odo", prefix = "", suffix = "" }) {
  if (style === "scramble") return <ScrambleNumber value={value} prefix={prefix} suffix={suffix} />;
  if (style === "plain") return <PlainCounter value={value} prefix={prefix} suffix={suffix} />;
  return <Odometer value={value} prefix={prefix} suffix={suffix} />;
}

// ---------- the main widget ----------
function FindYourRing({ navigate }) {
  const { TIERS } = window.HOAGS_DATA;
  // Underlying target driven by interactions
  const [target, setTarget] = useStateMC(0.46); // sits in Loop by default
  // Smoothed value used to drive visuals (spring lerp)
  const [depth, setDepth] = useStateMC(0.46);
  const [dragging, setDragging] = useStateMC(false);
  const [hover, setHover] = useStateMC({ x: 0, y: 0, in: false });
  const trackRef = useRefMC(null);
  const wrapRef = useRefMC(null);
  const rafRef = useRefMC(0);

  // Pull global motion tweak — kept reactive via hoags:tweaks event
  const [motion, setMotion] = useStateMC(
    document.documentElement.dataset.thMotion || "standard"
  );
  const [counterStyle, setCounterStyle] = useStateMC(
    document.documentElement.dataset.thCounter || "odo"
  );
  useEffectMC(() => {
    const onTweaks = (e) => {
      const d = e.detail || {};
      if (d.motion) setMotion(d.motion);
      if (d.counter) setCounterStyle(d.counter);
    };
    window.addEventListener("hoags:tweaks", onTweaks);
    return () => window.removeEventListener("hoags:tweaks", onTweaks);
  }, []);
  const intensity = motion === "subtle" ? 0.45 : motion === "showy" ? 1.25 : 1;
  const ambient = motion !== "subtle";

  // Spring loop toward target
  useEffectMC(() => {
    const tick = () => {
      setDepth((d) => {
        const diff = target - d;
        if (Math.abs(diff) < 0.0008) return target;
        // ease constant — showy = snappier, subtle = softer
        const k = motion === "showy" ? 0.22 : motion === "subtle" ? 0.10 : 0.16;
        return d + diff * k;
      });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [target, motion]);

  const stats = useMemoMC(() => statsFor(depth), [depth]);
  const liveTier = stats.tier;

  // pointer handling
  const setFromClientX = useCallbackMC((clientX) => {
    const el = trackRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const t = clamp((clientX - r.left) / r.width, 0, 1);
    setTarget(t);
  }, []);

  useEffectMC(() => {
    if (!dragging) return;
    const onMove = (e) => {
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      setFromClientX(x);
    };
    const onUp = () => setDragging(false);
    window.addEventListener("mousemove", onMove);
    window.addEventListener("touchmove", onMove, { passive: true });
    window.addEventListener("mouseup", onUp);
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("mouseup", onUp);
      window.removeEventListener("touchend", onUp);
    };
  }, [dragging, setFromClientX]);

  // keyboard
  const onKey = (e) => {
    if (e.key === "ArrowLeft") { setTarget((v) => clamp(v - 0.05, 0, 1)); e.preventDefault(); }
    if (e.key === "ArrowRight") { setTarget((v) => clamp(v + 0.05, 0, 1)); e.preventDefault(); }
    if (e.key === "Home") { setTarget(0); e.preventDefault(); }
    if (e.key === "End") { setTarget(1); e.preventDefault(); }
  };

  // cursor-follow soft glow
  const onWrapMove = (e) => {
    if (!wrapRef.current) return;
    const r = wrapRef.current.getBoundingClientRect();
    setHover({ x: e.clientX - r.left, y: e.clientY - r.top, in: true });
  };

  // ---------- flow curve geometry ----------
  // Build an SVG path from the handle down toward the recommended card.
  // Three target anchor x positions correspond to the three cards.
  const cardAnchors = { free: 0.166, loop: 0.5, inner: 0.834 }; // fractions of width
  const curveX1 = depth; // handle position
  const curveX2 = cardAnchors[liveTier];

  // Path in 0..1 normalized coords, we transform via SVG viewBox
  // Start at (curveX1, 0.05) -- handle bottom
  // End at (curveX2, 0.95)   -- top of the recommended card
  const cp1y = 0.45 + (curveX2 - curveX1) * 0.0 + 0.05 * Math.sin(depth * Math.PI * 2);
  const path = `M ${curveX1} 0.05
                C ${curveX1} ${0.4 + 0.1 * intensity},
                  ${curveX2} ${0.6 - 0.1 * intensity},
                  ${curveX2} 0.95`;

  return (
    <div
      ref={wrapRef}
      className={"mc-wrap" + (dragging ? " mc-is-drag" : "") + " mc-motion-" + motion}
      onMouseMove={onWrapMove}
      onMouseLeave={() => setHover((h) => ({ ...h, in: false }))}
    >
      {/* ambient background lines */}
      {ambient && <AmbientField intensity={intensity} depth={depth} />}

      {/* cursor follow soft halo */}
      {hover.in && motion !== "subtle" && (
        <span
          className="mc-halo"
          style={{
            transform: `translate(${hover.x - 280}px, ${hover.y - 280}px)`,
          }}
          aria-hidden="true"
        />
      )}

      <header className="mc-head">
        <span className="th-eyebrow mc-eyebrow">Find your ring</span>
        <h2 className="mc-title">
          Pick the depth.{" "}
          <span className="th-h-italic">Let the price find you.</span>
        </h2>
        <p className="mc-sub">
          Drag the handle. The three rings rearrange to show what fits the way
          you actually read. No upsell pressure — Feed is free and stays that way.
        </p>
      </header>

      {/* SCRUB */}
      <div className="mc-scrub">
        <div className="mc-scrub-labels">
          <span className={liveTier === "free" ? "is-on" : ""}>
            <em>Light</em> · a few essays
          </span>
          <span className={liveTier === "loop" ? "is-on" : ""}>
            <em>Regular</em> · working notes
          </span>
          <span className={liveTier === "inner" ? "is-on" : ""}>
            <em>Deep</em> · the full stack
          </span>
        </div>

        <div
          ref={trackRef}
          className="mc-track"
          role="slider"
          tabIndex={0}
          aria-valuemin={0}
          aria-valuemax={100}
          aria-valuenow={Math.round(depth * 100)}
          aria-label="Reading depth"
          onKeyDown={onKey}
          onMouseDown={(e) => { setDragging(true); setFromClientX(e.clientX); }}
          onTouchStart={(e) => { setDragging(true); setFromClientX(e.touches[0].clientX); }}
        >
          {/* tier zones */}
          <span className="mc-zone mc-zone-free" />
          <span className="mc-zone mc-zone-loop" />
          <span className="mc-zone mc-zone-inner" />

          {/* tick marks */}
          {[0, 0.34, 0.72, 1].map((p, i) => (
            <span key={i} className="mc-tick" style={{ left: `${p * 100}%` }} />
          ))}

          {/* fill */}
          <span
            className="mc-fill"
            style={{ width: `${depth * 100}%` }}
          />

          {/* handle */}
          <span
            className={"mc-handle " + ("mc-handle-" + liveTier)}
            style={{ left: `${depth * 100}%` }}
          >
            <span className="mc-handle-dot" />
            <span className="mc-handle-ring" />
            <span className="mc-handle-pulse" />
          </span>
        </div>

        {/* live stats row */}
        <div className="mc-stats">
          <Stat label="Essays / mo" value={stats.essays} style={counterStyle} />
          <Stat label="Minutes / wk" value={stats.minutes} style={counterStyle} />
          <Stat label="Reading credits" value={stats.credits} style={counterStyle} />
          <Stat
            label="At this depth"
            value={stats.price}
            prefix={stats.price ? "$" : ""}
            suffix={stats.price ? "/mo" : ""}
            big
            style={counterStyle}
            zero="Free"
          />
        </div>
      </div>

      {/* FLOW CURVE — links handle to the recommended card */}
      <svg className="mc-flow" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true">
        <defs>
          <linearGradient id="mc-flow-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--th-orange)" stopOpacity="0.85" />
            <stop offset="100%" stopColor="var(--th-hunter)" stopOpacity="0.0" />
          </linearGradient>
        </defs>
        <path
          d={path}
          fill="none"
          stroke="url(#mc-flow-grad)"
          strokeWidth="0.006"
          strokeLinecap="round"
        />
      </svg>

      {/* TIER CARDS */}
      <div className="mc-rings" data-live={liveTier}>
        {TIERS.map((t) => {
          const isLive = t.id === liveTier;
          const monthly = t.price;
          return (
            <div
              key={t.id}
              className={"mc-ring mc-ring-" + t.id + (isLive ? " mc-ring-live" : "")}
              style={{
                "--mc-accent": t.accent,
                transform: isLive
                  ? `translateY(${-10 * intensity}px) scale(${1 + 0.012 * intensity})`
                  : `translateY(${6 * intensity}px) scale(${1 - 0.01 * intensity})`,
              }}
            >
              <div className="mc-ring-head">
                <span className="mc-ring-mark" style={{ background: t.accent }} />
                <div className="mc-ring-name" style={{ color: t.accent }}>{t.name}</div>
                {isLive && (
                  <span className="mc-ring-pin">Your fit</span>
                )}
              </div>
              <p className="mc-ring-blurb">{t.blurb}</p>
              <div className="mc-ring-price">
                {t.price === 0 ? (
                  <span className="mc-ring-free">Free</span>
                ) : (
                  <>
                    <span className="mc-ring-price-num">
                      <Counter value={monthly} style={isLive ? counterStyle : "plain"} prefix="$" />
                    </span>
                    <span className="mc-ring-price-cad">/mo</span>
                  </>
                )}
              </div>
              <ul className="mc-ring-feats">
                {t.features.slice(0, 3).map((f, i) => (
                  <li key={i}>
                    <span className="mc-ring-bullet" style={{ background: t.accent }} />
                    {f}
                  </li>
                ))}
              </ul>
              <button
                className="mc-ring-cta"
                style={{
                  background: isLive ? t.accent : "transparent",
                  color: isLive ? "var(--th-stone)" : t.accent,
                  borderColor: t.accent,
                }}
                onClick={() => navigate("subscribe")}
              >
                {isLive ? t.cta + " →" : "Choose " + t.name}
              </button>
            </div>
          );
        })}
      </div>

      {/* depth ruler footer */}
      <div className="mc-ruler" aria-hidden="true">
        {Array.from({ length: 40 }).map((_, i) => {
          const t = i / 39;
          const active = t <= depth;
          return (
            <span
              key={i}
              className={"mc-ruler-tick" + (active ? " is-on" : "")}
              style={{
                height: `${8 + (i % 4 === 0 ? 8 : 0)}px`,
                opacity: active ? lerp(0.45, 1, t) : 0.18,
              }}
            />
          );
        })}
      </div>
    </div>
  );
}

// ---------- bits ----------

function Stat({ label, value, prefix = "", suffix = "", big = false, style = "odo", zero }) {
  return (
    <div className={"mc-stat" + (big ? " mc-stat-big" : "")}>
      <span className="mc-stat-label">{label}</span>
      <span className="mc-stat-val">
        {zero && value === 0 ? (
          <span className="mc-stat-zero">{zero}</span>
        ) : (
          <Counter value={value} prefix={prefix} suffix={suffix} style={style} />
        )}
      </span>
    </div>
  );
}

// Ambient background — slow drifting horizontal lines and a soft halo.
function AmbientField({ intensity, depth }) {
  // animate offset via rAF
  const [phase, setPhase] = useStateMC(0);
  useEffectMC(() => {
    let raf;
    const tick = (t) => {
      setPhase((p) => (p + 0.0008) % 1);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // build 5 lines with different speeds
  const lines = [0.20, 0.35, 0.55, 0.7, 0.85];
  return (
    <svg className="mc-ambient" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
      {lines.map((y, i) => {
        const speed = 0.4 + i * 0.18;
        const off = (phase * speed) % 1;
        const wave = 1.2 + intensity * (0.6 + 0.4 * Math.sin((phase + i) * Math.PI * 2));
        // draw a smooth sine path
        const pts = [];
        for (let x = 0; x <= 100; x += 4) {
          const yy = y * 100 + Math.sin((x / 100 + off) * Math.PI * 2 * (1 + i * 0.2)) * wave * (1 + 0.4 * depth);
          pts.push((x === 0 ? "M" : "L") + x + " " + yy);
        }
        return (
          <path
            key={i}
            d={pts.join(" ")}
            fill="none"
            stroke="var(--th-hunter)"
            strokeWidth="0.18"
            opacity={0.08 + i * 0.015}
          />
        );
      })}
    </svg>
  );
}

// ---------- inline styles ----------

(function injectMCStyles() {
  if (document.getElementById("mc-styles")) return;
  const css = `
  .mc-wrap {
    position: relative;
    max-width: 1180px;
    margin: 32px auto 64px;
    padding: 64px 56px 56px;
    background: linear-gradient(180deg, rgba(31,61,46,0.04), rgba(31,61,46,0.0)),
                var(--th-card-bg, #fff);
    border: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    border-radius: 10px;
    overflow: hidden;
    isolation: isolate;
  }
  .mc-ambient {
    position: absolute; inset: 0;
    width: 100%; height: 100%;
    pointer-events: none;
    z-index: 0;
  }
  .mc-halo {
    position: absolute;
    width: 560px; height: 560px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(201,98,46,0.10), rgba(201,98,46,0) 60%);
    pointer-events: none;
    z-index: 0;
    mix-blend-mode: multiply;
    transition: transform 240ms cubic-bezier(.2,.7,.2,1);
    will-change: transform;
  }

  .mc-head { position: relative; z-index: 2; text-align: center; margin-bottom: 40px; }
  .mc-eyebrow { display: block; margin-bottom: 14px; }
  .mc-title {
    font-family: var(--th-font-display);
    font-size: clamp(36px, 4.4vw, 56px);
    line-height: 1.04; letter-spacing: -0.022em;
    font-weight: 500;
    color: var(--th-hunter);
    margin: 0 0 14px;
  }
  .mc-title .th-h-italic { font-style: italic; color: var(--th-navy); }
  .mc-sub {
    font-family: var(--th-font-serif);
    font-size: 18px; line-height: 1.55;
    color: var(--th-ink-soft);
    max-width: 56ch;
    margin: 0 auto;
  }

  /* SCRUB */
  .mc-scrub { position: relative; z-index: 3; margin: 0 8px 56px; }
  .mc-scrub-labels {
    display: flex; justify-content: space-between;
    font-family: var(--th-font-mono);
    font-size: 11px; text-transform: uppercase; letter-spacing: 0.14em;
    color: var(--th-ink-quiet);
    margin: 0 6px 14px;
  }
  .mc-scrub-labels span { transition: color 220ms; }
  .mc-scrub-labels em { font-style: normal; }
  .mc-scrub-labels span.is-on { color: var(--th-hunter); }
  .mc-scrub-labels span.is-on em { color: var(--th-orange); font-style: italic; }

  .mc-track {
    position: relative;
    height: 22px;
    border-radius: 999px;
    background: rgba(31,61,46,0.06);
    cursor: grab;
    user-select: none;
  }
  .mc-wrap.mc-is-drag .mc-track { cursor: grabbing; }
  .mc-track:focus { outline: 2px solid var(--th-navy); outline-offset: 4px; }

  .mc-zone {
    position: absolute; top: 0; bottom: 0;
    border-radius: 999px;
    opacity: 0.5;
  }
  .mc-zone-free  { left: 0;    width: 34%; background: rgba(31,61,46,0.04); }
  .mc-zone-loop  { left: 34%;  width: 38%; background: rgba(27,42,74,0.06); }
  .mc-zone-inner { left: 72%;  width: 28%; background: rgba(107,34,48,0.06); }

  .mc-tick {
    position: absolute; top: 50%; transform: translate(-50%, -50%);
    width: 1px; height: 14px;
    background: rgba(31,61,46,0.18);
  }

  .mc-fill {
    position: absolute; top: 0; bottom: 0; left: 0;
    background: linear-gradient(90deg, rgba(31,61,46,0.18), var(--th-hunter));
    border-radius: 999px;
    transition: width 80ms linear;
  }

  .mc-handle {
    position: absolute; top: 50%;
    transform: translate(-50%, -50%);
    width: 36px; height: 36px;
    pointer-events: none;
  }
  .mc-handle-dot {
    position: absolute; inset: 8px;
    border-radius: 50%;
    background: var(--th-stone);
    border: 2px solid var(--th-hunter);
    box-shadow: 0 4px 12px rgba(31,61,46,0.25), 0 1px 3px rgba(31,61,46,0.18);
  }
  .mc-handle-free .mc-handle-dot { border-color: var(--th-hunter); }
  .mc-handle-loop .mc-handle-dot { border-color: var(--th-navy); }
  .mc-handle-inner .mc-handle-dot { border-color: var(--th-oxblood); }
  .mc-handle-ring {
    position: absolute; inset: 0;
    border-radius: 50%;
    border: 1.5px solid currentColor;
    color: var(--th-orange);
    opacity: 0.35;
  }
  .mc-handle-pulse {
    position: absolute; inset: -8px;
    border-radius: 50%;
    border: 1px solid var(--th-orange);
    opacity: 0;
    animation: mc-pulse 2.4s ease-out infinite;
  }
  .mc-motion-subtle .mc-handle-pulse { animation: none; opacity: 0; }
  .mc-motion-showy .mc-handle-pulse { animation-duration: 1.6s; }
  @keyframes mc-pulse {
    0% { transform: scale(0.9); opacity: 0.55; }
    80% { transform: scale(1.9); opacity: 0; }
    100% { transform: scale(1.9); opacity: 0; }
  }

  /* STATS */
  .mc-stats {
    margin-top: 28px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0;
    border-top: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    border-bottom: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
  }
  .mc-stat {
    padding: 20px 18px;
    border-right: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    display: flex; flex-direction: column; gap: 6px;
  }
  .mc-stat:last-child { border-right: 0; }
  .mc-stat-label {
    font-family: var(--th-font-mono);
    font-size: 10px;
    letter-spacing: 0.16em;
    text-transform: uppercase;
    color: var(--th-ink-quiet);
  }
  .mc-stat-val {
    font-family: var(--th-font-display);
    font-weight: 500;
    font-size: 32px;
    line-height: 1.2;
    color: var(--th-hunter);
    letter-spacing: -0.02em;
    display: inline-flex; align-items: baseline;
  }
  .mc-stat-big .mc-stat-val { font-size: 44px; color: var(--th-hunter); font-style: italic; }
  .mc-stat-zero { font-style: italic; font-weight: 400; }

  /* odometer digits */
  .mc-odo {
    display: inline-flex;
    align-items: baseline;
    line-height: 1.2;
  }
  .mc-digit {
    display: inline-block;
    height: 1.2em;
    overflow: hidden;
    vertical-align: baseline;
    line-height: 1.2;
  }
  .mc-digit-static {
    display: inline-block;
    width: auto;
    height: 1.2em;
    line-height: 1.2;
  }
  .mc-digit-track {
    display: flex; flex-direction: column;
    transition: transform 360ms cubic-bezier(.5,0,.15,1);
    will-change: transform;
  }
  .mc-motion-showy .mc-digit-track { transition-duration: 240ms; }
  .mc-motion-subtle .mc-digit-track { transition-duration: 520ms; }
  .mc-digit-cell {
    display: block;
    height: 1.2em;
    line-height: 1.2;
    text-align: center;
    min-width: 0.6em;
  }

  /* scramble */
  .mc-scramble { display: inline-flex; }
  .mc-scramble-ch {
    display: inline-block;
    animation: mc-scramble-in 360ms ease;
  }
  @keyframes mc-scramble-in {
    0% { opacity: 0; transform: translateY(-6px) skewX(-4deg); filter: blur(2px); }
    40% { opacity: 1; }
    100% { opacity: 1; transform: none; filter: none; }
  }

  .mc-plain { display: inline-block; }

  /* FLOW */
  .mc-flow {
    position: absolute;
    left: 56px; right: 56px;
    top: 260px; height: 280px;
    pointer-events: none;
    z-index: 1;
  }

  /* RINGS */
  .mc-rings {
    position: relative; z-index: 2;
    display: grid; grid-template-columns: repeat(3, 1fr);
    gap: 22px;
    margin-top: 16px;
  }
  .mc-ring {
    background: var(--th-card-bg, #fff);
    border: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    border-radius: 8px;
    padding: 28px 26px 26px;
    display: flex; flex-direction: column; gap: 14px;
    transition:
      transform 460ms cubic-bezier(.2,.7,.2,1),
      box-shadow 460ms ease,
      border-color 320ms ease,
      filter 320ms ease;
    will-change: transform;
  }
  .mc-motion-subtle .mc-ring { transition-duration: 700ms; }
  .mc-motion-showy .mc-ring { transition-duration: 360ms; }

  .mc-ring:not(.mc-ring-live) {
    filter: saturate(0.7);
    opacity: 0.78;
  }
  .mc-ring-live {
    box-shadow: 0 22px 60px -24px rgba(31,61,46,0.30),
                0 6px 18px -8px rgba(201,98,46,0.18);
    border-color: var(--mc-accent, var(--th-hunter));
    z-index: 3;
  }
  .mc-ring-head { display: flex; align-items: center; gap: 12px; }
  .mc-ring-mark {
    width: 10px; height: 28px; border-radius: 1px;
  }
  .mc-ring-name {
    font-family: var(--th-font-display);
    font-weight: 500;
    font-size: 22px;
    letter-spacing: -0.01em;
    flex: 1;
  }
  .mc-ring-pin {
    font-family: var(--th-font-mono);
    font-size: 9.5px; letter-spacing: 0.18em;
    text-transform: uppercase;
    color: var(--th-stone);
    background: var(--th-orange);
    padding: 5px 9px; border-radius: 2px;
    animation: mc-pop 380ms cubic-bezier(.2,.8,.2,1.2);
  }
  @keyframes mc-pop {
    0% { transform: scale(0.6); opacity: 0; }
    100% { transform: scale(1); opacity: 1; }
  }
  .mc-ring-blurb {
    font-family: var(--th-font-serif);
    font-size: 15px; line-height: 1.5;
    color: var(--th-ink-soft);
    margin: 0;
  }
  .mc-ring-price {
    display: flex; align-items: baseline; gap: 6px;
    border-top: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    border-bottom: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    padding: 14px 0;
  }
  .mc-ring-price-num {
    font-family: var(--th-font-display);
    font-weight: 500;
    font-size: 36px;
    line-height: 1.2;
    color: var(--th-hunter);
    letter-spacing: -0.02em;
  }
  .mc-ring-price-cad {
    font-family: var(--th-font-mono);
    font-size: 11px; letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--th-ink-quiet);
  }
  .mc-ring-free {
    font-family: var(--th-font-display);
    font-style: italic; font-weight: 500;
    font-size: 32px; color: var(--th-hunter);
  }
  .mc-ring-feats {
    list-style: none; margin: 0; padding: 0;
    display: flex; flex-direction: column; gap: 9px;
  }
  .mc-ring-feats li {
    font-family: var(--th-font-serif);
    font-size: 14.5px; line-height: 1.45;
    color: var(--th-ink-soft);
    display: flex; gap: 10px; align-items: baseline;
  }
  .mc-ring-bullet {
    flex: 0 0 6px;
    width: 6px; height: 6px;
    border-radius: 50%;
    transform: translateY(2px);
  }
  .mc-ring-cta {
    margin-top: 4px;
    font-family: var(--th-font-mono);
    font-size: 11px; letter-spacing: 0.14em;
    text-transform: uppercase;
    padding: 11px 14px;
    border: 1px solid;
    border-radius: 3px;
    cursor: pointer;
    transition: transform 160ms ease, background 160ms ease, color 160ms ease;
  }
  .mc-ring-cta:hover { transform: translateY(-1px); }

  /* depth ruler */
  .mc-ruler {
    margin-top: 36px;
    display: flex;
    align-items: flex-end;
    gap: 4px;
    height: 18px;
    justify-content: space-between;
    padding: 0 4px;
    border-top: 1px solid var(--th-rule-color, rgba(31,61,46,0.10));
    padding-top: 14px;
  }
  .mc-ruler-tick {
    flex: 1;
    background: var(--th-hunter);
    transition: opacity 200ms, height 200ms;
    border-radius: 1px;
  }
  .mc-ruler-tick.is-on { background: var(--th-orange); }

  @media (max-width: 880px) {
    .mc-wrap { padding: 40px 20px 32px; margin: 24px 12px 48px; }
    .mc-stats { grid-template-columns: repeat(2, 1fr); }
    .mc-stat { border-bottom: 1px solid var(--th-rule-color, rgba(31,61,46,0.10)); }
    .mc-rings { grid-template-columns: 1fr; }
    .mc-flow { display: none; }
  }
  `;
  const s = document.createElement("style");
  s.id = "mc-styles";
  s.textContent = css;
  document.head.appendChild(s);
})();

window.FindYourRing = FindYourRing;
