/* ═══════════════════════════════════════════════════════════
   DrewFans — Page components
   ═══════════════════════════════════════════════════════════ */

/* Filter definitions used by Home + Actress
   `sortBy` is the value sent to the backend. */
const HOME_FILTERS = [
  { id: 'featured',    label: 'In evidenza',     sortBy: '' },
  { id: 'recent',      label: 'Più recenti',     sortBy: 'post_date' },
  { id: 'top_today',   label: 'Top oggi',        sortBy: 'video_viewed_today' },
  { id: 'top_week',    label: 'Top settimana',   sortBy: 'video_viewed_week' },
  { id: 'top_month',   label: 'Top mese',        sortBy: 'video_viewed_month' },
  { id: 'top_all',     label: 'Top di sempre',   sortBy: 'video_viewed' },
];

const ACTRESS_FILTERS = [
  { id: 'recent',    label: 'Più recenti', sortBy: 'post_date' },
  { id: 'top_all',   label: 'Più viste',   sortBy: 'video_viewed' },
  { id: 'top_rated', label: 'Top rated',   sortBy: 'rating' },
];

/* Curated category list — links to search */
const CATEGORIES = [
  { name: 'Featured', count: null, slug: 'featured' },
  { name: 'Trending', count: null, slug: 'trending' },
  { name: 'New', count: null, slug: 'new' },
  { name: 'HD', count: null, slug: 'hd' },
  { name: '4K', count: null, slug: '4k' },
  { name: 'POV', count: null, slug: 'pov' },
  { name: 'Solo', count: null, slug: 'solo' },
  { name: 'Couple', count: null, slug: 'couple' },
  { name: 'Amateur', count: null, slug: 'amateur' },
  { name: 'Studio', count: null, slug: 'studio' },
  { name: 'Roleplay', count: null, slug: 'roleplay' },
  { name: 'Outdoor', count: null, slug: 'outdoor' },
  { name: 'Vintage', count: null, slug: 'vintage' },
  { name: 'Fetish', count: null, slug: 'fetish' },
  { name: 'Lesbian', count: null, slug: 'lesbian' },
  { name: 'MILF', count: null, slug: 'milf' },
  { name: 'Anal', count: null, slug: 'anal' },
  { name: 'Blowjob', count: null, slug: 'blowjob' },
  { name: 'Asian', count: null, slug: 'asian' },
  { name: 'Latina', count: null, slug: 'latina' },
];

/* ─── HomePage ──────────────────────────────────────────── */
function HomePage({ onVideoClick, onModelClick, watchLater }) {
  const [filterId, setFilterId] = useState('featured');
  const [page, setPage] = useState(1);
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [advOpen, setAdvOpen] = useState(false);
  const [advDuration, setAdvDuration] = useState('any'); // any | short | medium | long
  const [advQuality, setAdvQuality] = useState('any');   // any | hd | 4k

  const sortBy = HOME_FILTERS.find(f => f.id === filterId)?.sortBy ?? '';

  // Fetch when filter or page changes
  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    api.home(page, sortBy)
      .then(data => {
        if (cancelled) return;
        setVideos(data.videos || []);
        setLoading(false);
      })
      .catch(err => {
        if (cancelled) return;
        setError(err.message || 'Errore di rete');
        setVideos([]);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [page, sortBy]);

  // Reset page when filter changes
  const onFilterChange = (id) => {
    setFilterId(id);
    setPage(1);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const onPageChange = (p) => {
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // Client-side filter for duration + quality
  const filteredVideos = useMemo(() => {
    if (advDuration === 'any' && advQuality === 'any') return videos;
    return videos.filter(v => {
      // Duration filter — parse "MM:SS" or "HH:MM:SS" to seconds
      if (advDuration !== 'any') {
        const parts = (v.duration || '0:00').split(':').map(Number);
        const seconds = parts.reduce((acc, x) => acc * 60 + x, 0);
        if (advDuration === 'short' && seconds >= 600) return false;     // < 10 min
        if (advDuration === 'medium' && (seconds < 600 || seconds >= 1800)) return false; // 10-30 min
        if (advDuration === 'long' && seconds < 1800) return false;      // 30 min+
      }
      // Quality filter — naive based on categories
      if (advQuality !== 'any') {
        const cats = (v.categories || []).map(c => c.toLowerCase());
        if (advQuality === 'hd' && !cats.some(c => c.includes('hd') || c.includes('4k'))) return false;
        if (advQuality === '4k' && !cats.some(c => c.includes('4k'))) return false;
      }
      return true;
    });
  }, [videos, advDuration, advQuality]);

  const advActive = advDuration !== 'any' || advQuality !== 'any';

  const titleText = useMemo(() => {
    const f = HOME_FILTERS.find(x => x.id === filterId);
    return f ? f.label : 'Catalogo';
  }, [filterId]);

  return (
    <main className="df-main">
      <div className="df-page-head">
        <h1 className="df-h1">Catalogo</h1>
        <div className="df-sub">Filtra per periodo, durata e qualità.</div>
      </div>

      <div className="df-filter-bar">
        {HOME_FILTERS.map(f => (
          <button
            key={f.id}
            className={`df-filter-chip ${filterId === f.id ? 'active' : ''}`}
            onClick={() => onFilterChange(f.id)}
          >{f.label}</button>
        ))}
        <div className="df-filter-right">
          <button
            className={`df-pill ${advOpen || advActive ? 'active' : ''}`}
            onClick={() => setAdvOpen(o => !o)}
          >
            <Icon.Sliders size={12}/> Filtri{advActive ? ' attivi' : ''}
          </button>
        </div>
      </div>

      {advOpen && (
        <div className="df-adv-filters">
          <div className="df-adv-filter-group">
            <div className="df-adv-filter-label">Durata</div>
            <div className="df-adv-filter-row">
              {[
                { id: 'any', label: 'Tutte' },
                { id: 'short', label: '< 10 min' },
                { id: 'medium', label: '10 – 30 min' },
                { id: 'long', label: '30 min+' },
              ].map(o => (
                <button
                  key={o.id}
                  className={`df-pill ${advDuration === o.id ? 'active' : ''}`}
                  onClick={() => setAdvDuration(o.id)}
                >{o.label}</button>
              ))}
            </div>
          </div>
          <div className="df-adv-filter-group">
            <div className="df-adv-filter-label">Qualità</div>
            <div className="df-adv-filter-row">
              {[
                { id: 'any', label: 'Tutte' },
                { id: 'hd', label: 'HD+' },
                { id: '4k', label: '4K' },
              ].map(o => (
                <button
                  key={o.id}
                  className={`df-pill ${advQuality === o.id ? 'active' : ''}`}
                  onClick={() => setAdvQuality(o.id)}
                >{o.label}</button>
              ))}
            </div>
          </div>
        </div>
      )}

      {loading ? (
        <div className="df-loading"><div className="df-spinner"/></div>
      ) : error ? (
        <div className="df-empty">
          <div className="df-empty-h">Errore di rete</div>
          <div className="df-empty-p">{error}</div>
        </div>
      ) : (
        <VideoGrid
          videos={filteredVideos}
          onVideoClick={onVideoClick}
          onModelClick={onModelClick}
          watchLater={watchLater}
          emptyText={advActive ? 'Nessun video matcha i filtri' : 'Nessun video'}
        />
      )}

      {!loading && !error && videos.length > 0 && (
        <Pagination
          page={page}
          onChange={onPageChange}
          hasNext={videos.length >= 20}
        />
      )}
    </main>
  );
}

/* ─── SearchPage ────────────────────────────────────────── */
function SearchPage({ query, onVideoClick, onModelClick, watchLater }) {
  const [videos, setVideos] = useState([]);
  const [models, setModels] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Reset page when query changes
  useEffect(() => { setPage(1); }, [query]);

  useEffect(() => {
    if (!query) return;
    let cancelled = false;
    setLoading(true); setError(null);
    api.search(query, page)
      .then(data => {
        if (cancelled) return;
        setVideos(data.videos || []);
        setModels(page === 1 ? (data.models || []) : []);
        setLoading(false);
      })
      .catch(err => {
        if (cancelled) return;
        setError(err.message);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [query, page]);

  return (
    <main className="df-main">
      <div className="df-page-head">
        <h1 className="df-h1">Risultati per "{query}"</h1>
        <div className="df-sub">{page > 1 ? `Pagina ${page}` : `${videos.length} video${models.length ? ` · ${models.length} pornstar` : ''}`}</div>
      </div>

      {loading ? (
        <div className="df-loading"><div className="df-spinner"/></div>
      ) : error ? (
        <div className="df-empty">
          <div className="df-empty-h">Errore</div>
          <div className="df-empty-p">{error}</div>
        </div>
      ) : (
        <>
          {page === 1 && models.length > 0 && (
            <>
              <h2 className="df-section-title" style={{ marginTop: 0 }}>Pornstar</h2>
              <ModelGrid models={models} onModelClick={onModelClick}/>
            </>
          )}

          {page === 1 && models.length > 0 && videos.length > 0 && (
            <h2 className="df-section-title">Video</h2>
          )}

          <VideoGrid
            videos={videos}
            onVideoClick={onVideoClick}
            onModelClick={onModelClick}
            watchLater={watchLater}
            emptyText={`Nessun video per "${query}"`}
          />

          {(videos.length > 0 || page > 1) && (
            <Pagination
              page={page}
              onChange={(p) => { setPage(p); window.scrollTo({ top: 0, behavior: 'instant' }); }}
              hasNext={videos.length >= 20}
            />
          )}
        </>
      )}
    </main>
  );
}

/* ─── VideoPage ─────────────────────────────────────────── */
function VideoPage({ videoUrl, onVideoClick, onModelClick, onBack, watchLater, showToast }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!videoUrl) return;
    let cancelled = false;
    setLoading(true); setError(null); setData(null);
    api.video(videoUrl)
      .then(d => {
        if (cancelled) return;
        setData(d);
        setLoading(false);
      })
      .catch(err => {
        if (cancelled) return;
        setError(err.message);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [videoUrl]);

  if (loading) {
    return (
      <main className="df-video-page">
        <button className="df-back-btn" onClick={onBack}><Icon.ArrowLeft size={14}/> Indietro</button>
        <div className="df-loading"><div className="df-spinner"/></div>
      </main>
    );
  }
  if (error || !data) {
    return (
      <main className="df-video-page">
        <button className="df-back-btn" onClick={onBack}><Icon.ArrowLeft size={14}/> Indietro</button>
        <div className="df-empty">
          <div className="df-empty-h">Errore caricamento</div>
          <div className="df-empty-p">{error || 'Video non disponibile'}</div>
        </div>
      </main>
    );
  }

  const videoForWL = {
    url: videoUrl,
    title: data.title,
    thumbnail: data.preview,
    thumbnailWebp: data.preview,
    preview: data.preview,
    duration: data.duration || '',
    models: data.models || [],
    views: data.views || '',
    timeAgo: data.timeAgo || '',
  };
  const isSaved = watchLater.has(videoUrl);
  const primaryModel = data.models?.[0];

  return (
    <main className="df-video-page">
      <button className="df-back-btn" onClick={onBack}><Icon.ArrowLeft size={14}/> Indietro</button>

      <CustomPlayer data={data}/>

      <h1 className="df-video-title">{data.title}</h1>

      <div className="df-video-meta">
        {primaryModel && (
          <div
            className="df-video-model-pill"
            onClick={() => onModelClick(primaryModel.url, primaryModel.name)}
          >
            <div className="df-video-model-pill-img">
              <div className="df-video-model-pill-img-placeholder">
                {primaryModel.name.split(/\s+/).map(s => s[0]).join('').slice(0, 2).toUpperCase()}
              </div>
            </div>
            <span className="df-video-model-pill-name">{primaryModel.name}</span>
          </div>
        )}
        {data.views && (<span><Icon.Eye size={13}/> {data.views} views</span>)}
        {data.timeAgo && <span>· {data.timeAgo}</span>}
        {data.duration && <span>· {data.duration}</span>}
      </div>

      <div className="df-video-actions">
        <button
          className={`df-act ${isSaved ? 'saved' : ''}`}
          onClick={() => {
            watchLater.toggle(videoForWL);
            showToast?.(isSaved ? 'Rimosso da Guarda dopo' : 'Salvato in Guarda dopo');
          }}
        >
          <Icon.Bookmark size={14} filled={isSaved}/>
          {isSaved ? 'Salvato' : 'Salva'}
        </button>
        <button
          className="df-act"
          onClick={() => {
            if (navigator.share) {
              navigator.share({ title: data.title, url: window.location.href }).catch(() => {});
            } else {
              navigator.clipboard?.writeText(window.location.href);
              showToast?.('Link copiato');
            }
          }}
        ><Icon.Share size={14}/> Condividi</button>
      </div>

      {data.categories && data.categories.length > 0 && (
        <div className="df-tags">
          {data.categories.map((c, i) => <span key={i} className="df-tag">{c}</span>)}
        </div>
      )}

      {data.related && data.related.length > 0 && (
        <>
          <h2 className="df-section-title">Video correlati</h2>
          <VideoGrid
            videos={data.related}
            onVideoClick={onVideoClick}
            onModelClick={onModelClick}
            watchLater={watchLater}
          />
        </>
      )}
    </main>
  );
}

/* ─── ActressPage ───────────────────────────────────────── */
function ActressPage({ actressUrl, actressName, onVideoClick, onModelClick, onBack, watchLater }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [filterId, setFilterId] = useState('recent');
  const [page, setPage] = useState(1);

  const sortBy = ACTRESS_FILTERS.find(f => f.id === filterId)?.sortBy ?? '';

  // Reset page only when actress or sort changes
  useEffect(() => { setPage(1); }, [actressUrl, filterId]);

  // Fetch on actress / sort / page change
  useEffect(() => {
    if (!actressUrl) return;
    let cancelled = false;
    setLoading(true); setError(null);
    api.actress(actressUrl, page, sortBy)
      .then(d => {
        if (cancelled) return;
        setData(d);
        setLoading(false);
      })
      .catch(err => {
        if (cancelled) return;
        setError(err.message);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [actressUrl, sortBy, page]);

  const onPageChange = (p) => {
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const onFilterChange = (id) => {
    setFilterId(id);
    setPage(1);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const videos = data?.videos || [];

  return (
    <main className="df-profile-wrap">
      <button className="df-back-btn" onClick={onBack}>
        <Icon.ArrowLeft size={14}/> Indietro
      </button>

      <div className="df-profile-banner"/>
      <div className="df-profile-hero">
        <div className="df-profile-photo">
          {data?.photo
            ? <img src={api.proxyUrl(data.photo)} alt={data.name || actressName}/>
            : (
              <div className="df-model-placeholder">
                {(data?.name || actressName || '??').split(/\s+/).map(s => s[0]).join('').slice(0,2).toUpperCase()}
              </div>
            )
          }
        </div>
        <div className="df-profile-info">
          <h1 className="df-profile-name">{data?.name || actressName || 'Pornstar'}</h1>
          {data?.stats && Object.keys(data.stats).length > 0 && (
            <div className="df-profile-substats">
              {Object.entries(data.stats).slice(0, 4).map(([k, v]) => (
                <span key={k}><b>{v}</b> {k}</span>
              ))}
            </div>
          )}
        </div>
        <div className="df-profile-cta">
          <button onClick={() => {
            if (navigator.share) {
              navigator.share({ title: data?.name || actressName, url: window.location.href }).catch(() => {});
            } else if (navigator.clipboard) {
              navigator.clipboard.writeText(window.location.href);
            }
          }}><Icon.Share size={13}/> Condividi</button>
        </div>
      </div>

      {data?.stats && Object.keys(data.stats).length > 0 && (
        <div className="df-profile-stats-row">
          {Object.entries(data.stats).slice(0, 4).map(([k, v]) => (
            <div key={k} className="df-profile-stat">
              <div className="df-profile-stat-val">{v}</div>
              <div className="df-profile-stat-label">{k}</div>
            </div>
          ))}
        </div>
      )}

      <h2 className="df-section-title" style={{ marginTop: 0 }}>
        Video di {data?.name || actressName} {page > 1 ? `· pagina ${page}` : ''}
      </h2>
      <div className="df-filter-bar">
        {ACTRESS_FILTERS.map(f => (
          <button
            key={f.id}
            className={`df-filter-chip ${filterId === f.id ? 'active' : ''}`}
            onClick={() => onFilterChange(f.id)}
          >{f.label}</button>
        ))}
      </div>

      {loading ? (
        <div className="df-loading"><div className="df-spinner"/></div>
      ) : error ? (
        <div className="df-empty">
          <div className="df-empty-h">Errore</div>
          <div className="df-empty-p">{error}</div>
        </div>
      ) : (
        <>
          <VideoGrid
            videos={videos}
            onVideoClick={onVideoClick}
            onModelClick={onModelClick}
            watchLater={watchLater}
            emptyText="Nessun video"
          />
          {videos.length > 0 && (
            <Pagination
              page={page}
              onChange={onPageChange}
              hasNext={videos.length >= 20}
            />
          )}
        </>
      )}
    </main>
  );
}

/* ─── WatchLaterPage ────────────────────────────────────── */
function WatchLaterPage({ onVideoClick, onModelClick, watchLater }) {
  return (
    <main className="df-main">
      <div className="df-page-head">
        <h1 className="df-h1">Guarda dopo</h1>
        <div className="df-sub">
          {watchLater.items.length === 0
            ? 'Nessun video salvato'
            : `${watchLater.items.length} video salvati`}
        </div>
      </div>

      {watchLater.items.length === 0 ? (
        <div className="df-empty">
          <div className="df-empty-h">Nessun video salvato</div>
          <div className="df-empty-p">Tocca l'icona segnalibro su qualsiasi video per aggiungerlo qui.</div>
        </div>
      ) : (
        <VideoGrid
          videos={watchLater.items}
          onVideoClick={onVideoClick}
          onModelClick={onModelClick}
          watchLater={watchLater}
        />
      )}
    </main>
  );
}

/* ─── PornstarsPage ─────────────────────────────────────── */
function PornstarsPage({ onModelClick, onSubmitSearch }) {
  const [q, setQ] = useState('');
  return (
    <main className="df-main">
      <div className="df-page-head">
        <h1 className="df-h1">Pornstar</h1>
        <div className="df-sub">Cerca per nome per vedere il profilo di una pornstar.</div>
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (q.trim()) onSubmitSearch(q.trim());
        }}
        style={{ maxWidth: 460, marginBottom: 32, position: 'relative' }}
      >
        <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-mute)' }}>
          <Icon.Search size={16}/>
        </span>
        <input
          type="text"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Nome della pornstar..."
          style={{
            width: '100%',
            background: 'var(--bg-subtle)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--r-md)',
            padding: '12px 16px 12px 42px',
            fontSize: 14,
            color: 'var(--text)',
            outline: 'none',
          }}
        />
      </form>

      <div className="df-empty" style={{ paddingTop: 24, textAlign: 'left' }}>
        <div className="df-empty-h" style={{ textAlign: 'left' }}>Suggerimento</div>
        <div className="df-empty-p" style={{ textAlign: 'left', maxWidth: 480 }}>
          Usa la ricerca qui sopra o nella barra in alto. La ricerca scova sia video che pornstar
          corrispondenti. Cliccando sul nome di una pornstar (sotto un video o sui suoi risultati)
          si apre il suo profilo completo.
        </div>
      </div>
    </main>
  );
}

/* ─── CategoriesPage ────────────────────────────────────── */
function CategoriesPage({ onCategoryClick }) {
  return (
    <main className="df-main">
      <div className="df-page-head">
        <h1 className="df-h1">Categorie</h1>
        <div className="df-sub">Filtri rapidi su tutto il catalogo.</div>
      </div>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
          gap: 12,
        }}
      >
        {CATEGORIES.map(c => (
          <CategoryCard key={c.slug} category={c} onClick={() => onCategoryClick(c)}/>
        ))}
      </div>
    </main>
  );
}

Object.assign(window, {
  HomePage, SearchPage, VideoPage, ActressPage,
  WatchLaterPage, PornstarsPage, CategoriesPage,
  HOME_FILTERS, ACTRESS_FILTERS, CATEGORIES,
});
