// Vidgas — screens
// Exports: LibraryScreen, PlayerScreen, UploadScreen, CollectionsScreen, SearchScreen

const { useState: useS, useEffect: useE, useRef: useR, useMemo } = React;

/* ============== LIBRARY ============== */
function LibraryScreen({ data, navigate }) {
  const [filter, setFilter] = useS('all');
  const featured = data.VIDEOS.find(v => v.featured) || data.VIDEOS[0];
  const rest = data.VIDEOS.filter(v => v.id !== featured.id);

  const filters = [
    { value: 'all', label: 'Semua' },
    { value: 'recent', label: 'Terbaru' },
    { value: '4k', label: '4K' },
    { value: 'travel', label: 'Travel' },
    { value: 'family', label: 'Keluarga' },
    { value: 'friends', label: 'Anak-anak' },
  ];

  const filtered = useMemo(() => {
    if (filter === 'all') return rest;
    if (filter === 'recent') return rest.slice(0, 6);
    if (filter === '4k') return rest.filter(v => v.resolution === '4K');
    return rest.filter(v => v.collection === filter);
  }, [filter]);

  const recentlyAdded = rest.slice(0, 6);

  return (
    <div className="page">
      <Hero video={featured} navigate={navigate} />

      <div className="section">
        <SectionHead title="Baru ditambahkan" meta={`${recentlyAdded.length} video`} />
        <div className="grid">
          {recentlyAdded.map(v => <VideoCard key={v.id} video={v} navigate={navigate} />)}
        </div>
      </div>

      <div className="section">
        <SectionHead title="Library kamu" action={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span className="meta" style={{ color: 'var(--fg-2)', fontSize: 12.5 }}>{filtered.length} video</span>
          </div>
        } />
        <Chips items={filters} value={filter} onChange={setFilter} />
        <div className="grid">
          {filtered.map(v => <VideoCard key={v.id} video={v} navigate={navigate} />)}
        </div>
      </div>
    </div>
  );
}

/* ============== VIDEO PLAYER COMPONENT ============== */
// iOS Safari has the best native HLS implementation. Video.js VHS polyfill
// often stutters on iOS even in "native mode", so we bypass Video.js entirely
// for iOS and use a plain <video> element with the HLS URL.
const IS_IOS = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
               (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

function VidgasPlayer({ videoUrl, poster, filename }) {
  const videoRef = useR(null);
  const playerRef = useR(null);

  useE(() => {
    if (!videoRef.current || !videoUrl) return;

    // Determine HLS URL from filename
    const hlsUrl = filename ? `/api/hls/${filename}/index.m3u8` : null;

    // iOS path: use native <video> element directly. No Video.js, no VHS.
    // Prefer MP4 with HTTP Range over HLS — iOS Safari handles this most reliably
    // for VOD content and avoids MPEG-TS HLS stutter.
    if (IS_IOS) {
      const v = videoRef.current;
      v.src = videoUrl || hlsUrl;
      if (poster) v.poster = poster;
      v.controls = true;
      v.preload = 'metadata';
      return () => {
        try { v.pause(); v.removeAttribute('src'); v.load(); } catch (e) {}
      };
    }

    // Non-iOS path: Video.js with VHS polyfill
    const playerOptions = {
      controls: true,
      responsive: true,
      fluid: true,
      playsinline: true,
      preload: 'metadata',
      poster: poster || '',
      html5: {
        vhs: {
          overrideNative: !videojs.browser.IS_SAFARI,
          enableLowInitialPlaylist: true,
        },
        nativeAudioTracks: videojs.browser.IS_SAFARI,
        nativeVideoTracks: videojs.browser.IS_SAFARI,
      },
      sources: [],
    };

    if (hlsUrl) {
      playerOptions.sources.push({
        src: hlsUrl,
        type: 'application/x-mpegURL',
      });
    }
    if (videoUrl) {
      playerOptions.sources.push({
        src: videoUrl,
        type: 'video/mp4',
      });
    }

    const player = videojs(videoRef.current, playerOptions);
    playerRef.current = player;

    return () => {
      if (playerRef.current) {
        playerRef.current.dispose();
        playerRef.current = null;
      }
    };
  }, [videoUrl, filename]);

  // iOS: plain video element, no video-js classes (avoid Video.js CSS interference)
  if (IS_IOS) {
    return (
      <video
        ref={videoRef}
        playsInline
        controls
        style={{ width: '100%', height: 'auto', background: '#000', borderRadius: 8 }}
      />
    );
  }

  // Non-iOS: Video.js wrapper
  return (
    <div data-vjs-player>
      <video
        ref={videoRef}
        className="video-js vjs-big-play-centered vjs-theme-vidgas"
        playsInline
        crossOrigin="anonymous"
      />
    </div>
  );
}

/* ============== PLAYER ============== */
function PlayerScreen({ data, route, navigate }) {
  const video = data.VIDEOS.find(v => v.id === route.id) || data.VIDEOS[0];
  const related = data.VIDEOS.filter(v => v.id !== video.id && v.collection === video.collection).slice(0, 4);
  const more = data.VIDEOS.filter(v => v.id !== video.id).slice(0, 8);

  // Extract filename from video_url (e.g. "/api/stream/file.mp4" -> "file.mp4")
  const filename = video.video_url ? video.video_url.split('/').pop() : null;

  return (
    <div className="player-page">
      <div className="player-stage">
        <button className="player-back-btn" onClick={() => navigate({ name: 'library' })}>
          <Icon name="arrowLeft" /> Kembali
        </button>
        {video.video_url ? (
          <VidgasPlayer
            videoUrl={video.video_url}
            poster={video.thumb}
            filename={filename}
          />
        ) : (
          <img src={video.thumb} alt={video.title} />
        )}
      </div>

      <div className="player-info">
        <h1>{video.title}</h1>
        <div className="meta-row">
          <span className="pill">{video.resolution}</span>
          <span>{video.duration}</span>
          <span className="dot"></span>
          <span>{video.size}</span>
          <span className="dot"></span>
          <span>{video.views} kali ditonton</span>
          <span className="dot"></span>
          <span>{video.date}</span>
        </div>
        <div className="actions">
          <button className="btn"><Icon name="heart" /> Favoritkan</button>
          <button className="btn"><Icon name="share" /> Bagikan link</button>
          <button className="btn"><Icon name="download" /> Download</button>
          <button className="btn"><Icon name="folder" /> Pindahkan</button>
          <button className="btn"><Icon name="more" /></button>
        </div>
        <div className="desc">{video.description}</div>

        {related.length > 0 && (
          <div className="related">
            <SectionHead title="Dari koleksi yang sama" meta={`${related.length} video`} />
            <div className="grid">
              {related.map(v => <VideoCard key={v.id} video={v} navigate={navigate} />)}
            </div>
          </div>
        )}

        <div className="related">
          <SectionHead title="Mungkin kamu suka" />
          <div className="grid compact">
            {more.map(v => <VideoCard key={v.id} video={v} navigate={navigate} />)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============== UPLOAD / DOWNLOAD FROM VIDARA ============== */
function UploadScreen({ data, navigate }) {
  const [vidaraUrl, setVidaraUrl] = useS('');
  const [queue, setQueue] = useS([]);
  const [loading, setLoading] = useS(false);

  // Poll download status
  useE(() => {
    const downloading = queue.filter(q => q.status === 'downloading');
    if (!downloading.length) return;
    const id = setInterval(() => {
      downloading.forEach(item => {
        fetch('/api/download/status/' + item.id)
          .then(r => r.json())
          .then(d => {
            setQueue(q => q.map(qi => qi.id === item.id ? { ...qi, status: d.status, title: d.title || qi.title, size: d.size } : qi));
          }).catch(() => {});
      });
    }, 3000);
    return () => clearInterval(id);
  }, [queue]);

  const submitDownload = () => {
    if (!vidaraUrl.trim()) return;
    setLoading(true);
    fetch('/api/download', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ url: vidaraUrl.trim() }),
    })
      .then(r => r.json())
      .then(d => {
        if (d.ok) {
          setQueue(q => [{ id: d.video_id, title: vidaraUrl.split('/').pop(), status: d.status, size: 0 }, ...q]);
          setVidaraUrl('');
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  const totalVideos = data.VIDEOS.length;
  const totalSize = data.VIDEOS.reduce((s, v) => {
    const m = (v.size || '').match(/([\d.]+)\s*(GB|MB|KB)/i);
    if (!m) return s;
    const n = parseFloat(m[1]);
    if (m[2].toUpperCase() === 'GB') return s + n;
    if (m[2].toUpperCase() === 'MB') return s + n / 1024;
    return s;
  }, 0);

  return (
    <div className="page">
      <div style={{ margin: '32px 0 8px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', margin: 0 }}>Download video</h1>
        <p style={{ color: 'var(--fg-2)', fontSize: 14, margin: '8px 0 0' }}>Paste link Vidara.to untuk download dan simpan ke library.</p>
      </div>

      <div className="upload-grid">
        <div className="dropzone" style={{ cursor: 'default' }}>
          <div className="drop-icon">
            <Icon name="download" />
          </div>
          <h3>Download dari Vidara</h3>
          <p>Paste link video dari vidara.to</p>
          <div style={{ width: '100%', maxWidth: 480, margin: '16px auto 0' }}>
            <input
              value={vidaraUrl}
              onChange={(e) => setVidaraUrl(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && submitDownload()}
              placeholder="https://vidara.to/v/..."
              style={{
                width: '100%', padding: '14px 16px',
                background: 'var(--bg-1)', border: '1px solid var(--line-2)',
                borderRadius: 10, color: 'var(--fg-0)',
                fontSize: 14, fontFamily: 'var(--font-mono)',
                outline: 'none', marginBottom: 12,
              }}
            />
            <button
              className="btn btn-primary"
              onClick={submitDownload}
              disabled={loading || !vidaraUrl.trim()}
              style={{ width: '100%', padding: '12px', fontSize: 14, fontWeight: 600 }}
            >
              {loading ? '⏳ Memproses...' : '⬇️ Download & Simpan'}
            </button>
          </div>
          <div className="upload-formats" style={{ marginTop: 16 }}>
            <span>vidara.to</span><span>vidara.so</span><span>HLS → MP4</span>
          </div>
        </div>

        <div className="upload-side">
          <div className="stats">
            <div className="stat">
              <div className="label">Total size</div>
              <div className="val">{totalSize.toFixed(1)}<small> GB</small></div>
            </div>
            <div className="stat">
              <div className="label">Total video</div>
              <div className="val">{totalVideos}</div>
            </div>
            <div className="stat">
              <div className="label">Antrian</div>
              <div className="val">{queue.filter(q => q.status === 'downloading').length}</div>
            </div>
          </div>

          <div className="queue-card">
            <div className="head">
              <h4>Antrian download</h4>
              <span className="count">{queue.length} file</span>
            </div>
            {queue.length === 0 && (
              <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
                Belum ada download
              </div>
            )}
            {queue.map((u, i) => (
              <div className="queue-item" key={u.id || i}>
                <div className="queue-thumb"><Icon name="film" size={18} /></div>
                <div className="queue-info">
                  <div className="name">{u.title || u.id}</div>
                  <div className="sub">
                    <span>{u.size ? ((u.size / 1048576).toFixed(0) + ' MB') : '...'}</span>
                    <span style={{ flex: 1 }}></span>
                    <span className={'queue-status ' + u.status}>
                      {u.status === 'ready' ? '✅ Selesai' : u.status === 'downloading' ? '⬇️ Downloading...' : u.status === 'error' ? '❌ Error' : u.status === 'already_exists' ? '✅ Sudah ada' : u.status}
                    </span>
                  </div>
                  {u.status === 'downloading' && (
                    <div className="queue-bar">
                      <div style={{ width: '60%', animation: 'pulse 1.5s infinite' }}></div>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function UploadOption({ label, defaultOn }) {
  const [on, setOn] = useS(!!defaultOn);
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid var(--line-1)' }}>
      <span style={{ fontSize: 13, color: 'var(--fg-1)' }}>{label}</span>
      <button onClick={() => setOn(!on)} style={{
        width: 36, height: 20, borderRadius: 99,
        background: on ? 'var(--accent)' : 'var(--bg-4)',
        border: '1px solid var(--line-1)',
        position: 'relative', cursor: 'pointer', transition: 'background 160ms',
      }}>
        <div style={{
          position: 'absolute', top: 1, left: on ? 17 : 1, width: 16, height: 16,
          background: 'white', borderRadius: '50%', transition: 'left 160ms',
        }}></div>
      </button>
    </div>
  );
}

/* ============== COLLECTIONS ============== */
function CollectionsScreen({ data, navigate }) {
  return (
    <div className="page">
      <div style={{ margin: '32px 0 24px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', margin: 0 }}>Koleksi</h1>
          <p style={{ color: 'var(--fg-2)', fontSize: 14, margin: '8px 0 0' }}>Folder dan playlist buat ngerapiin video kamu.</p>
        </div>
        <button className="btn btn-primary"><Icon name="folder" /> Bikin koleksi baru</button>
      </div>

      <div className="coll-grid">
        {data.COLLECTIONS.map(c => (
          <div key={c.id} className="coll" onClick={() => navigate({ name: 'library' })}>
            <img src={c.thumb} alt={c.name} />
            <div className="coll-overlay">
              <span className="coll-tag" style={{ background: c.color }}></span>
              <h3 className="coll-name">{c.name}</h3>
              <div className="coll-count">
                <span className="pill">{c.count} video</span>
                <span>terakhir update 2 hari lalu</span>
              </div>
            </div>
          </div>
        ))}

        <div className="coll" style={{
          background: 'var(--bg-2)',
          border: '1.5px dashed var(--line-2)',
          display: 'grid', placeItems: 'center',
          color: 'var(--fg-2)', cursor: 'pointer',
        }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ width: 48, height: 48, borderRadius: 14, background: 'var(--bg-3)', display: 'grid', placeItems: 'center', margin: '0 auto 12px', color: 'var(--accent)' }}>
              <Icon name="folder" size={22} />
            </div>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-0)' }}>Koleksi baru</div>
            <div style={{ fontSize: 12, marginTop: 4 }}>Kelompokin video kamu</div>
          </div>
        </div>
      </div>

      <div className="section" style={{ marginTop: 48 }}>
        <SectionHead title="Sering diakses" />
        <div className="grid">
          {data.VIDEOS.slice(0, 4).map(v => <VideoCard key={v.id} video={v} navigate={navigate} />)}
        </div>
      </div>
    </div>
  );
}

/* ============== SEARCH ============== */
function SearchScreen({ data, navigate }) {
  const [q, setQ] = useS('bali');
  const [filter, setFilter] = useS('all');
  const inputRef = useR(null);

  useE(() => { inputRef.current && inputRef.current.focus(); }, []);

  const filters = [
    { value: 'all', label: 'Semua' },
    { value: 'video', label: 'Video' },
    { value: 'collection', label: 'Koleksi' },
    { value: '4k', label: '4K' },
    { value: 'recent', label: 'Bulan ini' },
  ];

  const results = useMemo(() => {
    if (!q) return [];
    const ql = q.toLowerCase();
    let r = data.VIDEOS.filter(v =>
      v.title.toLowerCase().includes(ql) ||
      v.description.toLowerCase().includes(ql) ||
      v.collection.toLowerCase().includes(ql)
    );
    if (filter === '4k') r = r.filter(v => v.resolution === '4K');
    if (filter === 'recent') r = r.slice(0, 6);
    return r;
  }, [q, filter]);

  const highlight = (text) => {
    if (!q) return text;
    const i = text.toLowerCase().indexOf(q.toLowerCase());
    if (i < 0) return text;
    return <>{text.slice(0, i)}<mark>{text.slice(i, i + q.length)}</mark>{text.slice(i + q.length)}</>;
  };

  return (
    <div className="page">
      <div style={{ margin: '32px 0 18px' }}>
        <div style={{ position: 'relative', maxWidth: 720 }}>
          <Icon name="search" style={{ position: 'absolute', left: 18, top: '50%', transform: 'translateY(-50%)', width: 18, height: 18, color: 'var(--fg-2)' }} />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Cari judul, deskripsi, koleksi…"
            style={{
              width: '100%', padding: '16px 18px 16px 50px',
              background: 'var(--bg-2)', border: '1px solid var(--line-2)',
              borderRadius: 14, color: 'var(--fg-0)',
              fontSize: 18, fontFamily: 'var(--font-display)', fontWeight: 500,
              outline: 'none', letterSpacing: '-0.01em',
            }}
          />
          {q && (
            <button className="icon-btn" onClick={() => setQ('')} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)' }}>
              <Icon name="x" />
            </button>
          )}
        </div>
        <div style={{ color: 'var(--fg-2)', fontSize: 13, margin: '14px 2px 0' }}>
          {q ? `${results.length} hasil untuk "${q}"` : 'Mulai ngetik buat nyari…'}
        </div>
      </div>

      <Chips items={filters} value={filter} onChange={setFilter} />

      {!q ? (
        <div className="search-empty">
          <h3>Apa yang lagi kamu cari?</h3>
          <p>Coba "bali", "mama", atau "tokyo".</p>
        </div>
      ) : results.length === 0 ? (
        <div className="search-empty">
          <h3>Ga ada hasil</h3>
          <p>Coba kata kunci lain.</p>
        </div>
      ) : (
        <div className="search-results">
          {results.map(v => (
            <div key={v.id} className="sr-item" onClick={() => navigate({ name: 'player', id: v.id })}>
              <div className="sr-thumb">
                <img src={v.thumb} alt={v.title} />
                <span className="card-duration">{v.duration}</span>
              </div>
              <div className="sr-body">
                <h3>{highlight(v.title)}</h3>
                <p>{highlight(v.description)}</p>
                <div className="meta">
                  <span>{v.resolution}</span>
                  <span className="dot"></span>
                  <span>{v.size}</span>
                  <span className="dot"></span>
                  <span>{v.views} kali ditonton</span>
                  <span className="dot"></span>
                  <span>{v.date}</span>
                </div>
              </div>
              <button className="icon-btn"><Icon name="play" /></button>
            </div>
          ))}
        </div>
      )}

      {q && (
        <div style={{ marginTop: 40 }}>
          <SectionHead title="Saran pencarian" />
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {['bali sunset', 'mama masak', 'bromo', 'tokyo snow', 'lebaran 2025', 'studio session'].map(s => (
              <button key={s} className="chip" onClick={() => setQ(s)}>{s}</button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LibraryScreen, PlayerScreen, UploadScreen, CollectionsScreen, SearchScreen });
