/* Club FRESH — Quiet Status (forgiving, identity-framed, never gamified) */

/* circular season medallion */
function CFMedallion({ anchor = 'self', size = 104, progress = 1, earned = true, initial = 'S' }) {
  const { CF_PILLAR_HEX: PHEX } = window;
  const c = PHEX[anchor] || '#748d78';
  const r = size / 2 - 6, cx = size / 2, circ = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ filter: earned ? `drop-shadow(0 8px 18px ${c}66)` : 'none' }}>
      <defs>
        <radialGradient id={`mg-${anchor}-${size}`} cx="38%" cy="30%">
          <stop offset="0%" stopColor={lighten(c, 26)} />
          <stop offset="100%" stopColor={darken(c, 14)} />
        </radialGradient>
      </defs>
      {/* outer guilloche-ish ring */}
      <circle cx={cx} cy={cx} r={r} fill="none" stroke="rgba(20,16,12,0.08)" strokeWidth="5" />
      <circle cx={cx} cy={cx} r={r} fill="none" stroke={earned ? c : c} strokeWidth="5" strokeLinecap="round"
        strokeDasharray={circ} strokeDashoffset={circ * (1 - progress)} transform={`rotate(-90 ${cx} ${cx})`}
        opacity={earned ? 1 : 0.9} style={{ transition: 'stroke-dashoffset .9s cubic-bezier(.22,1,.36,1)' }} />
      {/* disc */}
      <circle cx={cx} cy={cx} r={r - 9} fill={earned ? `url(#mg-${anchor}-${size})` : 'rgba(20,16,12,0.04)'} />
      {/* notches */}
      {earned && [...Array(12)].map((_, i) => {
        const a = (i / 12) * Math.PI * 2;
        const ri = r - 4, ro = r - 1;
        return <line key={i} x1={cx + Math.cos(a) * ri} y1={cx + Math.sin(a) * ri} x2={cx + Math.cos(a) * ro} y2={cx + Math.sin(a) * ro} stroke="rgba(255,255,255,0.35)" strokeWidth="1.2" />;
      })}
      <text x={cx} y={cx} textAnchor="middle" dominantBaseline="central"
        fontFamily="'Editors Note', Georgia, serif" fontSize={size * 0.34} fontStyle="italic"
        fill={earned ? '#fff' : 'rgba(20,16,12,0.3)'}>{initial}</text>
    </svg>
  );
}

/* Weeks-in-Rhythm tier — typographic wordmark, never a badge */
function CFTierBlock({ weeks, tiers }) {
  const current = [...tiers].reverse().find(t => weeks >= t.at);
  const next = tiers.find(t => weeks < t.at);
  const prevAt = current ? current.at : 0;
  const pct = next ? Math.min(1, (weeks - prevAt) / (next.at - prevAt)) : 1;
  return (
    <div className="cf-card-dark" style={{ padding: '22px 22px 20px', overflow: 'hidden', position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <p style={{ margin: 0, fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)' }}>Weeks in rhythm</p>
          <h3 style={{ fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 30, color: '#fff', margin: '8px 0 0', lineHeight: 1 }}>{current ? current.name : 'Just landed'}</h3>
        </div>
        <span className="cf-num" style={{ fontSize: 50, color: '#fff', lineHeight: 0.85 }}>{weeks}</span>
      </div>
      {next && (
        <div style={{ marginTop: 18 }}>
          <div style={{ height: 5, borderRadius: 999, background: 'rgba(255,255,255,0.14)', overflow: 'hidden' }}>
            <div style={{ width: pct * 100 + '%', height: '100%', borderRadius: 999, background: 'var(--cf-accent)' }} />
          </div>
          <p style={{ margin: '10px 0 0', fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>
            {next.at - weeks} weeks to <span style={{ color: '#fff', fontStyle: 'italic', fontFamily: 'var(--cf-head)' }}>{next.name}</span>
          </p>
        </div>
      )}
      <p style={{ margin: '16px 0 0', fontSize: 11.5, color: 'rgba(255,255,255,0.4)' }}>It only ever grows. A week counts at three of five days.</p>
    </div>
  );
}

/* Season medallion card + IG share moment */
function CFMedallionCard({ season, weeks, neededWeeks = 8 }) {
  const { CF_Icon: Icon } = window;
  const earned = weeks >= neededWeeks;
  const initial = season.name[0];
  const openShare = () => window.cfModal.open(close => <ShareCard season={season} weeks={weeks} initial={initial} onClose={close} />);
  return (
    <div className="cf-card" style={{ padding: '20px 20px', display: 'flex', alignItems: 'center', gap: 18 }}>
      <CFMedallion anchor="self" size={92} progress={Math.min(1, weeks / neededWeeks)} earned={earned} initial={initial} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <p className="cf-eyebrow" style={{ marginBottom: 6 }}>Season medallion</p>
        <h3 className="cf-h3" style={{ fontSize: 20 }}>{season.name}</h3>
        {earned ? (
          <p style={{ margin: '6px 0 0', fontSize: 12.5, color: 'var(--ink-m)', lineHeight: 1.45 }}>Earned. Yours to keep, four a year.</p>
        ) : (
          <p style={{ margin: '6px 0 0', fontSize: 12.5, color: 'var(--ink-m)', lineHeight: 1.45 }}>{neededWeeks - weeks} more weeks in rhythm, then re-take the audit.</p>
        )}
        <button className="cf-reset cf-tap" onClick={openShare} style={{ marginTop: 12, height: 36, paddingInline: 15, borderRadius: 999, background: earned ? 'var(--cf-dark)' : 'transparent', color: earned ? '#fff' : 'var(--ink-h)', border: earned ? 'none' : '1.4px solid rgba(20,16,12,0.16)', fontSize: 12.5, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 7 }}>
          <Icon name="share" size={15} /> {earned ? 'Share' : 'Preview'}
        </button>
      </div>
    </div>
  );
}

function ShareCard({ season, weeks, initial, onClose }) {
  const { CF_Icon: Icon, CF_RHYTHM: R } = window;
  React.useEffect(() => { const el = document.querySelector('.cf-scroll'); if (el) el.scrollTop = 0; }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,16,12,0.6)', backdropFilter: 'blur(6px)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 26px' }}>
      <button className="cf-glass cf-icon-only" onClick={onClose} style={{ position: 'absolute', top: 52, right: 22 }}><Icon name="x" size={18} /></button>
      {/* shareable story card */}
      <div style={{ width: '100%', borderRadius: 26, overflow: 'hidden', background: 'linear-gradient(170deg, #211d18 0%, #141210 100%)', padding: '34px 26px 30px', textAlign: 'center', boxShadow: '0 30px 60px rgba(0,0,0,0.4)' }}>
        <p style={{ margin: 0, fontSize: 10.5, letterSpacing: '0.24em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>Club FRESH</p>
        <div style={{ display: 'flex', justifyContent: 'center', margin: '26px 0 6px' }}>
          <CFMedallion anchor="self" size={150} progress={1} earned initial={initial} />
        </div>
        <h2 style={{ fontFamily: 'var(--cf-head)', fontSize: 30, color: '#fff', margin: '20px 0 0', lineHeight: 1.05 }}>{season.name}</h2>
        <p style={{ fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 16, color: 'rgba(255,255,255,0.7)', margin: '8px 0 0' }}>{season.line}</p>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 28, marginTop: 26, paddingTop: 22, borderTop: '1px solid rgba(255,255,255,0.12)' }}>
          <div><div className="cf-num" style={{ fontSize: 28, color: '#fff' }}>{weeks}</div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>weeks in rhythm</div></div>
          <div><div className="cf-num" style={{ fontSize: 28, color: '#fff' }}>{R.fresh.headline}</div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>FRESH score</div></div>
        </div>
      </div>
      <button className="cf-reset cf-tap" onClick={onClose} style={{ marginTop: 20, height: 50, width: '100%', borderRadius: 999, background: '#fff', color: '#1a1714', fontSize: 14.5, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
        <Icon name="share" size={17} /> Share to story
      </button>
    </div>
  );
}

/* small identity stats row */
function CFStatPair({ children }) {
  return <div style={{ display: 'flex', gap: 12 }}>{children}</div>;
}
function CFIdentityStat({ icon, value, label, accent }) {
  const { CF_Icon: Icon } = window;
  return (
    <div className="cf-card" style={{ flex: 1, padding: '16px 16px' }}>
      <span style={{ width: 36, height: 36, borderRadius: 11, background: accent ? 'color-mix(in srgb, var(--cf-accent) 16%, #fff)' : 'rgba(20,16,12,0.05)', color: accent ? 'var(--cf-accent)' : 'var(--ink-h)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={18} />
      </span>
      <div className="cf-num" style={{ fontSize: 28, marginTop: 12 }}>{value}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-m)', marginTop: 2, lineHeight: 1.3 }}>{label}</div>
    </div>
  );
}

function lighten(hex, p) { return mix(hex, 255, p); }
function darken(hex, p) { return mix(hex, 0, p); }
function mix(hex, target, p) {
  const n = parseInt(hex.slice(1), 16);
  const r = Math.round(((n >> 16) & 255) + (target - ((n >> 16) & 255)) * p / 100);
  const g = Math.round(((n >> 8) & 255) + (target - ((n >> 8) & 255)) * p / 100);
  const b = Math.round((n & 255) + (target - (n & 255)) * p / 100);
  return '#' + (0x1000000 + r * 0x10000 + g * 0x100 + b).toString(16).slice(1);
}

Object.assign(window, { CFMedallion, CFTierBlock, CFMedallionCard, CFIdentityStat, CFStatPair });
