// Per-WOD feedback row, rendered inside MessageBubble next to the Save button.
// Persists immediately on every interaction so the user never has to "submit".

function WodFeedback({ wodId }) {
  const [open, setOpen]               = React.useState(false);
  const [rating, setRating]           = React.useState(null);   // 'up' | 'down'
  const [difficulty, setDifficulty]   = React.useState(null);   // 'too_easy' | 'about_right' | 'too_hard'
  const [relevance, setRelevance]     = React.useState(null);   // 'relevant' | 'not_relevant'
  const [text, setText]               = React.useState('');
  const [savedText, setSavedText]     = React.useState('');
  const [busy, setBusy]               = React.useState(false);
  const [error, setError]             = React.useState(null);
  const [hydrated, setHydrated]       = React.useState(false);

  // Load any existing feedback when the panel opens (or on first thumb-tap).
  const ensureHydrated = React.useCallback(async () => {
    if (hydrated || !wodId) return;
    try {
      const d = await window.SnatchAPI.getWodFeedback(wodId);
      const fb = d.feedback;
      if (fb) {
        setRating(fb.rating || null);
        setDifficulty(fb.difficulty_signal || null);
        setRelevance(fb.relevance_signal || null);
        setText(fb.feedback_text || '');
        setSavedText(fb.feedback_text || '');
      }
    } catch {}
    setHydrated(true);
  }, [hydrated, wodId]);

  React.useEffect(() => { if (open) ensureHydrated(); }, [open, ensureHydrated]);

  const persist = React.useCallback(async (patch) => {
    if (!wodId) return;
    const next = {
      rating:            patch.rating            !== undefined ? patch.rating            : rating,
      difficulty_signal: patch.difficulty_signal !== undefined ? patch.difficulty_signal : difficulty,
      relevance_signal:  patch.relevance_signal  !== undefined ? patch.relevance_signal  : relevance,
      feedback_text:     patch.feedback_text     !== undefined ? patch.feedback_text     : savedText,
    };
    if (!next.rating && !next.difficulty_signal && !next.relevance_signal && !next.feedback_text) return;
    setBusy(true); setError(null);
    try {
      await window.SnatchAPI.submitWodFeedback(wodId, next);
      if (patch.feedback_text !== undefined) setSavedText(patch.feedback_text);
    } catch (e) {
      setError(e.message || 'Could not save feedback.');
    } finally {
      setBusy(false);
    }
  }, [wodId, rating, difficulty, relevance, savedText]);

  const tapRating = async (val) => {
    await ensureHydrated();
    const next = rating === val ? null : val;
    setRating(next);
    persist({ rating: next });
  };
  const tapDifficulty = (val) => {
    const next = difficulty === val ? null : val;
    setDifficulty(next);
    persist({ difficulty_signal: next });
  };
  const tapRelevance = (val) => {
    const next = relevance === val ? null : val;
    setRelevance(next);
    persist({ relevance_signal: next });
  };

  const saveText = () => persist({ feedback_text: text.trim() });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        <button
          onClick={() => tapRating('up')}
          aria-pressed={rating === 'up'}
          title="Good WOD"
          style={iconBtn(rating === 'up', '#2ecc71')}
        >👍</button>
        <button
          onClick={() => tapRating('down')}
          aria-pressed={rating === 'down'}
          title="Not great"
          style={iconBtn(rating === 'down', '#ff4d4d')}
        >👎</button>
        <button
          onClick={() => setOpen(o => !o)}
          style={textBtn}
        >{open ? 'Close feedback' : 'More feedback'}</button>
        {busy && <span className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.18em' }}>● SAVING</span>}
      </div>

      {open && (
        <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <PillRow
            label="Difficulty"
            options={[['too_easy', 'Too easy'], ['about_right', 'About right'], ['too_hard', 'Too hard']]}
            value={difficulty}
            onTap={tapDifficulty}
          />
          <PillRow
            label="Relevance"
            options={[['relevant', 'Relevant'], ['not_relevant', 'Not relevant']]}
            value={relevance}
            onTap={tapRelevance}
          />
          <div>
            <label className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase' }}>Notes</label>
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              onBlur={() => { if (text.trim() !== (savedText || '').trim()) saveText(); }}
              rows={2}
              maxLength={1000}
              placeholder="Anything specific? (optional)"
              style={{
                display: 'block', width: '100%', marginTop: 6, boxSizing: 'border-box',
                background: '#141414', border: '1px solid #2a2a2a', borderRadius: 3,
                color: '#fff', fontFamily: 'Archivo', fontSize: 13, padding: '8px 10px', resize: 'vertical',
              }}
            />
          </div>
          {error && <div style={{ fontSize: 12, color: '#fca' }}>{error}</div>}
        </div>
      )}
    </div>
  );
}

function PillRow({ label, options, value, onTap }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
        {options.map(([key, txt]) => {
          const active = value === key;
          return (
            <button
              key={key}
              onClick={() => onTap(key)}
              style={{
                padding: '7px 12px', borderRadius: 999,
                background: active ? 'var(--accent)' : 'transparent',
                color: active ? '#fff' : 'rgba(255,255,255,0.7)',
                border: '1px solid ' + (active ? 'var(--accent)' : 'rgba(255,255,255,0.18)'),
                fontFamily: 'Archivo', fontWeight: 600, fontSize: 12, cursor: 'pointer',
              }}
            >{txt}</button>
          );
        })}
      </div>
    </div>
  );
}

function iconBtn(active, activeColor) {
  return {
    padding: '8px 12px', borderRadius: 4,
    background: active ? activeColor : 'transparent',
    border: '1px solid ' + (active ? activeColor : 'rgba(255,255,255,0.2)'),
    color: '#fff', fontSize: 16, cursor: 'pointer', lineHeight: 1,
  };
}
const textBtn = {
  padding: '8px 12px', borderRadius: 4,
  background: 'transparent', border: '1px solid rgba(255,255,255,0.18)',
  color: 'rgba(255,255,255,0.75)', fontSize: 12, fontFamily: 'Archivo',
  fontWeight: 700, letterSpacing: '0.06em', cursor: 'pointer',
};

window.WodFeedback = WodFeedback;
