// screen-dashboard.jsx — Admin dashboard
const { useState: useDashState } = React;

// smooth catmull-rom -> bezier path
function smoothPath(pts) {
  if (pts.length < 2) return '';
  let d = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i], p1 = pts[i], p2 = pts[i + 1], p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C ${c1x} ${c1y}, ${c2x} ${c2y}, ${p2[0]} ${p2[1]}`;
  }
  return d;
}

function LineChart() {
  const W = 600, H = 230, pad = 28;
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const cur = [3.2, 4.1, 3.6, 5.2, 6.1, 8.4, 10.2];
  const prev = [4.0, 3.4, 4.6, 4.2, 6.6, 7.0, 8.6];
  const max = 12;
  const toPts = (arr) => arr.map((v, i) => [pad + (i * (W - pad * 2)) / (days.length - 1), H - pad - (v / max) * (H - pad * 2)]);
  const cp = toPts(cur), pp = toPts(prev);
  const area = smoothPath(cp) + ` L ${cp[cp.length - 1][0]} ${H - pad} L ${cp[0][0]} ${H - pad} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto' }}>
      <defs>
        <linearGradient id="lc" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent-600)" stopOpacity=".22" />
          <stop offset="100%" stopColor="var(--accent-600)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 3, 6, 9, 12].map(v => {
        const y = H - pad - (v / max) * (H - pad * 2);
        return <g key={v}><line x1={pad} y1={y} x2={W - pad} y2={y} stroke="var(--line)" strokeDasharray="3 4" /><text x={4} y={y + 4} fontSize="10" fill="var(--ink-400)" fontWeight="600">{v}M</text></g>;
      })}
      <path d={area} fill="url(#lc)" />
      <path d={smoothPath(pp)} fill="none" stroke="var(--ink-300)" strokeWidth="2.4" strokeLinecap="round" />
      <path d={smoothPath(cp)} fill="none" stroke="var(--accent-600)" strokeWidth="3" strokeLinecap="round" />
      {cp.map((p, i) => i === 5 ? <g key={i}><circle cx={p[0]} cy={p[1]} r="5" fill="#fff" stroke="var(--accent-600)" strokeWidth="3" /><rect x={p[0] - 38} y={p[1] - 34} width="76" height="22" rx="6" fill="var(--ink-900)" /><text x={p[0]} y={p[1] - 19} fontSize="10.5" fill="#fff" textAnchor="middle" fontWeight="700">8,452,210</text></g> : null)}
      {days.map((d, i) => <text key={d} x={pad + (i * (W - pad * 2)) / 6} y={H - 6} fontSize="10.5" fill="var(--ink-400)" textAnchor="middle" fontWeight="600">{d}</text>)}
    </svg>
  );
}

function Donut({ segments, size = 160, thickness = 26, center }) {
  const r = (size - thickness) / 2, c = size / 2, circ = 2 * Math.PI * r;
  let off = 0;
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      <circle cx={c} cy={c} r={r} fill="none" stroke="var(--ink-100)" strokeWidth={thickness} />
      {segments.map((s, i) => {
        const len = (s.pct / 100) * circ;
        const el = <circle key={i} cx={c} cy={c} r={r} fill="none" stroke={s.color} strokeWidth={thickness}
          strokeDasharray={`${len} ${circ - len}`} strokeDashoffset={-off} strokeLinecap="round" transform={`rotate(-90 ${c} ${c})`} />;
        off += len; return el;
      })}
      {center && <text x={c} y={c + 6} fontSize="22" fontWeight="800" fill="var(--ink-900)" textAnchor="middle">{center}</text>}
    </svg>
  );
}

function DashboardScreen({ openIdea, openUser, votes = {}, onVote }) {
  const Icon = window.Icon;
  const [tab, setTab] = useDashState('Total Users');
  const [pending, setPending] = useDashState(window.IDEAS.filter(i => i.status === 'pending' || i.status === 'review').slice(0, 4).map(i => ({ ...i, decided: null })));
  const tabs = ['Total Users', 'Total Ideas', 'Active Users', 'Pending Ideas'];
  const decide = (id, v) => setPending(p => p.map(x => x.id === id ? { ...x, decided: v } : x));

  const adminStats = [
    { key: 'a', icon: 'bulb', label: 'Total ideas', value: '1,000', trend: 9, tint: '#0a66ff' },
    { key: 'b', icon: 'checkCircle', label: 'Published', value: '612', trend: 14, tint: '#15a564' },
    { key: 'c', icon: 'calendar', label: 'Pending review', value: '188', trend: -6, tint: '#e8930c' },
    { key: 'd', icon: 'users', label: 'Active users', value: '500', trend: 8, tint: '#6d5cf0' },
  ];

  return (
    <div className="page fade-in">
      <div className="page-head"><div><div className="page-title">Dashboard</div><div className="page-sub">Admin overview of idea activity and moderation queue.</div></div></div>

      <div className="stat-grid" style={{ marginBottom: 22 }}>{adminStats.map(s => <window.StatCard key={s.key} s={s} />)}</div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 18, marginBottom: 22 }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="spread" style={{ marginBottom: 6 }}>
            <div className="section-label">General statistics</div>
            <div style={{ display: 'flex', gap: 16, fontSize: 12.5, fontWeight: 700 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-600)' }}><i style={{ width: 9, height: 9, borderRadius: 9, background: 'var(--accent-600)' }} />Current week</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-400)' }}><i style={{ width: 9, height: 9, borderRadius: 9, background: 'var(--ink-300)' }} />Previous week</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 4, margin: '10px 0 16px' }}>
            {tabs.map(t => <button key={t} onClick={() => setTab(t)} style={{ fontSize: 13, fontWeight: 700, padding: '6px 12px', borderRadius: 8, color: tab === t ? 'var(--accent-700)' : 'var(--ink-400)', background: tab === t ? 'var(--accent-50)' : 'transparent' }}>{t}</button>)}
          </div>
          <LineChart />
        </div>

        <div className="card" style={{ padding: 22 }}>
          <div className="section-label" style={{ marginBottom: 16 }}>Ideas by status</div>
          <div style={{ display: 'grid', placeItems: 'center', marginBottom: 16 }}>
            <Donut segments={[{ pct: 55, color: '#15a564' }, { pct: 28, color: '#e8930c' }, { pct: 17, color: '#e23b56' }]} center="1.0k" />
          </div>
          {[['Published', '#15a564', 550], ['Pending', '#e8930c', 280], ['Rejected', '#e23b56', 170]].map(([l, c, v]) => (
            <div key={l} className="spread" style={{ padding: '8px 0' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, fontWeight: 600, color: 'var(--ink-600)' }}><i style={{ width: 9, height: 9, borderRadius: 3, background: c }} />{l}</span>
              <span className="tnum" style={{ fontWeight: 800, color: 'var(--ink-900)' }}>{window.fmt(v)}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr 1.1fr', gap: 18, marginBottom: 22 }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="section-label" style={{ marginBottom: 18 }}>Traffic by devices</div>
          {window.DEVICES.map(d => (
            <div key={d.name} style={{ marginBottom: 15 }}>
              <div className="spread" style={{ marginBottom: 7 }}><span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-600)' }}>{d.name}</span><span className="tnum" style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-800)' }}>{d.pct}%</span></div>
              <div style={{ height: 8, borderRadius: 99, background: 'var(--ink-100)', overflow: 'hidden' }}><div style={{ width: `${d.pct}%`, height: '100%', borderRadius: 99, background: d.color }} /></div>
            </div>
          ))}
        </div>

        <div className="card" style={{ padding: 22 }}>
          <div className="section-label" style={{ marginBottom: 14 }}>Users by gender</div>
          <div style={{ display: 'grid', placeItems: 'center' }}><Donut segments={[{ pct: 75, color: '#6d5cf0' }, { pct: 25, color: '#f4623a' }]} center="75%" /></div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 18, marginTop: 14 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: 'var(--ink-600)' }}><i style={{ width: 9, height: 9, borderRadius: 9, background: '#6d5cf0' }} />Male</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: 'var(--ink-600)' }}><i style={{ width: 9, height: 9, borderRadius: 9, background: '#f4623a' }} />Female</span>
          </div>
        </div>

        <div className="card" style={{ padding: 22 }}>
          <div className="section-label" style={{ marginBottom: 14 }}>Most interactive users</div>
          {window.TOP_USERS.map((u, i) => (
            <div key={u.name} className="spread" style={{ padding: '9px 0', gap: 10, cursor: 'pointer', borderRadius: 8 }} onClick={() => openUser && openUser(u)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
                <window.Avatar src={u.av} size={36} />
                <div style={{ minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-900)', whiteSpace: 'nowrap' }}>{u.name}</div><div className="muted" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>{u.role}</div></div>
              </div>
              <span className="tnum" style={{ fontSize: 13, fontWeight: 700, color: 'var(--accent-700)', background: 'var(--accent-50)', padding: '4px 9px', borderRadius: 8, flex: 'none' }}>{u.ideas}</span>
            </div>
          ))}
        </div>
      </div>

      {/* pending approvals */}
      <div className="table-card" style={{ marginBottom: 22 }}>
        <div className="table-head-row"><div className="section-label">Last pending ideas</div><button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }}>Show all</button></div>
        <table className="tbl">
          <thead><tr><th style={{ width: 56 }}>#</th><th>Username</th><th>Idea title</th><th>Category</th><th>Status</th><th style={{ width: 120 }}>Action</th></tr></thead>
          <tbody>
            {pending.map(p => (
              <tr key={p.id}>
                <td className="rank tnum">#{p.rank}</td>
                <td><div className="user-cell"><window.Avatar src={p.avatar} size={36} /><b>{p.author}</b></div></td>
                <td><span className="idea-link" onClick={() => openIdea(p)}>{p.title}</span></td>
                <td><window.CatChip name={p.category} /></td>
                <td>{p.decided === 'approve' ? <window.StatusBadge status="published" /> : p.decided === 'reject' ? <window.StatusBadge status="rejected" /> : <window.StatusBadge status="pending" />}</td>
                <td>
                  {p.decided ? <span className="muted" style={{ fontSize: 13, fontWeight: 600 }}>{p.decided === 'approve' ? 'Approved' : 'Rejected'}</span> : (
                    <div style={{ display: 'flex', gap: 8 }}>
                      <button onClick={() => decide(p.id, 'approve')} style={{ color: 'var(--success)' }} title="Approve"><Icon name="checkCircle" size={26} /></button>
                      <button onClick={() => decide(p.id, 'reject')} style={{ color: 'var(--danger)' }} title="Reject"><Icon name="xCircle" size={26} /></button>
                    </div>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="table-card">
        <div className="table-head-row"><div className="section-label">Recent ideas</div><button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }}>Show all</button></div>
        <table className="tbl">
          <thead><tr><th style={{ width: 56 }}>#</th><th>Username</th><th>Idea title</th><th>Category</th><th>Statistics</th></tr></thead>
          <tbody>
            {window.IDEAS.slice(0, 4).map(i => (
              <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={36} /><b>{i.author}</b></div></td>
                <td><span className="idea-link">{i.title}</span></td>
                <td><window.CatChip name={i.category} /></td>
                <td><window.StatChips idea={i} vote={votes[i.id]} onVote={(d) => onVote(i.id, d)} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
window.DashboardScreen = DashboardScreen;
