/* cst-paywall.jsx — freemium gate UI. UsagePill (always-visible, upfront) +
   PaywallScreen (the upsell when free decisions run out). Usage is the rolling
   24h window from cst-stats (no login). Exported to window. */

const { useState: _pwS, useEffect: _pwE } = React;
const _PW = window.CST;
const { FONT: _pwF, TEXT: _pwT, HAZE: _pwH, HAZE_DIM: _pwHD, HAIR: _pwHR, GLASS: _pwG, GLASS_HI: _pwGH, INK: _pwI, AMBER: _pwAM, STATUS: _pwST } = _PW;
const S = window.CST_STATS;

// compact, always-on usage indicator (lives in the top bar)
function UsagePill({ onUpgrade, refreshKey }) {
  const sub = S.isSubscribed();
  const left = S.usesLeft();
  const limit = S.freeLimit();
  const authed = S.isAuthed();
  if (sub) {
    return (
      <button onClick={onUpgrade} style={{
        display: 'flex', alignItems: 'center', gap: 7, background: _pwAM + '1c', border: `1px solid ${_pwAM}66`,
        borderRadius: 10, padding: '7px 12px', cursor: 'pointer', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
      }}>
        <span style={{ color: _pwAM, fontSize: 11 }}>★</span>
        <span style={{ fontFamily: _pwF, fontSize: 11, fontWeight: 700, letterSpacing: 1, color: _pwAM }}>UNLIMITED</span>
      </button>);
  }
  const out = left === 0;
  const col = out ? _pwST.risk : _pwT;
  // anon: show dots (3); authed: show count badge instead of 10 dots
  const indicator = authed ? (
    <span style={{ fontFamily: _pwF, fontSize: 11, fontWeight: 700, color: out ? _pwST.risk : _pwST.good, fontVariantNumeric: 'tabular-nums' }}>{left}/{limit}</span>
  ) : (
    <span style={{ display: 'flex', gap: 3 }}>
      {Array.from({ length: limit }).map((_, i) => (
        <span key={i} style={{ width: 6, height: 6, borderRadius: 99, background: i < left ? _pwST.good : 'rgba(236,237,241,0.22)' }} />
      ))}
    </span>
  );
  return (
    <button onClick={onUpgrade} style={{
      display: 'flex', alignItems: 'center', gap: 8, background: _pwG, border: `1px solid ${out ? _pwST.risk + '66' : _pwHR}`,
      borderRadius: 10, padding: '7px 11px', cursor: 'pointer', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
    }}>
      {indicator}
      <span style={{ fontFamily: _pwF, fontSize: 11, fontWeight: 700, color: col, letterSpacing: 0.2 }}>
        {out ? (authed ? 'Go unlimited' : 'Sign in for more') : `${left} free left`}
      </span>
    </button>);
}

const BENEFITS = [
  'Unlimited Validate, SWOT & Price-It',
  'Every result as a shareable card',
  'Live re-runs as your numbers change',
  'First access to new tools',
];

function PaywallScreen({ active, accent = _pwAM, onSubscribe, onBook, onExit, onSignIn }) {
  const [, force] = _pwS(0);
  const sub = S.isSubscribed();
  const authed = S.isAuthed();
  const blocked = !sub && S.usesLeft() === 0;
  const limit = S.freeLimit();
  // tick the reset countdown while visible
  _pwE(() => {
    if (!active || sub) return;
    const id = setInterval(() => force((n) => n + 1), 30000);
    return () => clearInterval(id);
  }, [active, sub]);
  const countdown = S.fmtCountdown(S.resetInMs());

  // dynamic headline + body based on tier
  const blockedHeadline = authed
    ? `That\u2019s your ${limit} free decisions for today.`
    : `Sign in for ${10 - 3} more free decisions \u2014 or go unlimited.`;
  const idleBody = authed
    ? `You get ${limit} free decisions every 24 hours. Go unlimited and never wait.`
    : 'You get 3 free decisions without an account, or sign in for 10. Go unlimited and never wait.';

  return (
    <StageCard active={active} dir="up" label="Go unlimited">
      <Scrim from={0.15} to={0.98} />
      <div className="cst-scroll" style={{ position: 'relative', height: '100%', overflowY: 'auto' }}>
        <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '92px 24px 28px', gap: 15 }}>
          <Eyebrow color={accent}>CS Tech Unlimited</Eyebrow>

          {sub ? (
            <React.Fragment>
              <h2 style={{ margin: 0, fontFamily: _pwF, fontWeight: 700, fontSize: 27, letterSpacing: -1, lineHeight: 1.12, color: _pwT }}>You\u2019re on Unlimited.</h2>
              <p style={{ margin: 0, fontFamily: _pwF, fontSize: 13, lineHeight: 1.55, color: _pwH }}>Run every tool as much as you want. Manage your plan anytime in <span style={{ color: _pwT }}>[account settings]</span>.</p>
              <PrimaryBtn accent={accent} onClick={onExit}>Back to tools</PrimaryBtn>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <h2 style={{ margin: 0, fontFamily: _pwF, fontWeight: 700, fontSize: 26, letterSpacing: -1, lineHeight: 1.13, color: _pwT }}>
                {blocked ? blockedHeadline : 'Decide without limits.'}
              </h2>
              <p style={{ margin: 0, fontFamily: _pwF, fontSize: 13, lineHeight: 1.55, color: _pwH }}>
                {blocked
                  ? <React.Fragment>A fresh one unlocks in <span style={{ color: accent, fontWeight: 700 }}>{countdown}</span> — or go unlimited and keep deciding right now.</React.Fragment>
                  : idleBody}
              </p>

              {/* Sign in CTA for anonymous users */}
              {!authed && blocked && onSignIn && (
                <button onClick={onSignIn} style={{ cursor: 'pointer', padding: '12px 16px', borderRadius: 11, fontFamily: _pwF, fontWeight: 700, fontSize: 13, color: _pwT, background: 'rgba(236,237,241,0.08)', border: `1px solid ${_pwHR}`, marginBottom: 2 }}>
                  Sign in for 7 more free decisions →
                </button>
              )}

              <div style={{ display: 'flex', flexDirection: 'column', gap: 9, margin: '4px 0 2px' }}>
                {BENEFITS.map((b) => (
                  <div key={b} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                    <span style={{ color: accent, fontSize: 13, lineHeight: 1.4, flexShrink: 0 }}>✓</span>
                    <span style={{ fontFamily: _pwF, fontSize: 13, lineHeight: 1.4, color: 'rgba(236,237,241,0.86)' }}>{b}</span>
                  </div>
                ))}
              </div>

              {/* price card */}
              <div style={{ borderRadius: 14, border: `1px solid ${accent}55`, background: accent + '12', padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                    <span style={{ fontFamily: _pwF, fontWeight: 800, fontSize: 26, color: _pwT, letterSpacing: -0.5 }}>$4.99</span>
                    <span style={{ fontFamily: _pwF, fontSize: 13, color: _pwH }}>/ month</span>
                  </div>
                  <div style={{ fontFamily: _pwF, fontSize: 11, color: _pwHD, marginTop: 2 }}>cancel anytime · no commitments</div>
                </div>
                <span style={{ fontFamily: _pwF, fontSize: 10, fontWeight: 700, letterSpacing: 1, color: accent, border: `1px solid ${accent}66`, borderRadius: 7, padding: '4px 8px' }}>BEST VALUE</span>
              </div>

              <PrimaryBtn accent={accent} onClick={onSubscribe}>Go unlimited →</PrimaryBtn>
              <div style={{ display: 'flex', gap: 9 }}>
                <button onClick={onBook} style={ghostPW()}>Talk to CS Tech</button>
                <button onClick={onExit} style={ghostPW()}>{blocked ? `Wait ${countdown}` : 'Back to tools'}</button>
              </div>
              <p style={{ margin: '2px 0 0', fontFamily: _pwF, fontSize: 10.5, color: _pwHD, textAlign: 'center', lineHeight: 1.4 }}>
                {authed ? 'Your free decisions reset every 24 hours.' : 'No account needed to try — your free decisions are tracked on this device.'}
              </p>
            </React.Fragment>
          )}
        </div>
      </div>
    </StageCard>);
}
function ghostPW() {
  return { flex: 1, cursor: 'pointer', padding: '12px', borderRadius: 11, fontFamily: _pwF, fontWeight: 600, fontSize: 12.5, color: _pwH, background: 'transparent', border: `1px solid ${_pwHR}` };
}

Object.assign(window, { UsagePill, PaywallScreen });
