/* ============================================================
   studio-history.jsx — История генераций (3 таба)
   ============================================================ */

const { useState, useEffect } = React;

function HistoryPage() {
  const { API_BASE } = useAuth();
  const [tab, setTab] = useState('image');
  const [images, setImages] = useState([]);
  const [videos, setVideos] = useState([]);
  const [music, setMusic] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    Promise.all([
      fetch(`${API_BASE}/api/tg/generations`, { credentials: 'include' }).then(r => r.ok ? r.json() : { generations: [] }),
      fetch(`${API_BASE}/api/video-status/list`, { credentials: 'include' }).catch(() => null),
      fetch(`${API_BASE}/api/tg/music`, { credentials: 'include' }).then(r => r.ok ? r.json() : { generations: [] }),
    ]).then(([imgData, , musData]) => {
      setImages(imgData.generations || []);
      setMusic(musData.generations || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  const tabs = [
    { id: 'image', label: '🎨 Изображения', count: images.length },
    { id: 'video', label: '🎬 Видео',        count: videos.length },
    { id: 'music', label: '🎵 Музыка',       count: music.length },
  ];

  function fmtDate(d) {
    return new Date(d).toLocaleDateString('ru', { day: 'numeric', month: 'short', year: '2-digit' });
  }

  return (
    <div>
      <div className="page-head">
        <div className="page-head-text">
          <h1 className="page-title h-display">🕐 История</h1>
          <p className="page-sub muted">Все твои генерации</p>
        </div>
      </div>

      <Tabs items={tabs} active={tab} onChange={setTab} />

      {loading && <div style={{ textAlign: 'center', padding: 40 }}><Spinner /></div>}

      {/* Изображения */}
      {!loading && tab === 'image' && (
        images.length === 0 ? (
          <EmptyState icon="🎨" title="Нет изображений" sub="Создай первое в разделе Изображения" />
        ) : (
          <div className="hist-grid">
            {images.map(g => (
              <div key={g.id} className="glass hist-img-card">
                {g.imageUrl ? (
                  <img src={g.imageUrl} alt="" className="hist-art" style={{ borderRadius: 8, objectFit: 'cover', aspectRatio: '4/3' }} />
                ) : (
                  <PlaceholderArt type="img" style={{ height: 130 }} />
                )}
                <div className="hist-meta">
                  <span className="hist-model">{g.model}</span>
                  <span className="muted" style={{ fontSize: 12 }}>{fmtDate(g.createdAt)}</span>
                </div>
                {g.prompt && <p className="hist-prompt muted">{g.prompt}</p>}
                {g.imageUrl && (
                  <a href={g.imageUrl} download className="btn btn-ghost btn-sm" style={{ marginTop: 8 }}>⬇ Скачать</a>
                )}
              </div>
            ))}
          </div>
        )
      )}

      {/* Видео */}
      {!loading && tab === 'video' && (
        videos.length === 0 ? (
          <EmptyState icon="🎬" title="Нет видео" sub="Создай первое в разделе Видео" />
        ) : (
          <div className="hist-list">
            {videos.map(v => (
              <div key={v.id} className="glass hist-row">
                {v.videoUrl ? (
                  <video src={v.videoUrl} className="hist-thumb" style={{ borderRadius: 6, objectFit: 'cover' }} />
                ) : (
                  <PlaceholderArt type="vid" style={{ width: 90, height: 56, flexShrink: 0 }} />
                )}
                <div className="hist-row-body">
                  <div className="hist-row-head">
                    <span className="hist-model">{v.model}</span>
                    <span className={`status-ok${v.status !== 'done' ? '' : ''}`} style={{ color: v.status === 'done' ? '#34d399' : v.status === 'failed' ? '#fca5a5' : 'var(--text-muted)' }}>
                      {v.status === 'done' ? '✓ Готово' : v.status === 'failed' ? '✗ Ошибка' : '⏳ ...'}
                    </span>
                  </div>
                  <div className="hist-sub muted">{v.durationSeconds}с · {fmtDate(v.createdAt)}</div>
                </div>
                {v.videoUrl && (
                  <a href={v.videoUrl} download className="btn btn-ghost btn-sm">⬇</a>
                )}
              </div>
            ))}
          </div>
        )
      )}

      {/* Музыка */}
      {!loading && tab === 'music' && (
        music.length === 0 ? (
          <EmptyState icon="🎵" title="Нет музыки" sub="Создай первый трек в разделе Музыка" />
        ) : (
          <div className="hist-list">
            {music.map(m => (
              <div key={m.id} className="glass hist-music-row">
                <div className="hist-music-head">
                  <div className="gicon gicon-mus" style={{ width: 44, height: 44, fontSize: 20 }}>🎵</div>
                  <div className="hist-music-meta">
                    <span style={{ fontWeight: 700 }}>{m.model}</span>
                    <span className="muted" style={{ fontSize: 12 }}>
                      {m.durationSeconds}с · {fmtDate(m.createdAt)}
                    </span>
                  </div>
                  {(m.audioUrl || m.audioUrl2) && (
                    <a href={m.audioUrl2 || m.audioUrl} download className="btn btn-ghost btn-sm">⬇</a>
                  )}
                </div>
                {m.prompt && <p className="muted" style={{ fontSize: 13 }}>{m.prompt}</p>}
                {(m.audioUrl || m.audioUrl2) && (
                  <AudioPlayer src={m.audioUrl2 || m.audioUrl} compact />
                )}
              </div>
            ))}
          </div>
        )
      )}
    </div>
  );
}
