// Reveal — both answers side by side, with working reactions & favorite
// Changes from v1:
//  - Reactions POST /api/couple/reaction, clicking same emoji clears it
//  - Favorite is a real toggle (/api/couple/favorite) — no bot link needed
//  - Optimistic UI: we update the clicked state immediately, rollback on error

window.RevealScreen = function RevealScreen({ setScreen, state, data, reload }) {
  const { useState } = React;
  const D = data;

  // Primary source: D.today (populated when state === 'reveal-ready' or recent reveal)
  // Fallback: latest revealed item from history
  let src = D.today;
  let isToday = state === 'reveal-ready';
  let historyMode = false;
  if (!src || !src.partner_answer) {
    const h = D.history && D.history[0];
    if (h) {
      src = {
        question_id: h.db_id,
        number: h.number,
        text: h.text,
        category: h.category,
        cat_meta: h.cat_meta,
        you_answer: h.you,
        partner_answer: h.partner,
        you_reaction: h.you_reaction,
        partner_reaction: h.partner_reaction,
        date: h.date,
        favorite: h.favorite
      };
      isToday = false;
      historyMode = true;
    }
  }

  const [myReaction, setMyReaction] = useState(src ? (src.you_reaction || null) : null);
  const [favorite, setFavorite] = useState(src ? !!src.favorite : false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  if (!src) {
    return (
      <div className="fade-in">
        <div className="page-head">
          <div>
            <h1 className="page-head__title">Раскрытие ответов</h1>
            <div className="page-head__sub">Пока нет раскрытых вопросов</div>
          </div>
        </div>
        <div className="surface" style={{padding: 36, textAlign: 'center'}}>
          <div style={{fontSize: 40, marginBottom: 10}}>🌱</div>
          <div style={{fontSize: 15, color: 'var(--text-2)', marginBottom: 16}}>
            Как только вы оба ответите на сегодняшний вопрос — он появится здесь.
          </div>
          <button className="btn-primary" onClick={() => setScreen('today')}>
            <window.Icon name="today" size={15}/> К сегодняшнему вопросу
          </button>
        </div>
      </div>
    );
  }

  const cat = src.cat_meta;
  const partnerReacted = src.partner_reaction;

  async function onReact(r) {
    if (busy) return;
    const prev = myReaction;
    const next = r === myReaction ? null : r;
    setMyReaction(next);
    setBusy(true);
    setError(null);
    try {
      await window.API.setReaction(src.question_id, next);
      // Gently refresh once so history updates
      if (reload) reload();
    } catch (e) {
      setMyReaction(prev);
      setError(e.message || 'Не удалось сохранить реакцию');
    } finally {
      setBusy(false);
    }
  }

  async function onFavorite() {
    if (busy) return;
    const prev = favorite;
    const next = !favorite;
    setFavorite(next);
    setBusy(true);
    setError(null);
    try {
      await window.API.setFavorite(src.question_id, next);
      if (reload) reload();
    } catch (e) {
      setFavorite(prev);
      setError(e.message || 'Не удалось сохранить');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Раскрытие ответов</h1>
          <div className="page-head__sub">Вопрос #{src.number} · {isToday ? 'сегодня' : (src.date || 'последний раскрытый')}</div>
        </div>
        <div className="page-head__actions">
          <button className="btn-ghost" onClick={() => setScreen(historyMode ? 'archive' : 'today')}>
            <window.Icon name="arrow-l" size={14}/> Назад
          </button>
        </div>
      </div>

      <section className="reveal">
        <div className="reveal__eyebrow">
          <span className="heart">💕</span> ОТВЕТЫ ОТКРЫТЫ
        </div>
        <h2 className="reveal__q">«{src.text}»</h2>
        <div className="reveal__meta">
          <span className="qcard__cat" style={{background: `oklch(0.55 0.18 ${cat.hue} / 0.16)`, borderColor: `oklch(0.55 0.18 ${cat.hue} / 0.3)`, color: cat.color}}>
            <span>{cat.emoji}</span> {cat.ru}
          </span>
          <span>·</span>
          <span>оба ответили</span>
        </div>
      </section>

      {error && (
        <div style={{margin: '14px 0 0', padding: '8px 12px', borderRadius: 10, background: 'oklch(0.6 0.2 25 / 0.12)', color: 'oklch(0.75 0.2 25)', fontSize: 13}}>
          {error}
        </div>
      )}

      <div className="answers">
        <article className="answer answer--you fade-in">
          <header className="answer__head">
            <div className="answer__avatar">{D.me.initial}</div>
            <div>
              <div className="answer__name">{D.me.name}</div>
              <div className="answer__time">ты</div>
            </div>
            <div className="answer__role">ты</div>
          </header>
          <div className="answer__body">{src.you_answer || <span style={{color:'var(--text-4)'}}>Ответ не сохранён</span>}</div>
          <footer className="answer__foot">
            <div className="answer__react-shown">
              {partnerReacted ? <>
                <span style={{fontSize: 12}}>Реакция от {D.partner.name}:</span>
                <span className="pill"><span style={{fontSize: 16}}>{partnerReacted}</span></span>
              </> : <span style={{fontSize: 12, color: 'var(--text-4)'}}>Без реакции</span>}
            </div>
          </footer>
        </article>

        <article className="answer answer--partner fade-in" style={{animationDelay: '.15s'}}>
          <header className="answer__head">
            <div className="answer__avatar">{D.partner.initial}</div>
            <div>
              <div className="answer__name">{D.partner.name}</div>
              <div className="answer__time">партнёр</div>
            </div>
            <div className="answer__role">партнёр</div>
          </header>
          <div className="answer__body">{src.partner_answer || <span style={{color:'var(--text-4)'}}>Ответ не сохранён</span>}</div>
          <footer className="answer__foot">
            <div className="reactions">
              {D.reactions.map(r => (
                <button
                  key={r}
                  className={r === myReaction ? 'on' : ''}
                  onClick={() => onReact(r)}
                  disabled={busy}
                  title={r === myReaction ? 'Убрать реакцию' : 'Поставить реакцию'}
                >{r}</button>
              ))}
            </div>
          </footer>
        </article>
      </div>

      <div className="reveal-actions">
        <button className="btn-ghost" onClick={() => setScreen('archive')}>
          <window.Icon name="history" size={15}/> История
        </button>
        <button className="btn-primary" onClick={() => setScreen('today')}>
          К следующему вопросу <window.Icon name="arrow" size={15}/>
        </button>
      </div>

      <div className="surface" style={{padding: 18, marginTop: 20, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap'}}>
        <div style={{width: 36, height: 36, borderRadius: 11, background: favorite ? 'oklch(0.6 0.22 340 / 0.2)' : 'oklch(0.55 0.2 var(--hue-primary) / 0.15)', display: 'grid', placeItems: 'center', color: favorite ? 'oklch(0.75 0.2 340)' : 'var(--brand-hi)', flexShrink: 0, transition: 'background .2s'}}>
          <window.Icon name="heart" size={18}/>
        </div>
        <div style={{flex: 1, minWidth: 200}}>
          <div style={{fontSize: 14, fontWeight: 600}}>
            {favorite ? 'Сохранено в капсуле 💕' : 'Сохранить в капсулу?'}
          </div>
          <div style={{fontSize: 12.5, color: 'var(--text-3)', marginTop: 2}}>
            Избранные вопросы появляются на вкладке «Наша капсула» и остаются навсегда.
          </div>
        </div>
        <button
          className={favorite ? 'btn-primary' : 'btn-ghost'}
          onClick={onFavorite}
          disabled={busy}
          style={{padding: '8px 14px', minHeight: 36}}
        >
          <window.Icon name="heart" size={14}/> {favorite ? 'В избранном' : 'В избранное'}
        </button>
      </div>
    </div>
  );
};
