// Dashboard: main table view
const { useState: useStateD, useMemo: useMemoD, useEffect: useEffectD } = React;

function Dashboard({ people, statsPeople, filters, setFilters, onOpen, onExport, locks = {} }) {
  const [visibleCount, setVisibleCount] = useStateD(20);

  const rows = useMemoD(() => {
    console.log('Dashboard computing rows, people:', people, 'isArray:', Array.isArray(people));
    if (!Array.isArray(people)) return [];
    let r = people.map(p => ({
      ...p,
      counts: computeCounts(p, PLATFORMS),
      profCounts: computeProfileCounts(p),
    }));
    console.log('Mapped rows before filtering:', r);
    if (filters.q) {
      const q = filters.q.toLowerCase();
      r = r.filter(p =>
        (p.name || '').toLowerCase().includes(q) ||
        (p.category || '').toLowerCase().includes(q) ||
        (p.country || '').toLowerCase().includes(q)
      );
    }
    if (filters.status !== 'all') {
      r = r.filter(p => {
        const profPending = p.profCounts.unverified > 0 || p.profCounts.verified > 0;
        const profDone = p.profCounts.qc === p.profCounts.total;
        if (filters.status === 'complete') return p.counts.complete && profDone;
        if (filters.status === 'review')   return p.counts.unverified > 0 || p.counts.missing > 0 || p.profCounts.unverified > 0; // Include missing in review
        if (filters.status === 'qc')       return (p.counts.verified > 0 || p.profCounts.verified > 0) && !(p.counts.complete && profDone);
        if (filters.status === 'attrs')    return profPending;
        return true;
      });
    }
    if (filters.source !== 'all') r = r.filter(p => p.source === filters.source);
    console.log('Final filtered rows:', r);
    return r;
  }, [people, filters]);

  useEffectD(() => {
    setVisibleCount(20);
  }, [people, filters.q, filters.status, filters.source]);

  const visibleRows = useMemoD(() => rows.slice(0, visibleCount), [rows, visibleCount]);

  const onTableScroll = (e) => {
    const el = e.currentTarget;
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120) {
      setVisibleCount(v => Math.min(v + 20, rows.length));
    }
  };

  // Global stats
  const totals = useMemoD(() => {
    const basePeople = (Array.isArray(statsPeople) && statsPeople.length > 0) ? statsPeople : people;
    if (!Array.isArray(basePeople)) return { ppl: 0, complete: 0, review: 0, qc: 0, gaps: 0, attrs: 0, handles: 0, verifiedHandles: 0, attrTotal: 0, attrDone: 0 };
    const t = { ppl: basePeople.length, complete: 0, review: 0, qc: 0, gaps: 0, attrs: 0,
                handles: 0, verifiedHandles: 0, attrTotal: 0, attrDone: 0 };
    for (const p of basePeople) {
      const c = computeCounts(p, PLATFORMS);
      const pc = computeProfileCounts(p);
      t.handles += c.total;
      t.verifiedHandles += c.qc + c['non-existing'];
      t.attrTotal += pc.total;
      t.attrDone  += pc.qc;
      const profDone = pc.qc === pc.total;
      const profPending = pc.unverified > 0 || pc.verified > 0;
      if (profPending) t.attrs++;
      if (c.complete && profDone) t.complete++;
      else if (c.unverified > 0 || c.missing > 0 || pc.unverified > 0) t.review++;
      if ((c.verified > 0 || pc.verified > 0) && !(c.complete && profDone)) t.qc++;
      // Remove gaps counting since missing is now treated as needs review
    }
    return t;
  }, [people, statsPeople]);

  const statusChips = [
    { id: 'all',      label: 'All',                count: totals.ppl },
    { id: 'review',   label: 'Needs review',       count: totals.review },
    { id: 'attrs',    label: 'Profile mismatch',   count: totals.attrs },
    { id: 'qc',       label: 'Ready for QC',       count: totals.qc },
    { id: 'complete', label: 'Complete',           count: totals.complete },
  ];

  return (
    <>
      <div className="filters">
        <div className="search">
          <Icon name="search" size={14} stroke="var(--muted)"/>
          <input
            placeholder="Search by name or category…"
            value={filters.q}
            onChange={e => setFilters({ ...filters, q: e.target.value })}
          />
          <button
            className="kbd"
            type="button"
            onClick={() => setFilters({ ...filters, q: '' })}
            title="Clear search"
            aria-label="Clear search"
          >
            X
          </button>
        </div>

        {statusChips.map(c => (
          <button key={c.id}
            className={`chip ${filters.status === c.id ? 'active' : ''}`}
            onClick={() => setFilters({ ...filters, status: c.id })}>
            {c.label} <span className="count">{c.count}</span>
          </button>
        ))}

        <div className="spacer"/>

        <select className="chip" value={filters.source}
                onChange={e => setFilters({ ...filters, source: e.target.value })}
                style={{appearance: 'none', paddingRight: 22}}>
          <option value="all">All sources</option>
          <option value="SportsTool">SportsTool</option>
          <option value="CultureTool">CultureTool</option>
        </select>

        <button className="btn" onClick={onExport}>
          <Icon name="export" size={13}/> Export
        </button>
      </div>

      {/* progress strip */}
      <div className="progress-strip">
        <div className="stat">
          <span className="dot" style={{background: '#16A34A'}}/>
          <b>{totals.complete}</b> complete
        </div>
        <div className="stat">
          <span className="dot" style={{background: '#D97706'}}/>
          <b>{totals.review}</b> need review
        </div>
        <div className="stat" title="People with country/category that needs verifying">
          <span className="dot" style={{background: '#EA580C'}}/>
          <b>{totals.attrs}</b> profile checks
        </div>
        <div className="stat">
          <span className="dot" style={{background: '#84CC16'}}/>
          <b>{totals.qc}</b> ready for QC
        </div>
        <div className="stat">
          <span className="dot" style={{background: '#DC2626'}}/>
          <b>{totals.gaps}</b> have gaps
        </div>
        <div className="progress-bar" title={`${totals.verifiedHandles + totals.attrDone} / ${totals.handles + totals.attrTotal} items locked in`}>
          <span style={{background: '#16A34A', flex: totals.verifiedHandles + totals.attrDone }}/>
          <span style={{background: 'transparent', flex: (totals.handles + totals.attrTotal) - (totals.verifiedHandles + totals.attrDone) }}/>
        </div>
        <div className="stat">
          <b>{Math.round((totals.verifiedHandles + totals.attrDone) / (totals.handles + totals.attrTotal) * 100)}%</b> locked
        </div>
      </div>

      <div className="legend">
        <span className="lg-item"><Tile platform="instagram" status="unverified" /> To review</span>
        <span className="lg-item"><Tile platform="instagram" status="verified" /> Verified</span>
        <span className="lg-item"><Tile platform="instagram" status="qc" /> QC passed</span>
        <span className="lg-item"><Tile platform="instagram" status="non-existing" /> No account</span>
        <span className="lg-item"><Tile platform="instagram" status="missing" /> Missing</span>
        <div className="spacer"/>
        <span>Click any row to open</span>
      </div>

      <div className="scroll table-wrap" onScroll={onTableScroll}>
        <table className="data">
          <thead>
            <tr>
              <th style={{width: 32, paddingLeft: 16}}></th>
              <th style={{width: 300}}>Name</th>
              <th style={{width: 130}}>Category</th>
              <th style={{width: 130}}>Country</th>
              <th style={{width: 230}}>Platforms</th>
              <th style={{width: 130}}>Progress</th>
              <th style={{width: 140}}>Status</th>
              <th style={{width: 48}}></th>
            </tr>
          </thead>
          <tbody>
            {visibleRows.map((p, i) => {
              const pcCombined = {
                ...p.counts,
                // Roll profile pending into the overall status pill
                unverified: p.counts.unverified + p.profCounts.unverified,
                verified: p.counts.verified + p.profCounts.verified,
                complete: p.counts.complete && p.profCounts.qc === p.profCounts.total,
              };
              const o = overallStatus(pcCombined);
              const totalAll = p.counts.total + p.profCounts.total;
              const doneAll  = p.counts.qc + p.counts['non-existing'] + p.profCounts.qc;
              const pct = doneAll / totalAll;
              const profUnv = p.profCounts.unverified;
              const profVer = p.profCounts.verified;
              return (
                <tr key={p.id} onClick={() => onOpen(p.id)}>
                  <td style={{paddingLeft: 16, color: 'var(--muted-2)', fontVariantNumeric: 'tabular-nums', fontSize: 11}}>{String(i+1).padStart(2,'0')}</td>
                  <td>
                    <div className="nm">
                      <div className="nmavatar">{p.name.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
                      <div>
                        <div style={{display:'inline-flex', alignItems:'center', gap:6}}>
                          <span>{p.name}</span>
                          {locks[p.id] && <LockChip lock={locks[p.id]}/>}
                        </div>
                        <div style={{fontSize: 11, color: 'var(--muted)', marginTop: 1}}>{p.source}</div>
                      </div>
                    </div>
                  </td>
                  <td className="muted">
                    {p.category}
                    {profUnv > 0 && p.profile?.category?.status === 'unverified' && (
                      <span className="attr-flag" title={p.profile.category.note || 'Category needs review'}>!</span>
                    )}
                  </td>
                  <td className="muted">
                    {p.country}
                    {profUnv > 0 && p.profile?.country?.status === 'unverified' && (
                      <span className="attr-flag" title={p.profile.country.note || 'Country needs review'}>!</span>
                    )}
                  </td>
                  <td>
                    <div className="tile-row">
                      {PLATFORMS.map(pl => {
                        const handles = p.handles[pl.id];
                        const displayHandle = Array.isArray(handles) ? getMostAdvancedStatus(handles) : handles;
                        return (
                          <Tile key={pl.id}
                            platform={pl.id}
                            status={displayHandle.status}
                            title={`${pl.name}: ${STATUS_META[displayHandle.status].label}${Array.isArray(handles) && handles.length > 1 ? ` (${handles.length} handles)` : ''}`}
                          />
                        );
                      })}
                    </div>
                  </td>
                  <td>
                    <span className="ratio">
                      <span className="bar">
                        <span style={{flex: pct, background: pcCombined.complete ? '#16A34A' : 'var(--accent)'}}/>
                        <span style={{flex: 1-pct, background: 'transparent'}}/>
                      </span>
                      <span style={{fontSize: 11, color: 'var(--muted)'}}>{doneAll}/{totalAll}</span>
                    </span>
                  </td>
                  <td>
                    <Pill kind={o.kind} dot>{o.label}</Pill>
                  </td>
                  <td style={{color: 'var(--muted-2)', textAlign: 'right', paddingRight: 16}}>
                    <Icon name="chevR" size={14}/>
                  </td>
                </tr>
              );
            })}
            {rows.length === 0 && (
              <tr><td colSpan={8}><div className="empty"><div className="big">No records match those filters</div>Try clearing the search or switching the status chip.</div></td></tr>
            )}
          </tbody>
        </table>
      </div>

      {rows.length > 0 && (
        <div style={{fontSize: 12, color: 'var(--muted)', marginTop: 8}}>
          Showing {Math.min(visibleCount, rows.length)} of {rows.length} records
        </div>
      )}
    </>
  );
}

window.Dashboard = Dashboard;
