// screen-home.jsx — fetches ideas from the real API
const { useState: useHomeState, useEffect: useHomeEffect } = React;

function HomeScreen({ search, currentUser, votes, onVote, openIdea }) {
  const Icon = window.Icon;
  const [cats, setCats] = useHomeState(['All']);
  const [cat, setCat] = useHomeState('All');
  const [sort, setSort] = useHomeState('rank');
  const [sortOpen, setSortOpen] = useHomeState(false);
  const [page, setPage] = useHomeState(1);
  const [perPage, setPerPage] = useHomeState(6);
  const [ideas, setIdeas] = useHomeState([]);
  const [total, setTotal] = useHomeState(0);
  const [loading, setLoading] = useHomeState(false);

  useHomeEffect(() => {
    window.API.getCategories()
      .then(cs => setCats(['All', ...cs.map(c => c.name)]))
      .catch(() => setCats(['All', ...window.CATEGORIES.map(c => c.name)]));
  }, []);

  useHomeEffect(() => {
    let cancelled = false;
    setLoading(true);
    const params = { page, per: perPage, sort };
    if (cat !== 'All') params.category = cat;
    if (search.trim()) params.search = search.trim();
    window.API.getIdeas(params)
      .then(res => { if (!cancelled) { setIdeas(res.ideas); setTotal(res.total); } })
      .catch(() => {})
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [cat, sort, page, perPage, search]);

  const pages = Math.max(1, Math.ceil(total / perPage));
  const cur = Math.min(page, pages);
  const sortLabels = { rank: 'Default order', top: 'Most upvoted', views: 'Most viewed' };

  const norm = (i) => ({
    ...i,
    up: Number(i.up_votes ?? i.up ?? 0),
    down: Number(i.down_votes ?? i.down ?? 0),
    comments: Number(i.comment_count ?? i.comments ?? 0),
    date: i.date || (i.created_at ? new Date(i.created_at).toLocaleDateString('en-GB') : ''),
    rank: Number(i.rank ?? i.id),
    desc: i.description || i.desc || '',
  });

  const firstName = currentUser?.name?.split(' ')[0] || 'there';

  return (
    <div className="page fade-in">
      <div className="page-head">
        <div>
          <div className="page-title">Welcome back, {firstName}</div>
          <div className="page-sub">Here's what's happening across the idea pool this week.</div>
        </div>
      </div>

      <div className="spread" style={{ marginBottom: 14 }}>
        <div className="section-label">This week</div>
      </div>
      <div className="stat-grid" style={{ marginBottom: 30 }}>
        {window.STATS_HOME.map(s => <window.StatCard key={s.key} s={s} />)}
      </div>

      <div className="table-card">
        <div className="table-head-row">
          <div className="section-label">Ideas</div>
          <div className="table-tools">
            <div className="chip-row">
              {cats.map(c => (
                <button key={c} className={`chip ${cat === c ? 'active' : ''}`} onClick={() => { setCat(c); setPage(1); }}>{c}</button>
              ))}
            </div>
            <div style={{ position: 'relative' }}>
              <button className="chip" onClick={() => setSortOpen(o => !o)}><Icon name="sort" size={16} />{sortLabels[sort]}<Icon name="chevDown" size={15} /></button>
              {sortOpen && (
                <div style={{ position: 'absolute', right: 0, top: 42, background: 'var(--pop-bg)', border: '1px solid var(--line)', borderRadius: 12, boxShadow: 'var(--sh-lg)', padding: 6, zIndex: 40, minWidth: 170 }}>
                  {Object.entries(sortLabels).map(([k, v]) => (
                    <button key={k} onClick={() => { setSort(k); setSortOpen(false); setPage(1); }} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 12px', borderRadius: 8, fontSize: 13.5, fontWeight: 600, color: sort === k ? 'var(--accent-700)' : 'var(--ink-600)', background: sort === k ? 'var(--accent-50)' : 'transparent' }}>{v}</button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 56 }}>#</th><th>Username</th><th>Idea title</th>
              <th>Category</th><th>Description</th><th>Statistics</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 40, color: 'var(--ink-400)' }}>Loading…</td></tr>
            )}
            {!loading && ideas.map(raw => {
              const i = norm(raw);
              return (
                <tr key={i.id} className="clickable" onClick={() => openIdea(i)}>
                  <td className="rank tnum">#{i.rank}</td>
                  <td><div className="user-cell"><window.Avatar src={i.avatar} size={38} /><b style={{ whiteSpace: 'nowrap' }}>{i.author}</b></div></td>
                  <td><span className="idea-link">{i.title}</span></td>
                  <td><window.CatChip name={i.category} /></td>
                  <td><div className="desc-cell">{i.desc}</div></td>
                  <td><window.StatChips idea={i} vote={votes[i.id]} onVote={(d) => onVote(i.id, d)} /></td>
                </tr>
              );
            })}
            {!loading && ideas.length === 0 && (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 48, color: 'var(--ink-400)' }}>No ideas match your filters.</td></tr>
            )}
          </tbody>
        </table>

        <div className="pager">
          <div className="per">Per page:
            <select value={perPage} onChange={e => { setPerPage(+e.target.value); setPage(1); }}>
              <option value={6}>6</option><option value={8}>8</option><option value={12}>12</option>
            </select>
          </div>
          <div className="pages">
            <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={cur === 1}><Icon name="chevLeft" size={16} /></button>
            {Array.from({ length: pages }).map((_, idx) => (
              <button key={idx} className={cur === idx + 1 ? 'active' : ''} onClick={() => setPage(idx + 1)}>{idx + 1}</button>
            ))}
            <button onClick={() => setPage(p => Math.min(pages, p + 1))} disabled={cur === pages} style={{ fontWeight: 700, color: 'var(--ink-500)' }}>Next</button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.HomeScreen = HomeScreen;
