/* ============================================================
   CENSA — Stories (rangée sur le fil + visionneuse plein écran)
   ============================================================ */

function StoryVideoThumb({ mediaKey }) {
  const url = useMediaUrl(mediaKey);
  if (!url) return <div className="story-thumb" style={{ background: '#111' }} />;
  return <video src={url} muted playsInline preload="metadata" className="story-thumb" />;
}

function StoriesRow({ t, me, stories, onAdd, onOpen }) {
  const list = stories || [];
  return (
    <div className="stories-row">
      <button className="story-tile story-add" onClick={onAdd}>
        <div className="story-add-top">
          {me && me.avatar
            ? <MediaImg mediaKey={me.avatar} style={{ width: '100%', height: '100%' }} />
            : <div style={{ width: '100%', height: '100%', background: `linear-gradient(150deg, oklch(0.55 0.13 ${(me && me.hue) || 196}), oklch(0.40 0.11 ${((me && me.hue) || 196) + 30}))` }} />}
        </div>
        <span className="story-add-plus"><Icon name="plus" size={15} sw={3} /></span>
        <span className="story-label">{t.create_story}</span>
      </button>
      {list.map((s, i) => (
        <button key={s.id} className="story-tile" onClick={() => onOpen(i)}>
          {s.media.type === 'image'
            ? <MediaImg mediaKey={s.media.key} className="story-thumb" />
            : <StoryVideoThumb mediaKey={s.media.key} />}
          {s.media.type === 'video' && <span className="story-play"><Icon name="play" size={13} fill /></span>}
          <span className="story-grad" />
          <span className="story-av"><Avatar user={s.author} size={32} /></span>
          <span className="story-name">{s.author.name || '—'}</span>
        </button>
      ))}
    </div>
  );
}

function StoryViewer({ t, stories, index, setIndex, onClose }) {
  const s = stories[index];
  const [progress, setProgress] = useState(0);
  const vidRef = useRef(null);

  const go = (d) => {
    const n = index + d;
    if (n < 0) { setIndex(0); return; }
    if (n >= stories.length) { onClose(); return; }
    setIndex(n);
  };

  // auto-advance for images
  useEffect(() => {
    setProgress(0);
    if (!s) return;
    if (s.media.type === 'image') {
      const start = Date.now(); const dur = 5000;
      const id = setInterval(() => {
        const p = Math.min(1, (Date.now() - start) / dur);
        setProgress(p);
        if (p >= 1) { clearInterval(id); go(1); }
      }, 50);
      return () => clearInterval(id);
    }
  }, [index]);

  if (!s) return null;
  const url = null;
  return (
    <div className="story-viewer" onClick={onClose}>
      <div className="story-stage" onClick={(e) => e.stopPropagation()}>
        {/* progress segments */}
        <div className="story-progress">
          {stories.map((_, i) => (
            <span key={i} className="story-seg"><span className="story-seg-fill"
              style={{ width: i < index ? '100%' : i === index ? (progress * 100) + '%' : '0%' }} /></span>
          ))}
        </div>
        {/* header */}
        <div className="story-head">
          <Avatar user={s.author} size={34} />
          <span style={{ fontWeight: 600, fontSize: 14, color: '#fff' }}>{s.author.name || '—'}</span>
          <span className="mono" style={{ fontSize: 12, color: 'rgba(255,255,255,.7)' }}>{timeAgo(s.ts, t)}</span>
          <button className="iconbtn" onClick={onClose} style={{ marginLeft: 'auto', color: '#fff' }}><Icon name="x" size={20} /></button>
        </div>
        {/* media */}
        <div className="story-media">
          {s.media.type === 'image'
            ? <StoryImage mediaKey={s.media.key} />
            : <StoryVideo mediaKey={s.media.key} onEnded={() => go(1)} onProgress={setProgress} vidRef={vidRef} />}
        </div>
        {/* tap zones */}
        <button className="story-nav story-prev" onClick={() => go(-1)} aria-label="prev" />
        <button className="story-nav story-next" onClick={() => go(1)} aria-label="next" />
      </div>
    </div>
  );
}

function StoryImage({ mediaKey }) {
  const url = useMediaUrl(mediaKey);
  if (!url) return <div style={{ width: '100%', height: '100%', display: 'grid', placeItems: 'center', color: '#888' }}>…</div>;
  return <img src={url} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />;
}
function StoryVideo({ mediaKey, onEnded, onProgress }) {
  const url = useMediaUrl(mediaKey);
  if (!url) return <div style={{ width: '100%', height: '100%', display: 'grid', placeItems: 'center', color: '#888' }}>…</div>;
  return <video src={url} autoPlay playsInline controls={false} onEnded={onEnded}
    onTimeUpdate={(e) => { const v = e.target; if (v.duration) onProgress(v.currentTime / v.duration); }}
    style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />;
}

function timeAgo(ts, t) {
  if (!ts) return '';
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 60) return getCurLang() === 'en' ? 'now' : "à l'instant";
  const m = Math.floor(s / 60); if (m < 60) return m + ' min';
  const h = Math.floor(m / 60); if (h < 24) return h + ' h';
  return Math.floor(h / 24) + ' j';
}

Object.assign(window, { StoriesRow, StoryViewer, timeAgo });
