// Main App
const { useState, useEffect, useRef } = React;

const STORAGE_KEY = 'snatch_state_v1';
function loadState() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; } catch { return {}; }
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {}
}

const SUGGESTIONS = [
  "I've got 30 min and no gear",
  "Light day, my legs are toast",
  "Crush my core",
  "Full-body HIIT, let's go",
  "Back + biceps, 45 min, dumbbells",
  "Something for after a long run",
];

const SAMPLE_HISTORY = [
  { id: 'h1', title: 'THE GRINDER', date: 'Apr 17', duration: '32 MIN', intensity: 'HARD', focus: 'Conditioning', completed: true },
  { id: 'h2', title: 'IRON HOUR', date: 'Apr 15', duration: '60 MIN', intensity: 'BRUTAL', focus: 'Strength', completed: true },
  { id: 'h3', title: 'SWEAT EQUITY', date: 'Apr 13', duration: '25 MIN', intensity: 'MEDIUM', focus: 'Cardio', completed: true },
  { id: 'h4', title: 'LUNGS & LEGS', date: 'Apr 10', duration: '40 MIN', intensity: 'HARD', focus: 'Legs', completed: false },
  { id: 'h5', title: 'CHEST DAY', date: 'Apr 8', duration: '45 MIN', intensity: 'HARD', focus: 'Push', completed: true },
];

// ===== MAIN APP =====
function App() {
  const [view, setView] = useState('home');
  const [variant, setVariant] = useState(window.TWEAKS?.variant || 'poster');
  const [showTicker, setShowTicker] = useState(window.TWEAKS?.ticker !== false);
  const persisted = loadState();
  const [messages, setMessages] = useState(persisted.messages || []);
  const [saved, setSaved] = useState(persisted.saved || []);
  const [activeWod, setActiveWod] = useState(persisted.activeWod || null);
  const [loading, setLoading] = useState(false);
  const [input, setInput] = useState('');

  useEffect(() => {
    const onTweak = (e) => {
      setVariant(e.detail.variant || 'poster');
      setShowTicker(e.detail.ticker !== false);
    };
    window.addEventListener('tweaks-changed', onTweak);
    return () => window.removeEventListener('tweaks-changed', onTweak);
  }, []);

  useEffect(() => {
    saveState({ messages, saved, activeWod });
  }, [messages, saved, activeWod]);

  const sendMessage = async (text) => {
    if (!text.trim() || loading) return;
    const newMessages = [...messages, { role: 'user', content: text }];
    setMessages(newMessages);
    setInput('');
    setLoading(true);
    setView('chat');

    try {
      const reply = await window.WODLib.callCoach(newMessages);
      const parsed = window.WODLib.parseWodResponse(reply);
      setMessages(m => [...m, { role: 'assistant', content: parsed.intro || "Here you go.", wod: parsed.wod, outro: parsed.outro }]);
      if (parsed.wod) setActiveWod({ ...parsed.wod, id: 'w_' + Date.now(), generatedAt: Date.now() });
    } catch (err) {
      // worker unreachable or returned an error
    } finally {
      setLoading(false);
    }
  };

  const toggleSave = (wod) => {
    if (!wod) return;
    const exists = saved.find(s => s.id === wod.id);
    if (exists) setSaved(saved.filter(s => s.id !== wod.id));
    else setSaved([{ ...wod, savedAt: Date.now() }, ...saved]);
  };

  const isSaved = (wod) => wod && saved.some(s => s.id === wod.id);

  return (
    <div style={{ minHeight: '100vh', background: '#0a0a0a' }}>
      <Nav view={view} setView={setView} variant={variant} />
      {view === 'home' && <Home setView={setView} onSuggest={sendMessage} onSend={(txt) => { sendMessage(txt); setView('chat'); }} variant={variant} showTicker={showTicker} />}
      {view === 'chat' && <ChatView messages={messages} loading={loading} input={input} setInput={setInput} onSend={sendMessage} variant={variant} onSave={toggleSave} isSaved={isSaved} onReset={() => { setMessages([]); setActiveWod(null); }} />}
      {view === 'saved' && <SavedView saved={saved} onOpen={(w) => { setActiveWod(w); setView('chat'); }} onRemove={toggleSave} variant={variant} />}
      {view === 'history' && <HistoryView variant={variant} />}
    </div>
  );
}

// ===== RANDOM WOD =====
const RANDOM_WODS = [
  "Give me a random full-body WOD, surprise me!",
  "Random WOD — any equipment, any duration, go!",
  "Pick any workout for me today, coach's choice.",
  "Surprise me with something brutal today.",
  "Random WOD, I trust you coach.",
];

// ===== HOME =====
function Home({ setView, onSuggest, onSend, variant, showTicker }) {
  const [heroInput, setHeroInput] = useState('');

  const handleHeroSend = () => {
    if (!heroInput.trim()) return;
    onSend(heroInput);
  };

  const handleRandom = () => {
    const pick = RANDOM_WODS[Math.floor(Math.random() * RANDOM_WODS.length)];
    onSend(pick);
  };

  return (
    <div>
      <section style={{ padding: '60px 32px 80px', maxWidth: 1400, margin: '0 auto', position: 'relative' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 60, alignItems: 'center' }}>
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)', marginBottom: 20 }}>● WORKOUT OF THE DAY</div>
            <RotatingHype />
            <p style={{ fontSize: 17, lineHeight: 1.5, color: 'rgba(255,255,255,0.65)', maxWidth: 520, marginTop: 20 }}>
              Tell your coach how you feel, what you've got, and what you need. Get a workout built for today — not last week, not someone else.
            </p>
            <form onSubmit={(e) => { e.preventDefault(); handleHeroSend(); }} style={{ display: 'flex', gap: 0, marginTop: 28, maxWidth: 520 }}>
              <input
                value={heroInput}
                onChange={e => setHeroInput(e.target.value)}
                placeholder="How's your body feeling today?"
                style={{
                  flex: 1, background: 'rgba(255,255,255,0.07)', border: '1.5px solid rgba(255,255,255,0.2)',
                  borderRight: 0, color: '#fff', fontFamily: 'Archivo', fontSize: 15, padding: '16px 20px',
                  outline: 'none', borderRadius: '2px 0 0 2px',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.2)'}
              />
              <button type="submit" className="btn btn-primary pulse" style={{ borderRadius: '0 2px 2px 0', whiteSpace: 'nowrap' }}>
                Talk to coach →
              </button>
            </form>
            <div style={{ marginTop: 14 }}>
              <button className="btn btn-ghost" onClick={handleRandom} style={{ fontSize: 13 }}>
                Random WOD
              </button>
            </div>
          </div>

          <div style={{ position: 'relative', height: 520 }}>
            <HeroVisual variant={variant} />
          </div>
        </div>
      </section>

      {showTicker && <Ticker variant={variant} items={['DISCIPLINE', 'SWEAT', 'EVERY DAMN DAY', 'NO EXCUSES', 'SHOW UP', 'EARN IT', 'LOCK IN', 'OUTWORK']} />}

      <section style={{ padding: '60px 32px 120px', maxWidth: 1400, margin: '0 auto' }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)', marginBottom: 8 }}>HOW IT WORKS</div>
        <div className="display" style={{ fontSize: 'clamp(40px, 6vw, 80px)', marginBottom: 48 }}>Three steps.<br />Zero excuses.</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          <Step num="01" title="Say what's up" body="Tell coach how you feel, what you've got, what hurts. Just type." />
          <Step num="02" title="Get your WOD" body="A workout designed around your day — warmup, work, cooldown." />
          <Step num="03" title="Go crush it" body="Save it. Beat it. Log it. Come back tomorrow and do it again." />
        </div>
      </section>
    </div>
  );
}

function HeroVisual({ variant }) {
  if (variant === 'neon') {
    return (
      <div style={{
        position: 'relative', height: '100%',
        background: 'radial-gradient(circle at 60% 40%, rgba(255,45,45,0.15), transparent 60%), #0a0a0a',
        border: '1px solid rgba(255,255,255,0.08)', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', top: 24, left: 24, right: 24, display: 'flex', justifyContent: 'space-between' }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', color: 'var(--accent)' }}>● LIVE · HR 142</span>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', opacity: 0.5 }}>SESSION 047</span>
        </div>
        <svg viewBox="0 0 500 400" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          <defs>
            <linearGradient id="hg" x1="0" x2="1">
              <stop offset="0" stopColor="var(--accent)" stopOpacity="0.1" />
              <stop offset="1" stopColor="var(--accent)" stopOpacity="1" />
            </linearGradient>
          </defs>
          {[0,1,2,3,4,5,6,7,8].map(i => (
            <line key={i} x1="0" y1={50 + i * 40} x2="500" y2={50 + i * 40} stroke="rgba(255,255,255,0.04)" strokeWidth="1" />
          ))}
          <path d="M 0 250 L 60 250 L 70 230 L 80 270 L 90 250 L 150 250 L 160 100 L 175 400 L 185 200 L 195 280 L 250 250 L 260 250 L 275 240 L 290 260 L 340 250 L 355 120 L 370 360 L 385 220 L 400 260 L 500 250"
            fill="none" stroke="url(#hg)" strokeWidth="2.5" />
        </svg>
        <div style={{ position: 'absolute', bottom: 24, left: 24, right: 24 }}>
          <div className="display" style={{ fontSize: 80, color: '#fff', lineHeight: 0.85 }}>142<span style={{ fontSize: 24, marginLeft: 10, color: 'var(--accent)' }}>BPM</span></div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', opacity: 0.5, marginTop: 8 }}>REAL ATHLETES. REAL DATA. REAL GAINS.</div>
        </div>
      </div>
    );
  }
  return (
    <div style={{
      position: 'relative', height: '100%',
      background: 'linear-gradient(135deg, var(--accent), #1a1a1a 70%)',
      overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: 28, left: 28 }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.25em', color: '#fff', opacity: 0.9 }}>● TODAY'S EDITION</span>
      </div>
      <div style={{ position: 'absolute', bottom: 40, left: 32, right: 32 }}>
        <div className="display" style={{ fontSize: 96, color: '#fff', lineHeight: 0.85 }}>TRAIN<br />LIKE YOU<br /><span style={{ color: 'rgba(255,255,255,0.4)', WebkitTextStroke: '2px #fff' }}>MEAN IT</span></div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.22em', color: '#fff', opacity: 0.8, marginTop: 24, borderTop: '1px solid rgba(255,255,255,0.3)', paddingTop: 14 }}>
          EDITION № 047
        </div>
      </div>
    </div>
  );
}

function Step({ num, title, body }) {
  return (
    <div style={{ padding: 32, border: '1px solid rgba(255,255,255,0.1)', background: 'rgba(255,255,255,0.02)', position: 'relative' }}>
      <div className="display" style={{ fontSize: 80, color: 'var(--accent)', lineHeight: 0.8 }}>{num}</div>
      <div className="display" style={{ fontSize: 28, marginTop: 24, color: '#fff' }}>{title}</div>
      <p style={{ fontSize: 15, color: 'rgba(255,255,255,0.6)', lineHeight: 1.5, marginTop: 10 }}>{body}</p>
    </div>
  );
}

// ===== CHAT VIEW =====
function ChatView({ messages, loading, input, setInput, onSend, variant, onSave, isSaved, onReset }) {
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading]);

  const empty = messages.length === 0;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr', maxWidth: 1400, margin: '0 auto', padding: '24px 32px', height: 'calc(100vh - 82px)', gap: 24 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minHeight: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ position: 'relative', width: 44, height: 44, borderRadius: '50%', background: 'linear-gradient(135deg, var(--accent), #8a0c0c)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span className="display" style={{ fontSize: 20, color: '#fff' }}>V</span>
              <span style={{ position: 'absolute', bottom: 0, right: 0, width: 12, height: 12, borderRadius: '50%', background: '#2ecc71', border: '2px solid #0a0a0a' }} />
            </div>
            <div>
              <div className="display" style={{ fontSize: 22 }}>COACH V</div>
              <div className="mono" style={{ fontSize: 11, opacity: 0.5, letterSpacing: '0.12em' }}>● ONLINE · READY TO COOK</div>
            </div>
          </div>
          <button className="btn btn-ghost" style={{ padding: '10px 16px', fontSize: 12 }} onClick={onReset}>↻ New chat</button>
        </div>

        <div ref={scrollRef} className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '8px 0', minHeight: 0 }}>
          {empty && <EmptyChat onSuggest={onSend} />}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 920, margin: '0 auto' }}>
            {messages.map((m, i) => (
              <MessageBubble key={i} msg={m} variant={variant} onSave={onSave} isSaved={isSaved} />
            ))}
            {loading && <TypingBubble />}
          </div>
        </div>

        <Composer input={input} setInput={setInput} onSend={onSend} loading={loading} />
      </div>
    </div>
  );
}

function EmptyChat({ onSuggest }) {
  return (
    <div style={{ maxWidth: 920, margin: '40px auto 24px', textAlign: 'center' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)' }}>READY WHEN YOU ARE</div>
      <div className="display" style={{ fontSize: 'clamp(44px, 6vw, 72px)', marginTop: 18 }}>What are we<br />doing today?</div>
      <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.5)', marginTop: 18 }}>Tell me how you feel, how long you've got, what you have. I'll build it.</p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 32 }}>
        {SUGGESTIONS.map((s, i) => (
          <button key={i} className="chip" onClick={() => onSuggest(s)}>{s}</button>
        ))}
      </div>
    </div>
  );
}

function MessageBubble({ msg, variant, onSave, isSaved }) {
  if (msg.role === 'user') {
    return (
      <div style={{ alignSelf: 'flex-end', maxWidth: '78%' }} className="fade-up">
        <div style={{ background: 'var(--accent)', color: '#fff', padding: '14px 20px', borderRadius: '14px 14px 2px 14px', fontSize: 16, fontWeight: 500, lineHeight: 1.4 }}>
          {msg.content}
        </div>
      </div>
    );
  }
  return (
    <div style={{ alignSelf: 'stretch', maxWidth: '100%' }} className="fade-up">
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <div style={{ flexShrink: 0, width: 32, height: 32, borderRadius: '50%', background: 'linear-gradient(135deg, var(--accent), #8a0c0c)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 4 }}>
          <span className="display" style={{ fontSize: 14, color: '#fff' }}>V</span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          {msg.content && (
            <div style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', color: '#fff', padding: '14px 20px', borderRadius: '14px 14px 14px 2px', fontSize: 16, lineHeight: 1.45, maxWidth: 680 }}>
              {msg.content}
            </div>
          )}
          {msg.wod && (
            <div style={{ marginTop: 12, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', padding: '20px 24px', borderRadius: '0 14px 14px 14px', maxWidth: 680 }}>
              <div className="display" style={{ fontSize: 32, marginBottom: 4 }}>{msg.wod.title}</div>
              <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.55)', marginBottom: 16 }}>{msg.wod.subtitle} · {msg.wod.duration} · {msg.wod.intensity}</div>
              {msg.wod.blocks.map((b, i) => (
                <div key={i} style={{ marginBottom: 16 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.15em', color: 'var(--accent)', marginBottom: 6, textTransform: 'uppercase' }}>{b.label}{b.time ? ` · ${b.time}` : ''}</div>
                  {b.note && <div style={{ fontSize: 13, fontStyle: 'italic', color: 'rgba(255,255,255,0.5)', marginBottom: 6 }}>{b.note}</div>}
                  {b.items.map((it, j) => (
                    <div key={j} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid rgba(255,255,255,0.06)', fontSize: 15 }}>
                      <span>{it.name}</span>
                      <span className="mono" style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>{it.reps}</span>
                    </div>
                  ))}
                </div>
              ))}
              {msg.wod.closer && <div style={{ marginTop: 16, fontSize: 15, fontStyle: 'italic', color: 'rgba(255,255,255,0.7)' }}>"{msg.wod.closer}"</div>}
              <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
                <button className="btn btn-ghost" style={{ padding: '12px 18px', fontSize: 13 }} onClick={() => onSave(msg.wod)}>{isSaved(msg.wod) ? '✓ Saved' : '☆ Save'}</button>
              </div>
            </div>
          )}
          {msg.outro && (
            <div style={{ marginTop: 12, fontSize: 14, color: 'rgba(255,255,255,0.55)', fontStyle: 'italic', paddingLeft: 4 }}>{msg.outro}</div>
          )}
        </div>
      </div>
    </div>
  );
}

function TypingBubble() {
  return (
    <div style={{ alignSelf: 'flex-start' }} className="fade-up">
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'linear-gradient(135deg, var(--accent), #8a0c0c)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <span className="display" style={{ fontSize: 14, color: '#fff' }}>V</span>
        </div>
        <div style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', padding: '14px 18px', borderRadius: 14 }}>
          <span className="dot" /><span className="dot" /><span className="dot" />
        </div>
      </div>
    </div>
  );
}

function Composer({ input, setInput, onSend, loading }) {
  return (
    <div style={{ maxWidth: 920, width: '100%', margin: '0 auto' }}>
      <form onSubmit={(e) => { e.preventDefault(); onSend(input); }} style={{
        display: 'flex', gap: 8, alignItems: 'center',
        background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 4, padding: 8,
      }}>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(input); } }}
          placeholder="How's your body feeling today?"
          rows={1}
          style={{
            flex: 1, background: 'transparent', border: 0, color: '#fff',
            fontSize: 16, padding: '12px 12px', resize: 'none', outline: 'none', maxHeight: 140,
          }}
        />
        <button type="submit" className="btn btn-primary" disabled={loading || !input.trim()} style={{ opacity: loading || !input.trim() ? 0.4 : 1 }}>
          {loading ? 'Cooking...' : 'Send →'}
        </button>
      </form>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', opacity: 0.35, marginTop: 10, textAlign: 'center' }}>
        ENTER TO SEND · SHIFT+ENTER FOR NEW LINE
      </div>
    </div>
  );
}

// ===== SAVED =====
function SavedView({ saved, onOpen, onRemove, variant }) {
  return (
    <div style={{ maxWidth: 1400, margin: '0 auto', padding: '48px 32px' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)' }}>● YOUR ARSENAL</div>
      <div className="display" style={{ fontSize: 'clamp(48px, 8vw, 104px)', marginTop: 10 }}>Saved WODs</div>
      <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: 16, maxWidth: 600, marginTop: 12 }}>
        Workouts you've starred. Ready to run again when the mood strikes.
      </p>
      {saved.length === 0 ? (
        <div style={{ marginTop: 60, padding: 60, border: '1px dashed rgba(255,255,255,0.15)', textAlign: 'center' }}>
          <div className="display" style={{ fontSize: 44, color: 'rgba(255,255,255,0.4)' }}>Nothing here yet.</div>
          <p style={{ color: 'rgba(255,255,255,0.4)', marginTop: 12, fontSize: 15 }}>Generate a WOD and star it to save it for later.</p>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 20, marginTop: 40 }}>
          {saved.map(w => <SavedCard key={w.id} wod={w} onOpen={() => onOpen(w)} onRemove={() => onRemove(w)} />)}
        </div>
      )}
    </div>
  );
}

function SavedCard({ wod, onOpen, onRemove }) {
  return (
    <div
      style={{ border: '1px solid rgba(255,255,255,0.08)', padding: 24, background: 'rgba(255,255,255,0.02)', position: 'relative', cursor: 'pointer', transition: 'all .15s' }}
      onClick={onOpen}
      onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--accent)'}
      onMouseLeave={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.08)'}
    >
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', color: 'rgba(255,255,255,0.4)' }}>{new Date(wod.savedAt || Date.now()).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }).toUpperCase()}</div>
      <div className="display" style={{ fontSize: 40, marginTop: 8, lineHeight: 0.9 }}>{wod.title}</div>
      <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.55)', marginTop: 6 }}>{wod.subtitle}</div>
      <div style={{ display: 'flex', gap: 12, marginTop: 20, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
        <span className="mono" style={{ fontSize: 11, opacity: 0.6 }}>{wod.duration}</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{wod.intensity}</span>
        <button onClick={e => { e.stopPropagation(); onRemove(); }} style={{ marginLeft: 'auto', background: 'transparent', border: 0, color: 'rgba(255,255,255,0.4)', cursor: 'pointer', fontSize: 12 }}>Remove</button>
      </div>
    </div>
  );
}

// ===== HISTORY =====
function BigStat({ num, label, accent }) {
  return (
    <div style={{ background: '#0a0a0a', padding: 36 }}>
      <div className="display" style={{ fontSize: 64, lineHeight: 0.9, color: accent ? 'var(--accent)' : '#fff' }}>{num}</div>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', opacity: 0.55, marginTop: 10, textTransform: 'uppercase' }}>{label}</div>
    </div>
  );
}

function Heatmap() {
  const weeks = 12, days = 7;
  const cells = [];
  let seed = 42;
  const rand = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
  for (let w = 0; w < weeks; w++) {
    for (let d = 0; d < days; d++) {
      const r = rand();
      cells.push(r < 0.3 ? 0 : r < 0.55 ? 1 : r < 0.8 ? 2 : 3);
    }
  }
  const colors = ['rgba(255,255,255,0.06)', 'rgba(255,45,45,0.3)', 'rgba(255,45,45,0.6)', 'var(--accent)'];
  return (
    <div style={{ display: 'inline-flex', gap: 3 }}>
      {Array.from({ length: weeks }).map((_, w) => (
        <div key={w} style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {Array.from({ length: days }).map((_, d) => (
            <div key={d} style={{ width: 18, height: 18, background: colors[cells[w * days + d]], borderRadius: 2 }} />
          ))}
        </div>
      ))}
      <div style={{ marginLeft: 20, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 6 }}>
        <span className="mono" style={{ fontSize: 10, opacity: 0.5 }}>Less</span>
        <div style={{ display: 'flex', gap: 2 }}>
          {colors.map((c, i) => <div key={i} style={{ width: 14, height: 14, background: c, borderRadius: 2 }} />)}
        </div>
        <span className="mono" style={{ fontSize: 10, opacity: 0.5 }}>More</span>
      </div>
    </div>
  );
}

function HistoryView({ variant }) {
  return (
    <div style={{ maxWidth: 1400, margin: '0 auto', padding: '48px 32px' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)' }}>● EARNED, NOT GIVEN</div>
      <div className="display" style={{ fontSize: 'clamp(48px, 8vw, 104px)', marginTop: 10 }}>History</div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, marginTop: 40, background: 'rgba(255,255,255,0.08)' }}>
        <BigStat num="47" label="Total WODs" />
        <BigStat num="12" label="Current streak" accent />
        <BigStat num="23h" label="Time trained" />
        <BigStat num="94%" label="Completion rate" />
      </div>

      <div style={{ marginTop: 48 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', opacity: 0.5, marginBottom: 16 }}>LAST 12 WEEKS</div>
        <Heatmap />
      </div>

      <div style={{ marginTop: 48 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', opacity: 0.5, marginBottom: 16 }}>RECENT SESSIONS</div>
        <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)' }}>
          {SAMPLE_HISTORY.map(h => (
            <div key={h.id} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 120px 120px 120px 80px', alignItems: 'center', padding: '20px 0', borderBottom: '1px solid rgba(255,255,255,0.08)', gap: 16 }}>
              <div className="mono" style={{ fontSize: 11, opacity: 0.5, letterSpacing: '0.15em' }}>{h.date.toUpperCase()}</div>
              <div className="display" style={{ fontSize: 28 }}>{h.title}</div>
              <div className="mono" style={{ fontSize: 12, opacity: 0.6 }}>{h.duration}</div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--accent)' }}>{h.intensity}</div>
              <div style={{ fontSize: 13, opacity: 0.7 }}>{h.focus}</div>
              <div style={{ textAlign: 'right' }}>
                {h.completed
                  ? <span className="mono" style={{ fontSize: 11, color: '#2ecc71', letterSpacing: '0.15em' }}>✓ DONE</span>
                  : <span className="mono" style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.15em' }}>— SKIP</span>
                }
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Mount
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
