// ExerciseCard — interactive exercise with hints, starter code, AI reviewer
function ExerciseCard({ ex, exIdx, moduleId, accentColor, previewMode = false }) {
  const [done, setDone] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('bwc_exercises') || '{}')[`${moduleId}_${exIdx}`] || false; }
    catch { return false; }
  });
  const [expanded, setExpanded] = React.useState(false);
  const [hintsRevealed, setHintsRevealed] = React.useState(0);
  const [showStarter, setShowStarter] = React.useState(false);
  const [showExpected, setShowExpected] = React.useState(false);
  const [tab, setTab] = React.useState('overview'); // overview | criteria | review
  const [code, setCode] = React.useState('');
  const [reviewing, setReviewing] = React.useState(false);
  const [reviewResult, setReviewResult] = React.useState(null);
  const [noKey, setNoKey] = React.useState(false);
  const [showKeySetup, setShowKeySetup] = React.useState(false);
  const [copied, setCopied] = React.useState(false);

  const diffColor = ex.difficulty === 'Expert' ? '#EF4444' : ex.difficulty === 'Advanced' ? '#3B82F6' : '#C9A84C';
  const hasEnrichment = ex.hints || ex.starterCode || ex.successCriteria;

  function toggleDone() {
    const key = `${moduleId}_${exIdx}`;
    try {
      const s = JSON.parse(localStorage.getItem('bwc_exercises') || '{}');
      s[key] = !done;
      localStorage.setItem('bwc_exercises', JSON.stringify(s));
    } catch {}
    setDone(d => !d);
  }

  async function reviewCode() {
    if (!code.trim()) return;
    setNoKey(false);
    setReviewing(true);
    setReviewResult(null);
    try {
      const prompt = `You are a code reviewer for a programming course. Review this student's solution to the following exercise.

EXERCISE: ${ex.title}
DESCRIPTION: ${ex.description}

SUCCESS CRITERIA:
${(ex.successCriteria || []).map((c,i) => `${i+1}. ${c}`).join('\n')}

STUDENT'S CODE:
\`\`\`
${code}
\`\`\`

Provide a structured review with:
1. PASS/FAIL for each success criterion (be specific about what's right or wrong)
2. Bugs or errors you spot (with line references if possible)
3. One specific improvement suggestion
4. Overall verdict: PASS, NEEDS WORK, or TRY AGAIN

Be encouraging but honest. Keep it under 400 words. Use plain text (no markdown headers).`;

      const result = await callClaude(prompt, moduleId);
      setReviewResult(result);
    } catch (e) {
      if (e.message === 'NO_SESSION') {
        setReviewResult('Session expired. Please log in again.');
      } else if (e.message === 'NO_ANTHROPIC_KEY' || e.message === 'INVALID_KEY') {
        setNoKey(true);
        setReviewResult('');
      } else if (e.message === 'RATE_LIMITED') {
        setReviewResult('Rate limit hit. Wait a minute and try again.');
      } else {
        setReviewResult(`Error: ${e.message}`);
      }
    }
    setReviewing(false);
  }

  function copyStarter() {
    if (ex.starterCode) {
      navigator.clipboard.writeText(ex.starterCode.content);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    }
  }

  return (
    <div style={{
      background: '#000',
      border: `1px solid ${done ? accentColor + '44' : '#111'}`,
      borderLeft: `3px solid ${done ? accentColor : expanded ? '#333' : '#1a1a1a'}`,
      transition: 'border-color 0.2s'
    }}>
      {/* Header row */}
      <div style={{ padding:'18px 20px', display:'flex', alignItems:'flex-start', gap:14, cursor:'pointer' }}
        onClick={() => setExpanded(e => !e)}>
        {/* Checkbox */}
        <button onClick={e => { e.stopPropagation(); toggleDone(); }} style={{
          width:20, height:20, borderRadius:3, flexShrink:0, marginTop:1,
          background: done ? accentColor : 'transparent',
          border: `1.5px solid ${done ? accentColor : '#333'}`,
          cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
          transition:'all 0.15s'
        }}>
          {done && <span style={{ fontSize:11, color:'#000', fontWeight:800, lineHeight:1 }}>✓</span>}
        </button>

        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12 }}>
            <div style={{ fontFamily:'Syne,sans-serif', fontWeight:600, fontSize:15, color: done ? '#555' : '#fff', textDecoration: done ? 'line-through' : 'none', lineHeight:1.3 }}>
              {ex.title}
            </div>
            <div style={{ display:'flex', gap:8, alignItems:'center', flexShrink:0 }}>
              <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', color:diffColor, textTransform:'uppercase' }}>{ex.difficulty}</span>
              {hasEnrichment && (
                <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', letterSpacing:'0.1em' }}>
                  {expanded ? '▲' : '▼'}
                </span>
              )}
            </div>
          </div>
          <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color: done ? '#444' : '#666', lineHeight:1.65, marginTop:6 }}>
            {ex.description}
          </div>
        </div>
      </div>

      {/* Expanded content */}
      {expanded && hasEnrichment && (
        <div style={{ borderTop:'1px solid #111' }}>
          {/* Tabs */}
          <div style={{ display:'flex', borderBottom:'1px solid #111' }}>
            {[
              { id:'overview', label:'Overview' },
              { id:'criteria', label:`Criteria (${(ex.successCriteria||[]).length})` },
              { id:'review', label:'AI Review' }
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} style={{
                fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em',
                textTransform:'uppercase', background:'none', border:'none',
                borderBottom: tab===t.id ? `2px solid ${accentColor}` : '2px solid transparent',
                color: tab===t.id ? accentColor : '#444',
                padding:'10px 16px', cursor:'pointer', transition:'color 0.15s'
              }}>{t.label}</button>
            ))}
          </div>

          {/* Tab: Overview */}
          {tab === 'overview' && (
            <div style={{ padding:'20px' }}>
              {/* Hints */}
              {ex.hints && ex.hints.length > 0 && (
                <div style={{ marginBottom:20 }}>
                  <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#444', textTransform:'uppercase', marginBottom:12 }}>
                    Progressive Hints — reveal when stuck
                  </div>
                  {ex.hints.slice(0, hintsRevealed).map((hint, hi) => (
                    <div key={hi} style={{ background:'#0a0d14', borderLeft:`2px solid ${accentColor}44`, padding:'12px 14px', marginBottom:8 }}>
                      <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:accentColor, letterSpacing:'0.14em', marginBottom:6 }}>HINT {hi+1}</div>
                      <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#888', lineHeight:1.6 }}>{hint}</div>
                    </div>
                  ))}
                  {hintsRevealed < ex.hints.length && (
                    <button onClick={() => setHintsRevealed(h => h+1)} style={{
                      fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', textTransform:'uppercase',
                      background:'none', border:`1px solid #222`, color:'#555',
                      padding:'8px 14px', cursor:'pointer', width:'100%', transition:'all 0.15s'
                    }}>
                      {hintsRevealed === 0 ? `Reveal hint 1 of ${ex.hints.length}` : `Reveal hint ${hintsRevealed+1} of ${ex.hints.length}`}
                    </button>
                  )}
                  {hintsRevealed === ex.hints.length && (
                    <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', textAlign:'center', padding:'8px' }}>All hints revealed</div>
                  )}
                </div>
              )}

              {/* Starter code */}
              {ex.starterCode && (
                <div style={{ marginBottom:20 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
                    <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#444', textTransform:'uppercase' }}>Starter Code</div>
                    <div style={{ display:'flex', gap:8 }}>
                      <button onClick={() => setShowStarter(s => !s)} style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', textTransform:'uppercase', background:'none', border:'1px solid #222', color:'#555', padding:'5px 10px', cursor:'pointer' }}>
                        {showStarter ? 'Hide' : 'Show'}
                      </button>
                      <button onClick={copyStarter} style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', textTransform:'uppercase', background: accentColor, border:'none', color:'#000', padding:'5px 10px', cursor:'pointer', fontWeight:600 }}>
                        {copied ? '✓ Copied' : 'Copy'}
                      </button>
                    </div>
                  </div>
                  {showStarter && (
                    <pre style={{ background:'#060606', border:'1px solid #1a1a1a', margin:0, padding:'16px', overflowX:'auto' }}>
                      <code style={{ fontFamily:'JetBrains Mono,monospace', fontSize:12, color:'#c9d1d9', lineHeight:1.65 }}>{ex.starterCode.content}</code>
                    </pre>
                  )}
                </div>
              )}

              {/* Expected output */}
              {ex.expectedOutput && (
                <div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
                    <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#444', textTransform:'uppercase' }}>Expected Output</div>
                    <button onClick={() => setShowExpected(s => !s)} style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', textTransform:'uppercase', background:'none', border:'1px solid #222', color:'#555', padding:'5px 10px', cursor:'pointer' }}>
                      {showExpected ? 'Hide' : 'Show'}
                    </button>
                  </div>
                  {showExpected && (
                    <pre style={{ background:'#050f05', border:'1px solid #1a2a1a', margin:0, padding:'14px 16px', overflowX:'auto' }}>
                      <code style={{ fontFamily:'JetBrains Mono,monospace', fontSize:12, color:'#7ec87e', lineHeight:1.65 }}>{ex.expectedOutput}</code>
                    </pre>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Tab: Success Criteria */}
          {tab === 'criteria' && (
            <div style={{ padding:'20px' }}>
              <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#666', lineHeight:1.6, marginBottom:16 }}>
                Before marking this exercise complete, verify each criterion:
              </div>
              {(ex.successCriteria || []).map((c, ci) => (
                <div key={ci} style={{ display:'flex', gap:10, padding:'10px 0', borderBottom:'1px solid #0d0d0d' }}>
                  <div style={{ width:18, height:18, borderRadius:3, border:`1px solid #222`, flexShrink:0, marginTop:1, display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <span style={{ fontSize:9, color:'#333' }}>{ci+1}</span>
                  </div>
                  <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#888', lineHeight:1.6 }}>{c}</div>
                </div>
              ))}
              <button onClick={toggleDone} style={{
                marginTop:16, width:'100%', fontFamily:'JetBrains Mono,monospace', fontSize:10,
                letterSpacing:'0.18em', textTransform:'uppercase',
                background: done ? 'transparent' : accentColor,
                border: `1px solid ${accentColor}`,
                color: done ? accentColor : '#000',
                padding:'12px', cursor:'pointer', fontWeight:600, transition:'all 0.2s'
              }}>
                {done ? '✓ Marked Complete — click to undo' : 'All criteria met — mark complete'}
              </button>
            </div>
          )}

          {/* Tab: AI Review */}
          {tab === 'review' && (
            <div style={{ padding:'20px' }}>
              {/* No key warning */}
              {noKey && (
                <div style={{ background:'#0a0a00', border:'1px solid #2a2a00', borderLeft:'3px solid #C9A84C', padding:'16px 18px', marginBottom:16 }}>
                  <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#C9A84C', textTransform:'uppercase', marginBottom:8 }}>
                    API key required
                  </div>
                  <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#888', lineHeight:1.6, marginBottom:12 }}>
                    {previewMode
                      ? 'Add your Anthropic API key (free preview). It stays in this browser; we proxy requests so your key is never exposed to client-side network calls to Anthropic. You pay Anthropic for usage.'
                      : 'AI review uses the Anthropic API key from your dashboard (stored encrypted on our servers and proxied for reviews).'}
                  </div>
                  <button onClick={() => setShowKeySetup(true)} style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', textTransform:'uppercase', background:'#C9A84C', border:'none', color:'#000', padding:'8px 16px', cursor:'pointer', fontWeight:600 }}>
                    Set up API key →
                  </button>
                </div>
              )}

              <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#666', lineHeight:1.6, marginBottom:16 }}>
                Paste your code below. Claude will review it against the exercise criteria and flag any issues.
              </div>
              <textarea value={code} onChange={e => setCode(e.target.value)}
                placeholder="# Paste your solution here..."
                style={{ width:'100%', minHeight:200, background:'#060606', border:'1px solid #1a1a1a', color:'#c9d1d9',
                  fontFamily:'JetBrains Mono,monospace', fontSize:12, padding:'14px', resize:'vertical', outline:'none',
                  lineHeight:1.65, boxSizing:'border-box' }} />
              <button onClick={reviewCode} disabled={reviewing || !code.trim()} style={{
                marginTop:10, width:'100%', fontFamily:'JetBrains Mono,monospace', fontSize:10, letterSpacing:'0.18em', textTransform:'uppercase',
                background: reviewing ? '#111' : accentColor, border:'none',
                color: reviewing ? '#555' : '#000', padding:'12px', cursor: reviewing ? 'not-allowed' : 'pointer',
                fontWeight:600, transition:'all 0.2s'
              }}>
                {reviewing ? '⏳ Reviewing your code...' : '→ Review with Claude'}
              </button>

              {reviewResult && (
                <div style={{ marginTop:16, background:'#080808', border:`1px solid #1a1a1a`, borderLeft:`3px solid ${accentColor}`, padding:'18px' }}>
                  <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:accentColor, textTransform:'uppercase', marginBottom:12 }}>
                    Claude's Review
                  </div>
                  <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#999', lineHeight:1.75, whiteSpace:'pre-wrap' }}>
                    {reviewResult}
                  </div>
                  {(reviewResult.includes('PASS') && !reviewResult.includes('NEEDS WORK') && !reviewResult.includes('TRY AGAIN')) && (
                    <button onClick={() => { if(!done) toggleDone(); }} style={{ marginTop:14, fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', textTransform:'uppercase', background:accentColor, border:'none', color:'#000', padding:'8px 16px', cursor:'pointer', fontWeight:600 }}>
                      {done ? '✓ Already marked complete' : 'Mark as complete →'}
                    </button>
                  )}
                </div>
              )}

              {/* Key setup overlay */}
              {showKeySetup && <ApiKeyPanel isOverlay={true} previewMode={previewMode} onClose={() => { setShowKeySetup(false); setNoKey(previewMode ? !getPreviewApiKey() : localStorage.getItem('bwc_has_api_key') !== '1'); }} />}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ExerciseCard });
