/* Club FRESH — §12 Min/Max, §13 Foundations, §14 The Well */

/* ============ "Watch your floor rise" graph ============ */
function CFFloorGraph({ floor }) {
  const { CF_PILLAR_HEX: PHEX } = window;
  const c = PHEX[floor.anchor];
  const W = 300, H = 120, n = floor.weeks.length;
  const all = [...floor.minLine, ...floor.maxLine, ...floor.done];
  const lo = Math.min(...all) - 3, hi = Math.max(...all) + 3;
  const x = i => (i / (n - 1)) * W;
  const y = v => H - ((v - lo) / (hi - lo)) * H;
  const path = arr => 'M ' + arr.map((v, i) => `${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(' L ');
  return (
    <div className="cf-card" style={{ padding: '20px 20px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <h3 className="cf-h3" style={{ fontSize: 19 }}>Watch your floor rise</h3>
          <p style={{ margin: '5px 0 0', fontSize: 12.5, color: 'var(--ink-m)' }}>Self · your minimum is what grows</p>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12.5, fontWeight: 600, color: c }}>floor {floor.minLine[0]} → {floor.minLine[floor.minLine.length - 1]}</span>
      </div>
      <svg width="100%" viewBox={`0 0 ${W} ${H + 6}`} style={{ marginTop: 16, overflow: 'visible' }}>
        <path d={path(floor.maxLine)} fill="none" stroke={c} strokeOpacity="0.28" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" />
        <path d={path(floor.minLine)} fill="none" stroke={c} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
        {floor.done.map((v, i) => <circle key={i} cx={x(i)} cy={y(v)} r="3.4" fill="#fff" stroke={c} strokeWidth="2" />)}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
        {floor.weeks.map(w => <span key={w} style={{ fontSize: 11, color: 'var(--ink-m)' }}>{w}</span>)}
      </div>
      <div style={{ display: 'flex', gap: 16, marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(20,16,12,0.07)' }}>
        <Legend c={c} label="Minimum (your floor)" solid />
        <Legend c={c} label="Maximum" />
      </div>
    </div>
  );
}
function Legend({ c, label, solid }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-b)' }}>
      <span style={{ width: 16, height: 0, borderTop: `${solid ? 3 : 2}px ${solid ? 'solid' : 'dashed'} ${c}`, opacity: solid ? 1 : 0.5 }} />{label}
    </span>
  );
}

/* ============ Monday setting ritual (bottom sheet) ============ */
function CFMinMaxSheet({ tracks, onClose }) {
  const { CF_Icon: Icon, CF_PILLARS: P, CF_PILLAR_HEX: PHEX } = window;
  const pillars = window.CF_PILLARS || [
    { key:'fitness', short:'Fitness' }, { key:'relationships', short:'Relationships' },
    { key:'environment', short:'Environment' }, { key:'self', short:'Self' }, { key:'hustle', short:'Hustle' }];
  const [state, setState] = React.useState(() => JSON.parse(JSON.stringify(tracks)));
  const bump = (k, field, d) => setState(s => ({ ...s, [k]: { ...s[k], [field]: Math.max(0, s[k][field] + d) } }));
  React.useEffect(() => { const el = document.querySelector('.cf-scroll'); if (el) el.scrollTop = 0; }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,16,12,0.45)' }} />
      <div style={{ position: 'relative', background: 'var(--canvas-top)', borderTopLeftRadius: 28, borderTopRightRadius: 28, padding: '12px 20px 28px', maxHeight: '88%', overflowY: 'auto', boxShadow: '0 -16px 40px rgba(20,16,12,0.2)' }} className="cf-scroll">
        <div style={{ width: 40, height: 5, borderRadius: 999, background: 'rgba(20,16,12,0.14)', margin: '0 auto 16px' }} />
        <p className="cf-eyebrow">60 seconds · Monday</p>
        <h2 className="cf-display" style={{ fontSize: 30, marginTop: 8 }}>Set this week</h2>
        <p style={{ fontSize: 13.5, color: 'var(--ink-b)', margin: '8px 0 0', lineHeight: 1.5 }}>The minimum is the promise. The maximum is the invitation. Tiny is allowed.</p>
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {pillars.map(p => {
            const tr = state[p.key]; if (!tr) return null;
            return (
              <div key={p.key} className="cf-card" style={{ padding: '15px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                  <span style={{ width: 9, height: 9, borderRadius: '50%', background: PHEX[p.key] }} />
                  <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink-h)' }}>{tr.name}</span>
                  <span style={{ fontSize: 11.5, color: 'var(--ink-m)' }}>{p.short}</span>
                </div>
                <div style={{ display: 'flex', gap: 10, marginTop: 13 }}>
                  <Stepper label="Min" value={tr.min} unit={tr.unit} accent={PHEX[p.key]} onDec={() => bump(p.key, 'min', -1)} onInc={() => bump(p.key, 'min', 1)} />
                  <Stepper label="Max" value={tr.max} unit={tr.unit} onDec={() => bump(p.key, 'max', -1)} onInc={() => bump(p.key, 'max', 1)} />
                </div>
              </div>
            );
          })}
        </div>
        <button className="cf-reset cf-tap" onClick={() => onClose(state)} style={{ width: '100%', height: 54, borderRadius: 999, marginTop: 18, background: 'var(--cf-dark)', color: '#fff', fontSize: 15, fontWeight: 600 }}>Lock in my week</button>
      </div>
    </div>
  );
}
function Stepper({ label, value, unit, accent, onDec, onInc }) {
  const { CF_Icon: Icon } = window;
  return (
    <div style={{ flex: 1, borderRadius: 14, padding: '10px 12px', background: accent ? `color-mix(in srgb, ${accent} 12%, #fff)` : 'rgba(20,16,12,0.04)', border: accent ? `1px solid color-mix(in srgb, ${accent} 26%, transparent)` : '1px solid rgba(20,16,12,0.07)' }}>
      <div style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-m)' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
        <button className="cf-reset" onClick={onDec} style={{ width: 26, height: 26, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(20,16,12,0.12)', color: 'var(--ink-h)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>–</button>
        <span className="cf-num" style={{ fontSize: 19 }}>{value}<span style={{ fontSize: 11, color: 'var(--ink-m)', fontWeight: 400 }}>{unit ? ' ' + unit : ''}</span></span>
        <button className="cf-reset" onClick={onInc} style={{ width: 26, height: 26, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(20,16,12,0.12)', color: 'var(--ink-h)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>+</button>
      </div>
    </div>
  );
}

/* ============ The Well ============ */
function CFWell({ back }) {
  const { CF_Icon: Icon, CF_WELL: W, CF_PILLARS: P, CF_PILLAR_HEX: PHEX, CF_PILLAR_ICON: PI } = window;
  const [rail, setRail] = React.useState('lift');
  const pmap = Object.fromEntries(P.map(p => [p.key, p]));
  const play = (title, anchor) => window.cfModal.open(close => <CFWellPlayer title={title} anchor={anchor} rail={rail} onClose={close} />);
  return (
    <div className="cf-fade-in">
      <div className="cf-pad" style={{ paddingTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button className="cf-glass cf-icon-only" onClick={back}><Icon name="arrowL" size={19} /></button>
        <window.CFFreshMark size={24} />
      </div>
      <div className="cf-pad" style={{ marginTop: 12 }}>
        <p className="cf-eyebrow">With Tracy</p>
        <h1 className="cf-display" style={{ fontSize: 46, marginTop: 8 }}>The Well</h1>
        <p style={{ fontSize: 14, color: 'var(--ink-b)', margin: '10px 0 0', lineHeight: 1.5, maxWidth: '32ch' }}>Her voice for the moment you are in. A well, not a curriculum. Nothing to finish.</p>
      </div>

      {/* state rails */}
      <div className="cf-pad" style={{ marginTop: 18 }}>
        <div style={{ display: 'flex', gap: 6, background: 'rgba(20,16,12,0.05)', borderRadius: 999, padding: 4 }}>
          {[['lift', 'Lift me'], ['push', 'Push me']].map(([k, l]) => (
            <button key={k} className="cf-reset" onClick={() => setRail(k)} style={{ flex: 1, height: 40, borderRadius: 999, fontSize: 13.5, fontWeight: 600, color: rail === k ? 'var(--ink-h)' : 'var(--ink-m)', background: rail === k ? '#fff' : 'transparent', boxShadow: rail === k ? '0 2px 8px rgba(20,16,12,0.1)' : 'none' }}>{l}</button>
          ))}
        </div>
        <p style={{ fontSize: 12, color: 'var(--ink-m)', margin: '10px 4px 0' }}>{rail === 'lift' ? 'For the depleted, doubting days. Her warmest register.' : 'For the days you want to be stretched. The coach voice.'}</p>
      </div>

      {/* by anchor */}
      <div className="cf-pad" style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {W.byAnchor.map(a => (
          <button key={a.anchor} className="cf-reset cf-tap" onClick={() => play(a[rail], a.anchor)} style={{ width: '100%' }}>
            <div className="cf-card" style={{ padding: '14px 15px', display: 'flex', alignItems: 'center', gap: 13, textAlign: 'left' }}>
              <span style={{ width: 46, height: 46, borderRadius: 14, background: PHEX[a.anchor], color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={PI[a.anchor]} size={20} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 9.5, letterSpacing: '0.13em', textTransform: 'uppercase', color: PHEX[a.anchor], fontWeight: 600 }}>{pmap[a.anchor].short}</div>
                <div style={{ fontFamily: 'var(--cf-head)', fontSize: 16.5, color: 'var(--ink-h)', marginTop: 2, lineHeight: 1.15 }}>{a[rail]}</div>
              </div>
              <span style={{ width: 36, height: 36, borderRadius: '50%', background: 'color-mix(in srgb, var(--cf-accent) 14%, #fff)', color: 'var(--ink-h)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="play" size={15} fill="currentColor" /></span>
            </div>
          </button>
        ))}
      </div>

      {/* by moment */}
      <div className="cf-pad" style={{ marginTop: 22, display: 'flex', alignItems: 'center', gap: 12 }}>
        <h3 className="cf-h3" style={{ fontSize: 20 }}>By moment</h3>
        <span style={{ flex: 1, height: 1, background: 'rgba(20,16,12,0.1)' }} />
      </div>
      <div className="cf-pad" style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 9 }}>
        {W.moments.map((m, i) => (
          <button key={i} className="cf-reset cf-tap" onClick={() => play(m.t, m.anchor)} style={{ width: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: '#fff', borderRadius: 14, boxShadow: '0 1px 8px rgba(20,16,12,0.04)' }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: PHEX[m.anchor] }} />
              <span style={{ flex: 1, textAlign: 'left', fontSize: 14, color: 'var(--ink-h)', fontWeight: 500 }}>{m.t}</span>
              <span style={{ fontSize: 12, color: 'var(--ink-m)' }}>{m.len}</span>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function CFWellPlayer({ title, anchor, rail, onClose }) {
  const { CF_Icon: Icon, CF_PILLAR_HEX: PHEX } = window;
  const c = PHEX[anchor] || '#748d78';
  const [playing, setPlaying] = React.useState(true);
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 60, background: '#0c0a08', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, position: 'relative', background: `radial-gradient(75% 55% at 50% 38%, ${c}66, #0c0a08 72%)`, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 28 }}>
        <div style={{ position: 'absolute', top: 50, left: 22, right: 22, display: 'flex', justifyContent: 'space-between' }}>
          <button className="cf-glass cf-icon-only" onClick={onClose}><Icon name="chevD" size={20} /></button>
          <button className="cf-glass cf-icon-only"><Icon name="heart" size={18} /></button>
        </div>
        {/* pulsing orb */}
        <div style={{ width: 168, height: 168, borderRadius: '50%', background: `linear-gradient(150deg, ${c}, color-mix(in srgb, ${c} 55%, #000))`, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 0 60px ${c}77`, animation: 'cfPulse 3.4s ease-in-out infinite' }}>
          <window.CFFreshMark size={40} light />
        </div>
        <div style={{ textAlign: 'center', padding: '0 32px' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: c, fontWeight: 600 }}>{rail === 'lift' ? 'Lift me' : 'Push me'} · with Tracy</div>
          <h3 style={{ fontFamily: 'var(--cf-head)', fontSize: 25, color: '#fff', margin: '10px 0 0', lineHeight: 1.2 }}>{title}</h3>
        </div>
      </div>
      <div style={{ padding: '20px 26px 36px', background: '#0c0a08' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>1:12</span>
          <div style={{ flex: 1, height: 4, borderRadius: 999, background: 'rgba(255,255,255,0.18)' }}><div style={{ width: '32%', height: '100%', borderRadius: 999, background: c }} /></div>
          <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>4:05</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 30, marginTop: 20 }}>
          <Icon name="arrowL" size={22} style={{ color: 'rgba(255,255,255,0.55)' }} />
          <button className="cf-reset cf-tap" onClick={() => setPlaying(p => !p)} style={{ width: 70, height: 70, borderRadius: '50%', background: '#fff', color: '#1a1714', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={playing ? 'pause' : 'play'} size={28} fill="#1a1714" />
          </button>
          <Icon name="arrowL" size={22} style={{ color: 'rgba(255,255,255,0.55)', transform: 'scaleX(-1)' }} />
        </div>
      </div>
    </div>
  );
}

/* ============ FRESH Foundations ============ */
function CFFoundations({ back, go }) {
  const { CF_Icon: Icon, CF_FOUNDATIONS: F, CF_PILLARS: P, CF_PILLAR_HEX: PHEX, CF_PILLAR_ICON: PI } = window;
  const pmap = Object.fromEntries(P.map(p => [p.key, p]));
  return (
    <div className="cf-fade-in">
      <div className="cf-pad" style={{ paddingTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button className="cf-glass cf-icon-only" onClick={back}><Icon name="arrowL" size={19} /></button>
        <window.CFFreshMark size={24} />
      </div>
      <div className="cf-pad" style={{ marginTop: 12 }}>
        <p className="cf-eyebrow">Start here</p>
        <h1 className="cf-display" style={{ fontSize: 42, marginTop: 8 }}>The FRESH Framework</h1>
      </div>

      {/* orientation */}
      <div className="cf-pad" style={{ marginTop: 16 }}>
        <div className="cf-card-dark" style={{ padding: '22px 22px' }}>
          <span style={{ fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>Orientation · {F.orientation.len}</span>
          <h3 className="cf-h3" style={{ color: '#fff', marginTop: 10 }}>{F.orientation.t}</h3>
          <p style={{ fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 17, color: 'rgba(255,255,255,0.85)', margin: '12px 0 0', lineHeight: 1.4 }}>{F.orientation.line}</p>
          <button className="cf-reset cf-tap" style={{ marginTop: 18, height: 44, paddingInline: 20, borderRadius: 999, background: '#fff', color: '#1a1714', fontSize: 14, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <Icon name="play" size={15} fill="#1a1714" /> Watch with Tracy
          </button>
        </div>
      </div>

      {/* primers */}
      <div className="cf-pad" style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
        <h3 className="cf-h3" style={{ fontSize: 20 }}>The five anchors</h3>
        <span style={{ flex: 1, height: 1, background: 'rgba(20,16,12,0.1)' }} />
      </div>
      <div className="cf-pad" style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {F.primers.map((p, i) => (
          <div key={i} className="cf-card" style={{ padding: '15px 16px', display: 'flex', gap: 13, alignItems: 'flex-start' }}>
            <span style={{ width: 42, height: 42, borderRadius: 13, background: PHEX[p.anchor], color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={PI[p.anchor]} size={20} /></span>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontFamily: 'var(--cf-head)', fontSize: 17, color: 'var(--ink-h)' }}>{p.t}</span>
                <span style={{ fontSize: 11.5, color: 'var(--ink-m)' }}>{p.len}</span>
              </div>
              <p style={{ margin: '5px 0 0', fontSize: 12.5, color: 'var(--ink-m)', lineHeight: 1.4 }}>{p.why}</p>
              <p style={{ margin: '7px 0 0', fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 13.5, color: PHEX[p.anchor] }}>“{p.line}”</p>
            </div>
          </div>
        ))}
      </div>

      {/* reset upsell */}
      <div className="cf-pad" style={{ marginTop: 18 }}>
        <div style={{ borderRadius: 'var(--cf-radius)', padding: '20px 20px', background: 'linear-gradient(140deg, #7b623c, #c9a46c)', boxShadow: '0 14px 30px rgba(123,98,60,0.3)' }}>
          <span style={{ fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.8)' }}>The deep end</span>
          <h3 className="cf-h3" style={{ color: '#fff', marginTop: 10, fontSize: 21 }}>{F.reset.t}</h3>
          <p style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.9)', margin: '8px 0 0', lineHeight: 1.5 }}>{F.reset.line}</p>
          <div style={{ marginTop: 16, display: 'inline-flex', alignItems: 'center', gap: 8, height: 42, paddingInline: 18, borderRadius: 999, background: 'rgba(255,255,255,0.96)', color: '#7b623c', fontSize: 13.5, fontWeight: 600 }}>
            Explore the Reset <Icon name="arrowUR" size={15} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CFFloorGraph, CFMinMaxSheet, CFWell, CFWellPlayer, CFFoundations });
