/* Club FRESH — Today, rebuilt around the Daily Five sweep */
function CFToday({ lens, freedom, freedomDay, sweep, onMark, tracks, onSetWeek, dailyAudio, onAudio,
  deckRevealed, onRevealDeck, deckCard, avatar, go }) {
  const { CF_Icon: Icon, CF_Monogram: Mono, CF_THREAD: THREAD, CF_PILLARS: PILLARS } = window;
  const marked = PILLARS.filter(p => sweep[p.key] && sweep[p.key] !== 'none').length;
  const swept = marked > 0;
  const moment = freedom ? freedomDay : lens;
  const dowName = new Date().toLocaleDateString('en-AU', { weekday: 'long' });
  const hour = new Date().getHours();
  const greet = hour < 12 ? 'Morning' : hour < 17 ? 'Afternoon' : 'Evening';

  return (
    <div className="cf-fade-in">
      {/* header */}
      <div className="cf-pad" style={{ paddingTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <p className="cf-eyebrow" style={{ marginBottom: 4 }}>{dowName} · Steady Season</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <FreshMark size={26} />
            <span style={{ fontFamily: 'var(--cf-head)', fontSize: 19, color: 'var(--ink-h)' }}>Club FRESH</span>
          </div>
        </div>
        <button className="cf-reset cf-tap" onClick={() => go('settings')}>
          <Mono name={avatar.name} pillar="self" size={42} />
        </button>
      </div>

      {/* greeting */}
      <div className="cf-pad" style={{ marginTop: 20 }}>
        <h1 className="cf-display" style={{ fontSize: 40 }}>{greet}, <em style={{ fontStyle: 'italic' }}>lovely</em></h1>
      </div>

      {/* Tracy lens / freedom card */}
      <div className="cf-pad" style={{ marginTop: 16 }}>
        <div style={{ padding: '22px 22px 20px', position: 'relative', overflow: 'hidden', borderRadius: 'var(--cf-radius)', color: '#fff', background: `linear-gradient(158deg, color-mix(in srgb, ${moment.color || '#1a1714'} 56%, #241a12) 0%, color-mix(in srgb, ${moment.color || '#1a1714'} 26%, #1a130d) 100%)`, boxShadow: `0 20px 46px color-mix(in srgb, ${moment.color || '#1a1714'} 28%, transparent)` }}>
          <span style={{ position: 'absolute', top: 4, right: 18, fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 100, lineHeight: 1, color: 'rgba(255,255,255,0.07)' }}>”</span>
          <p style={{ margin: 0, fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)' }}>
            {freedom ? 'Your freedom day' : `Today Tracy's looking at ${lens.name}`}
          </p>
          <p style={{ fontFamily: 'var(--cf-head)', fontSize: 23, lineHeight: 1.34, color: '#fff', margin: '12px 0 0', position: 'relative', maxWidth: '25ch' }}>{moment.line}</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '18px 0 0' }}>
            <span style={{ width: 28, height: 1, background: 'rgba(255,255,255,0.4)' }} />
            <span className="cf-script" style={{ fontSize: 25, color: '#fff' }}>Tracy</span>
          </div>
          <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid rgba(255,255,255,0.13)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <span style={{ width: 34, height: 34, borderRadius: 11, background: 'rgba(255,255,255,0.18)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name={freedom ? 'heart' : window.CF_PILLAR_ICON[lens.anchor]} size={18} />
            </span>
            <div>
              <p style={{ margin: 0, fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>{freedom ? 'Your invitation' : 'Your five minutes'}</p>
              <p style={{ margin: '5px 0 0', fontSize: 14.5, lineHeight: 1.5, color: 'rgba(255,255,255,0.92)' }}>{moment.action}</p>
            </div>
          </div>
          {/* daily audio */}
          {dailyAudio && (
            <button className="cf-reset cf-tap" onClick={onAudio} style={{ width: '100%', marginTop: 16, display: 'flex', alignItems: 'center', gap: 11, background: 'rgba(255,255,255,0.12)', borderRadius: 14, padding: '11px 13px', textAlign: 'left' }}>
              <span style={{ width: 36, height: 36, borderRadius: '50%', background: '#fff', color: '#1a1714', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="play" size={15} fill="#1a1714" /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)' }}>From the Well</div>
                <div style={{ fontFamily: 'var(--cf-head)', fontSize: 15, color: '#fff', marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{dailyAudio}</div>
              </div>
              <Icon name="chevR" size={16} style={{ color: 'rgba(255,255,255,0.6)', flexShrink: 0 }} />
            </button>
          )}
        </div>
      </div>

      {/* The Daily Five */}
      <div className="cf-pad" style={{ marginTop: 14 }}>
        <DailyFive sweep={sweep} onMark={onMark} tracks={tracks} onSetWeek={onSetWeek} freedom={freedom} swept={swept} marked={marked} lensAnchor={freedom ? null : lens.anchor} />
      </div>

      {/* deck draw */}
      {!freedom && (
        <div className="cf-pad" style={{ marginTop: 14 }}>
          <DeckDraw revealed={deckRevealed} onReveal={onRevealDeck} card={deckCard} />
        </div>
      )}

      {/* thread preview */}
      <div className="cf-pad" style={{ marginTop: 14 }}>
        <button className="cf-reset cf-tap" style={{ width: '100%' }} onClick={() => go('club')}>
          <div className="cf-card" style={{ padding: '16px 18px', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ display: 'flex' }}>
              {[window.CF_LEAD, ...window.CF_PEOPLE.slice(0, 2)].map((p, i) => (
                <span key={i} style={{ marginLeft: i ? -9 : 0, borderRadius: '50%', boxShadow: '0 0 0 2px #fff' }}><Mono name={p.name} pillar={p.anchor} size={28} /></span>
              ))}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-h)' }}>{THREAD.inToday} in the rhythm today</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-m)' }}>Join today's thread</div>
            </div>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#5fb07a', boxShadow: '0 0 0 4px rgba(95,176,122,0.18)' }} />
          </div>
        </button>
      </div>
    </div>
  );
}

/* ---------- The Daily Five (core component) ---------- */
function DailyFive({ sweep, onMark, tracks, onSetWeek, freedom, swept, marked, lensAnchor }) {
  const { CF_Icon: Icon, CF_PILLARS: PILLARS } = window;
  return (
    <div className="cf-card" style={{ padding: '20px 18px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <h3 className="cf-h3" style={{ fontSize: 20 }}>{freedom ? 'Resting today' : 'Today’s FRESH sweep'}</h3>
          <p style={{ margin: '4px 0 0', fontSize: 12.5, color: 'var(--ink-m)' }}>{freedom ? 'Chips rest on your freedom day.' : 'Mark what’s true. Two with intention is a good day.'}</p>
        </div>
        {!freedom && (
          <button className="cf-reset cf-tap" onClick={onSetWeek} style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-h)', display: 'inline-flex', alignItems: 'center', gap: 5, height: 32, paddingInline: 11, borderRadius: 999, border: '1.4px solid rgba(20,16,12,0.16)' }}><Icon name="sliders" size={13} /> Set</button>
        )}
      </div>

      <div style={{ display: 'flex', gap: 9, marginTop: 18, justifyContent: 'space-between' }}>
        {PILLARS.map(p => (
          <Chip key={p.key} p={p} state={freedom ? 'rest' : (sweep[p.key] || 'none')} track={tracks[p.key]} onMark={onMark} lens={p.key === lensAnchor} />
        ))}
      </div>

      {!freedom && (
        <div style={{ marginTop: 18 }}>
          {swept ? (
            <div style={{ height: 46, borderRadius: 999, background: 'rgba(95,176,122,0.14)', color: '#3f7a55', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, fontSize: 14, fontWeight: 600 }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', background: '#5fb07a', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={14} sw={2.6} /></span>
              In the rhythm today · {marked} of 5 marked
            </div>
          ) : (
            <p style={{ margin: 0, textAlign: 'center', fontSize: 12.5, color: 'var(--ink-m)' }}>Tap to keep a minimum · hold for a maximum</p>
          )}
        </div>
      )}
    </div>
  );
}

function Chip({ p, state, track, onMark, lens }) {
  const { CF_Icon: Icon, CF_PILLAR_HEX: PHEX } = window;
  const color = PHEX[p.key];
  const holdRef = React.useRef(null);
  const heldRef = React.useRef(false);
  const rest = state === 'rest';

  const start = (e) => {
    if (rest) return;
    heldRef.current = false;
    holdRef.current = setTimeout(() => { heldRef.current = true; onMark(p.key, 'max'); }, 420);
  };
  const end = () => {
    if (rest) return;
    clearTimeout(holdRef.current);
    if (heldRef.current) return;
    onMark(p.key, state === 'none' ? 'min' : 'none');
  };
  const cancel = () => clearTimeout(holdRef.current);

  const filled = state === 'min' || state === 'max';
  const dark = p.key === 'hustle';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flex: 1, userSelect: 'none' }}>
      <button className="cf-reset" onPointerDown={start} onPointerUp={end} onPointerLeave={cancel}
        style={{
          position: 'relative', width: '100%', aspectRatio: '1', maxWidth: 54, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--cf-head)', fontSize: 22,
          background: filled ? color : (rest ? 'rgba(20,16,12,0.04)' : `color-mix(in srgb, ${color} 9%, #fff)`),
          color: filled ? (dark ? '#fff' : '#fff') : (rest ? 'rgba(20,16,12,0.25)' : color),
          border: filled ? 'none' : `1.5px ${rest ? 'solid' : 'dashed'} ${rest ? 'rgba(20,16,12,0.12)' : `color-mix(in srgb, ${color} 45%, transparent)`}`,
          boxShadow: lens ? `0 0 0 3px #fff, 0 0 0 5px color-mix(in srgb, ${color} 55%, transparent)` : (filled ? `0 6px 16px ${color}44` : 'none'),
          transition: 'background .2s, transform .12s, box-shadow .2s', touchAction: 'none', cursor: 'pointer',
        }}>
        {p.letter}
        {state === 'max' && (
          <span style={{ position: 'absolute', top: -4, right: -4, width: 20, height: 20, borderRadius: '50%', background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 1px 5px rgba(20,16,12,0.22)' }}>
            <Icon name="spark" size={12} fill={color} />
          </span>
        )}
      </button>
      <span style={{ fontSize: 10, color: filled ? 'var(--ink-h)' : 'var(--ink-m)', fontWeight: filled ? 600 : 400 }}>{state === 'max' ? 'max' : state === 'min' ? 'min' : (rest ? '·' : track ? track.min : '')}</span>
    </div>
  );
}

/* face-down deck card that flips to reveal */
function DeckDraw({ revealed, onReveal, card }) {
  const { CF_Icon: Icon, CF_PILLAR_HEX: PHEX } = window;
  const c = card || { anchor:'self', prompt:'' };
  const accent = PHEX[c.anchor] || '#748d78';
  return (
    <button className="cf-reset" style={{ width: '100%', perspective: 1200 }} onClick={() => !revealed && onReveal()}>
      <div style={{ position: 'relative', height: 150, transformStyle: 'preserve-3d', transition: 'transform .7s cubic-bezier(.22,1,.36,1)', transform: revealed ? 'rotateY(180deg)' : 'none' }}>
        <div style={{ position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden', borderRadius: 'var(--cf-radius)', background: 'linear-gradient(150deg, #f1e9da, #e3d6c1)', border: '1px solid rgba(184,145,90,0.3)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, boxShadow: '0 10px 26px rgba(20,16,12,0.12)', opacity: revealed ? 0 : 1, transition: 'opacity .25s .25s' }}>
          <FreshMark size={30} />
          <span style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--gold)' }}>Tap to draw today's card</span>
        </div>
        <div style={{ position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden', transform: 'rotateY(180deg)', borderRadius: 'var(--cf-radius)', background: `linear-gradient(155deg, color-mix(in srgb, ${accent} 82%, #2a1d12), color-mix(in srgb, ${accent} 52%, #160f09))`, padding: '20px 22px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', boxShadow: `0 14px 34px color-mix(in srgb, ${accent} 36%, rgba(20,16,12,0.3))`, opacity: revealed ? 1 : 0, transition: 'opacity .25s .25s' }}>
          <span style={{ fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)' }}>The FRESH Deck</span>
          <p style={{ margin: 0, fontFamily: 'var(--cf-head)', fontSize: 21, lineHeight: 1.25, color: '#fff' }}>{c.prompt}</p>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'rgba(255,255,255,0.85)' }}>Filed in your deck · sit with it <Icon name="arrowUR" size={14} /></span>
        </div>
      </div>
    </button>
  );
}

function FreshMark({ size = 28, light }) {
  const cols = ['#c07152', '#d7ad82', '#c69b8b', '#748d78', light ? '#f6f4f1' : '#1a1714'];
  const d = size / 3.4;
  return (
    <span style={{ display: 'inline-grid', gridTemplateColumns: `repeat(3, ${d}px)`, gap: size * 0.07, width: size, justifyContent: 'center' }}>
      {cols.map((c, i) => <span key={i} style={{ width: d, height: d, borderRadius: '50%', background: c }} />)}
      <span style={{ width: d, height: d, borderRadius: '50%', background: '#c07152' }} />
      <span style={{ width: d, height: d, borderRadius: '50%', background: '#d7ad82' }} />
    </span>
  );
}

Object.assign(window, { CFToday, CFFreshMark: FreshMark });
