/* cst-stats.jsx — live social-proof numbers WITHOUT a backend or login.
   • Global "this week" counter is derived from the clock (everyone sees a similar,
     always-growing number) with a localStorage guard so it never ticks down for a
     returning user, and resets each week to match the "this week" copy.
   • The user's own activity persists per-browser in localStorage (no login).
   • Percentile lines are derived from the user's score so they feel personal.
   NOTE: these are SEEDED/SIMULATED numbers — swap globalThisWeek()/underpricedPct()
   for a real API call when a backend exists; nothing else changes.
   Exported to window.CST_STATS + LiveCounter to window. Loads after cst-core. */

const { useState: _stS, useEffect: _stE } = React;
const _STC = window.CST;
const { FONT: _stF, TEXT: _stT, HAZE: _stH, HAIR: _stHR, GLASS: _stG, AMBER: _stAM } = _STC;

// ---- tunables (believable, easy to change) --------------------------------
const WEEK_BASELINE = 2400;     // Monday-morning starting volume
const RATE_PER_SEC = 0.04;      // global decisions/sec (~3,456/day)
const LIVE_TICK_MS = 3200;      // how often the on-screen number ticks
const FREE_ANON = 3;            // free decisions for anonymous users
const FREE_AUTHED = 10;         // free decisions for logged-in users
const DAY_MS = 86400000;

// ---- localStorage helpers (safe in private mode) --------------------------
function lsGet(k, d) { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } }
function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} }

// ---- the user's own activity (per browser, no login) ----------------------
function userRuns() { return lsGet('cst_runs', 0); }
function userRunsTool(tool) { return lsGet('cst_runs_' + tool, 0); }
function bumpRun(tool) {
  const n = userRuns() + 1; lsSet('cst_runs', n);
  if (tool) lsSet('cst_runs_' + tool, userRunsTool(tool) + 1);
  recordUse();
  // also record server-side if authenticated (fire-and-forget)
  if (window.CST_AUTH && window.CST_AUTH.recordUse) window.CST_AUTH.recordUse(tool);
  return n;
}

// ---- freemium gate: 3 anon / 10 logged-in / unlimited subscribed ----------
let _isAuthed = false;          // synced from app.jsx
let _profilePlan = null;
function syncAuth(loggedIn) { _isAuthed = !!loggedIn; }
function syncPlan(plan) { _profilePlan = plan === 'unlimited' ? 'unlimited' : null; }
function isAuthed() { return _isAuthed; }

function usesWindow() { return lsGet('cst_uses', []).filter((t) => Date.now() - t < DAY_MS); }
function recordUse() { const a = usesWindow(); a.push(Date.now()); lsSet('cst_uses', a); return a.length; }
function usesToday() { return usesWindow().length; }
function freeLimit() { return isSubscribed() ? Infinity : _isAuthed ? FREE_AUTHED : FREE_ANON; }
function usesLeft() { const fl = freeLimit(); return fl === Infinity ? Infinity : Math.max(0, fl - usesToday()); }
// ms until the oldest in-window use expires and frees a slot
function resetInMs() {
  const fl = freeLimit();
  if (fl === Infinity) return 0;
  const a = usesWindow().sort((x, y) => x - y);
  if (a.length < fl) return 0;
  return Math.max(0, DAY_MS - (Date.now() - a[0]));
}
function isSubscribed() { return !!lsGet('cst_sub', false) || !!_profilePlan; }
function setSubscribed(v) { lsSet('cst_sub', !!v); }
function canRun() { return isSubscribed() || usesLeft() > 0; }
// pretty "Xh Ym" / "Ym" countdown
function fmtCountdown(ms) {
  if (ms <= 0) return 'now';
  const h = Math.floor(ms / 3600000), m = Math.floor((ms % 3600000) / 60000);
  return h > 0 ? `${h}h ${m}m` : `${m}m`;
}

// ---- weekly clock-seeded global counter -----------------------------------
function weekId() { return Math.floor((Date.now() / 86400000 + 3) / 7); } // ISO-ish week index
function weekStartSec() {
  const d = new Date();
  const dow = (d.getUTCDay() + 6) % 7; // Monday = 0
  return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - dow) / 1000;
}
// the "true" time-derived value (consistent across reloads + visitors)
function globalThisWeek() {
  const elapsed = Math.max(0, Math.floor(Date.now() / 1000) - weekStartSec());
  return WEEK_BASELINE + Math.floor(elapsed * RATE_PER_SEC) + userRuns();
}

// ---- personalized, believable percentiles ---------------------------------
const clamp = _STC.clamp;
function percentileFromScore(s) { return clamp(Math.round(s * 0.82 + 8), 6, 96); }
// stable-ish per week so it doesn't flip every render
function underpricedPct() { return 60 + (weekId() % 11); } // 60–70%

// ---- the live, deterministic counter component -----------------------------
function LiveCounter({ accent = _stAM, noun = 'decisions pressure-tested', style }) {
  const [n, setN] = _stS(() => globalThisWeek());
  _stE(() => {
    const id = setInterval(() => {
      setN(globalThisWeek());
    }, LIVE_TICK_MS);
    return () => clearInterval(id);
  }, []);
  const mine = userRuns();
  const pct = clamp(Math.min(96, 40 + mine * 6), 40, 96);
  return (
    <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 4, padding: '6px 12px', borderRadius: 14,
      background: _stG, border: `1px solid ${_stHR}`, backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ width: 7, height: 7, borderRadius: 99, background: '#5FD08C', boxShadow: '0 0 8px #5FD08C', animation: 'cstPulse 1.6s infinite' }} />
        <span style={{ fontFamily: _stF, fontSize: 11, color: _stH, letterSpacing: 0.2 }}>
          <span style={{ color: _stT, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{n.toLocaleString('en-US')}</span> {noun} this week
        </span>
      </div>
      {mine > 0 && (
        <div style={{ fontFamily: _stF, fontSize: 10.5, color: accent, letterSpacing: 0.2, paddingLeft: 15 }}>
          You: {mine} {mine === 1 ? 'run' : 'runs'} &middot; sharper than {pct}% of operators
        </div>
      )}
    </div>);
}

window.CST_STATS = {
  userRuns, userRunsTool, bumpRun, globalThisWeek, percentileFromScore, underpricedPct, weekId,
  usesToday, usesLeft, freeLimit, resetInMs, isSubscribed, isAuthed, setSubscribed, canRun, fmtCountdown, syncPlan, syncAuth,
};
window.LiveCounter = LiveCounter;
