// admin.jsx — Admin Dashboard

const { useState: useStateA } = React;

function AdminDashboardPage({ onNav, user }) {
  const [period, setPeriod] = useStateA('12');
  const adminUser = { name: user?.name || 'Andrei Popescu', role: 'Super Admin' };

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh', background: 'linear-gradient(135deg, #0A0A0F, #0E0E0E)' }}>
      <DashSidebar active="admin" onNav={onNav} user={adminUser} admin />
      <main style={{ padding: '32px 48px', overflowY: 'auto' }} className="dash-main">
        <AdminHeader user={adminUser} onNav={onNav} />
        <KpiGrid />
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 24 }} className="adm-row">
          <CreatorsChart period={period} setPeriod={setPeriod} />
          <CategoriesChart />
        </div>
        <ActivityFeed />
        <AlertsRow />
        <QuickStatsRow />
      </main>
      <style>{`
        @media (max-width: 1100px) { .adm-row { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

function AdminHeader({ user, onNav }) {
  const now = new Date(2026, 3, 26);
  const dayLabel = now.toLocaleDateString('ro-RO', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
  return (
    <div style={{ marginBottom: 32 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div className="pill" style={{ background: 'rgba(255,215,0,.08)', borderColor: 'rgba(255,215,0,.4)', color: 'var(--accent-2)', display: 'inline-flex', marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.15em' }}>● MOD ADMIN · DASHBOARD</span>
          </div>
          <h1 className="display" style={{ fontSize: 36, margin: 0 }}>Bună, <span style={{ color: 'var(--accent-2)' }}>{user.name.split(' ')[0]}</span> 👋</h1>
          <div className="mono" style={{ fontSize: 12, color: 'var(--txt-3)', marginTop: 6 }}>{dayLabel} · 14:32 · {user.role}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn btn-glass btn-sm" onClick={() => onNav('admin-products')}>+ Adaugă produs</button>
          <button className="btn btn-glass btn-sm">↑ Upload puncte lunare</button>
          <button className="btn btn-glass btn-sm">📊 Export raport</button>
        </div>
      </div>
    </div>
  );
}

function KpiGrid() {
  const items = [
    { ico: '👥', label: 'Creatori activi', val: 4847, sub: '+47 luna asta', subC: 'var(--accent-1)', click: 'admin-creators' },
    { ico: '📦', label: 'Comenzi în așteptare', val: 23, sub: 'Procesează →', subC: 'var(--accent-2)', click: 'admin-orders' },
    { ico: '💎', label: 'Puncte distribuite Apr', val: 124758, sub: 'Total în circulație: 2.4M', subC: 'var(--txt-3)' },
    { ico: '💰', label: 'Revenue lună (RON)', val: 487200, sub: '+18% vs. martie', subC: 'var(--accent-1)' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }} className="kpi-grid">
      {items.map((s, i) => (
        <div key={i} className="card" style={{ padding: 20, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 'auto -20% -50% auto', width: 120, height: 120, borderRadius: 999, background: 'rgba(255,215,0,.04)', filter: 'blur(40px)' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, position: 'relative' }}>
            <span style={{ fontSize: 18 }}>{s.ico}</span>
            <span className="mono" style={{ fontSize: 9, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>APR 2026</span>
          </div>
          <div className="display mono" style={{ fontSize: 30, lineHeight: 1, position: 'relative' }}>
            <Counter to={s.val} />
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--txt-2)', position: 'relative' }}>{s.label}</div>
          <div className="mono" style={{ marginTop: 4, fontSize: 10, color: s.subC, position: 'relative' }}>{s.sub}</div>
        </div>
      ))}
      <style>{`@media (max-width: 1100px) { .kpi-grid { grid-template-columns: 1fr 1fr !important; } }`}</style>
    </div>
  );
}

function CreatorsChart({ period, setPeriod }) {
  const data12 = [3200, 3380, 3520, 3680, 3840, 3950, 4080, 4220, 4400, 4560, 4720, 4847];
  const data6 = data12.slice(-6);
  const data24 = [...data12.map(d => d - 1200), ...data12];
  const map = { '6': data6, '12': data12, '24': data24 };
  const data = map[period];
  const labels12 = ['Mai','Iun','Iul','Aug','Sep','Oct','Noi','Dec','Ian','Feb','Mar','Apr'];
  const labels6 = labels12.slice(-6);
  const labels24 = ['Mai\'24', '...', '...', '...', '...', '...', '...', '...', '...', '...', '...', 'Mai\'25', '...', '...', '...', '...', '...', '...', '...', '...', '...', '...', 'Mar', 'Apr'];
  const labels = period === '6' ? labels6 : period === '12' ? labels12 : labels24;
  const max = Math.max(...data);
  const min = Math.min(...data);
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>● EVOLUȚIE CREATORI</div>
          <div className="display" style={{ fontSize: 22, marginTop: 6 }}>{period} luni · {data[data.length-1].toLocaleString('ro-RO')} activi</div>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          {['6', '12', '24'].map(p => (
            <button key={p} onClick={() => setPeriod(p)} className="btn btn-sm" style={{
              background: period === p ? 'var(--accent-1)' : 'transparent',
              color: period === p ? '#0A0A0F' : 'var(--txt-2)',
              border: period === p ? 'none' : '.5px solid var(--line)',
            }}>{p}L</button>
          ))}
        </div>
      </div>
      <div style={{ height: 200 }}>
        <svg viewBox="0 0 600 200" style={{ width: '100%', height: '100%', overflow: 'visible' }} preserveAspectRatio="none">
          <defs>
            <linearGradient id="admArea" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#52F20F" stopOpacity="0.35"/>
              <stop offset="100%" stopColor="#52F20F" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {[0, 0.25, 0.5, 0.75, 1].map(y => (
            <line key={y} x1="0" y1={200 * y} x2="600" y2={200 * y} stroke="#27272A" strokeDasharray="2 4" strokeWidth="0.5"/>
          ))}
          <path d={`M ${data.map((d, i) => `${(i / (data.length - 1)) * 600},${200 - ((d - min) / (max - min || 1)) * 170 - 10}`).join(' L ')} L 600,200 L 0,200 Z`} fill="url(#admArea)"/>
          <path d={`M ${data.map((d, i) => `${(i / (data.length - 1)) * 600},${200 - ((d - min) / (max - min || 1)) * 170 - 10}`).join(' L ')}`} stroke="#52F20F" strokeWidth="2" fill="none" strokeLinejoin="round" style={{ filter: 'drop-shadow(0 0 8px rgba(82,242,15,0.6))' }}/>
          {data.map((d, i) => (
            <circle key={i} cx={(i / (data.length - 1)) * 600} cy={200 - ((d - min) / (max - min || 1)) * 170 - 10} r={i === data.length - 1 ? 5 : 3} fill={i === data.length - 1 ? '#52F20F' : '#0E0E0E'} stroke="#52F20F" strokeWidth="2"/>
          ))}
        </svg>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, overflow: 'hidden' }}>
        {labels.filter((_, i) => period === '24' ? i % 4 === 0 : true).map((l, i) => (
          <span key={i} className="mono" style={{ fontSize: 9, color: 'var(--txt-3)' }}>{l}</span>
        ))}
      </div>
    </div>
  );
}

function CategoriesChart() {
  const cats = [
    { name: 'Tehnologie', pct: 38, c: '#52F20F' },
    { name: 'Modă', pct: 24, c: '#FFD700' },
    { name: 'Călătorii', pct: 18, c: '#52F20F' },
    { name: 'Experiențe', pct: 12, c: '#FFD700' },
    { name: 'Cosmetice', pct: 8, c: '#52F20F' },
  ];
  return (
    <div className="card" style={{ padding: 24 }}>
      <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>● TOP CATEGORII PRODUSE</div>
      <div className="display" style={{ fontSize: 22, marginTop: 6, marginBottom: 24 }}>Aprilie 2026</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, height: 160 }}>
        {cats.map((c, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <div className="mono" style={{ fontSize: 11, color: c.c }}>{c.pct}%</div>
            <div style={{
              width: '100%', height: `${c.pct * 3}px`, borderRadius: '6px 6px 0 0',
              background: `linear-gradient(180deg, ${c.c}, ${c.c}40)`,
              boxShadow: `0 0 16px ${c.c}40`, transition: 'all .8s',
            }} />
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 12 }}>
        {cats.map((c, i) => (
          <div key={i} style={{ flex: 1, fontSize: 10, color: 'var(--txt-3)', textAlign: 'center', lineHeight: 1.3 }}>{c.name}</div>
        ))}
      </div>
    </div>
  );
}

function ActivityFeed() {
  const acts = [
    { ico: '👤', txt: <><strong>Maria Iancu</strong> s-a înscris ca creator nou</>, t: 'acum 4 min' },
    { ico: '📦', txt: <>Comandă <strong>#ORD-2402</strong> finalizată — PS5 Slim livrată</>, t: 'acum 12 min' },
    { ico: '💎', txt: <>Puncte adăugate la <strong>4.247 creatori</strong> (actualizare lunară)</>, t: 'acum 1 oră' },
    { ico: '🎁', txt: <>Produs nou adăugat: <strong>MacBook Air M3</strong> (1.450 pts)</>, t: 'acum 2 ore' },
    { ico: '🤖', txt: <>AI Chat: <strong>47 conversații</strong> azi (rate +12%)</>, t: 'acum 3 ore' },
    { ico: '⚠️', txt: <>Stoc scăzut alertat: <strong>Geantă LV</strong> (2 buc.)</>, t: 'acum 4 ore' },
    { ico: '✉️', txt: <>Newsletter trimis către <strong>3.521 abonați</strong></>, t: 'azi 09:30' },
    { ico: '📈', txt: <>Cea mai bună zi a lunii: <strong>247 comenzi</strong></>, t: 'ieri' },
  ];
  return (
    <div className="card" style={{ padding: 24, marginTop: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>● ACTIVITATE RECENTĂ</div>
          <div className="display" style={{ fontSize: 20, marginTop: 6 }}>Ultimele acțiuni</div>
        </div>
        <a className="ulink" style={{ fontSize: 13 }}>Vezi toate →</a>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {acts.map((a, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderTop: i > 0 ? '.5px solid var(--line-soft)' : 'none' }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', display: 'grid', placeItems: 'center', fontSize: 14, flexShrink: 0 }}>{a.ico}</div>
            <div style={{ flex: 1, fontSize: 13 }}>{a.txt}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)' }}>{a.t}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AlertsRow() {
  const alerts = [
    { type: 'red', ico: '🔴', title: 'Stoc scăzut', msg: '3 produse au stoc <5', cta: 'Vezi produse' },
    { type: 'yellow', ico: '🟡', title: 'Comenzi neprocesate >3 zile', msg: '5 comenzi necesită atenție', cta: 'Procesează acum' },
    { type: 'green', ico: '🟢', title: 'Sistem OK', msg: 'Toate procesele rulează normal', cta: null },
    { type: 'blue', ico: '💡', title: 'Reminder', msg: 'Următoarea actualizare puncte: 5 mai 2026', cta: 'Setări' },
  ];
  const colors = {
    red: { bg: 'rgba(239,68,68,.06)', bd: 'rgba(239,68,68,.3)', c: '#ef4444' },
    yellow: { bg: 'rgba(255,215,0,.06)', bd: 'rgba(255,215,0,.3)', c: '#FFD700' },
    green: { bg: 'rgba(82,242,15,.06)', bd: 'rgba(82,242,15,.3)', c: '#52F20F' },
    blue: { bg: 'rgba(99,179,237,.06)', bd: 'rgba(99,179,237,.3)', c: '#63B3ED' },
  };
  return (
    <div style={{ marginTop: 24 }}>
      <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 12 }}>● ALERTE</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }} className="alert-grid">
        {alerts.map((a, i) => {
          const c = colors[a.type];
          return (
            <div key={i} className="card" style={{ padding: 16, background: c.bg, borderColor: c.bd }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 14 }}>{a.ico}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: c.c }}>{a.title}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--txt-2)', lineHeight: 1.5 }}>{a.msg}</div>
              {a.cta && <a className="ulink" style={{ fontSize: 11, marginTop: 8, display: 'inline-block', color: c.c }}>{a.cta} →</a>}
            </div>
          );
        })}
      </div>
      <style>{`@media (max-width: 1100px) { .alert-grid { grid-template-columns: 1fr 1fr !important; } }`}</style>
    </div>
  );
}

function QuickStatsRow() {
  const stats = [
    { label: 'Conversion înscriere', val: '4.2%', sub: '+0.3pp' },
    { label: 'Average order points', val: '285', sub: 'pts/comandă' },
    { label: 'Active AI chats today', val: '47', sub: 'în desfășurare' },
    { label: 'Newsletter abonați', val: '3.521', sub: '+47 azi' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 24 }} className="qs-grid">
      {stats.map((s, i) => (
        <div key={i} style={{ padding: 16, background: 'var(--bg-2)', borderRadius: 12, border: '.5px solid var(--line)' }}>
          <div className="display mono" style={{ fontSize: 22, color: 'var(--accent-2)' }}>{s.val}</div>
          <div style={{ fontSize: 12, color: 'var(--txt-2)', marginTop: 4 }}>{s.label}</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 2 }}>{s.sub}</div>
        </div>
      ))}
      <style>{`@media (max-width: 1100px) { .qs-grid { grid-template-columns: 1fr 1fr !important; } }`}</style>
    </div>
  );
}

window.AdminDashboardPage = AdminDashboardPage;
