// dashboard.jsx — Creator dashboard

const { useState: useStateD } = React;

function DashboardPage({ onNav, user }) {
  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh' }}>
      <DashSidebar active="dashboard" onNav={onNav} user={user} />
      <main style={{ padding: '32px 48px', overflowY: 'auto', background: 'var(--bg-1)' }} className="dash-main">
        <DashHeader user={user} />
        <PointsCard onNav={onNav} />
        <StatsGrid />
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 24 }} className="dash-row">
          <PointsHistory />
          <Achievements />
        </div>
        <RecentOrders />
        <ReferralBanner />
      </main>
      <style>{`
        @media (max-width: 1100px) { .dash-row { grid-template-columns: 1fr !important; }}
        @media (max-width: 900px) { .dash-main { padding: 24px !important; }}
      `}</style>
    </div>
  );
}

function DashSidebar({ active, onNav, user, admin }) {
  const items = admin ? [
    { id: 'admin', icon: '⚡', label: 'Dashboard' },
    { id: 'admin-creators', icon: '👥', label: 'Creatori' },
    { id: 'admin-points', icon: '💎', label: 'Actualizare puncte' },
    { id: 'admin-products', icon: '🎁', label: 'Produse' },
    { id: 'admin-orders', icon: '📦', label: 'Comenzi' },
    { id: 'admin-ai', icon: '🤖', label: 'AI Chat' },
    { id: 'admin-stats', icon: '📊', label: 'Statistici' },
  ] : [
    { id: 'dashboard', icon: '◆', label: 'Dashboard' },
    { id: 'chat', icon: '✦', label: 'Chat AI' },
    { id: 'shop', icon: '◇', label: 'Cadouri', badge: 'Nou' },
    { id: 'orders', icon: '▣', label: 'Istoric comenzi' },
    { id: 'profile', icon: '◉', label: 'Profil' },
  ];

  return (
    <aside style={{
      background: '#08080C', borderRight: '.5px solid var(--line-soft)',
      padding: 20, display: 'flex', flexDirection: 'column', position: 'sticky', top: 0, height: '100vh',
    }} className="dash-sidebar">
      <div onClick={() => onNav('home')} style={{ cursor: 'pointer', padding: '8px 0 24px' }}><Logo size={28} /></div>
      {!admin && (
        <div style={{ background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 12, padding: 14, display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
          <div style={{ width: 40, height: 40, borderRadius: 999, background: 'linear-gradient(135deg, var(--accent-2), var(--accent-1))', flexShrink: 0 }} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user?.name || 'Andra M.'}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--accent-1)', letterSpacing: '0.1em' }}>● DIAMOND</div>
          </div>
        </div>
      )}
      {admin && (
        <div style={{ background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 10, padding: '8px 12px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--accent-1)', letterSpacing: '0.1em' }}>● ADMIN</span>
          <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--txt-2)' }}>{user?.name || 'Andrei P.'}</span>
        </div>
      )}
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
        {items.map(it => (
          <button key={it.id} onClick={() => onNav(it.id)} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
            borderRadius: 8, border: 0, cursor: 'pointer', background: active === it.id ? 'rgba(82,242,15,.08)' : 'transparent',
            color: active === it.id ? 'var(--accent-1)' : 'var(--txt-2)', fontSize: 14, textAlign: 'left',
            fontFamily: 'inherit', transition: 'all .18s', position: 'relative',
          }} onMouseEnter={(e) => { if (active !== it.id) e.currentTarget.style.color = 'var(--txt-0)'; }}
             onMouseLeave={(e) => { if (active !== it.id) e.currentTarget.style.color = 'var(--txt-2)'; }}>
            {active === it.id && <span style={{ position: 'absolute', left: -20, top: '50%', transform: 'translateY(-50%)', width: 3, height: 18, background: 'var(--accent-1)', borderRadius: 2 }}/>}
            <span style={{ width: 18, fontSize: 14 }}>{it.icon}</span>
            <span style={{ flex: 1 }}>{it.label}</span>
            {it.badge && <span className="pill" style={{ padding: '2px 6px', fontSize: 9, background: 'rgba(255,215,0,.12)', borderColor: 'rgba(255,215,0,.3)', color: 'var(--accent-2)' }}>{it.badge}</span>}
          </button>
        ))}
      </nav>
      <div style={{ borderTop: '.5px solid var(--line-soft)', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <button onClick={() => onNav('home')} style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
          borderRadius: 8, border: 0, cursor: 'pointer', background: 'transparent',
          color: 'var(--txt-3)', fontSize: 13, textAlign: 'left', fontFamily: 'inherit',
        }}>
          <span style={{ width: 18 }}>↗</span>Vezi site-ul
        </button>
        <button onClick={() => onNav('home')} style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
          borderRadius: 8, border: 0, cursor: 'pointer', background: 'transparent',
          color: 'var(--txt-3)', fontSize: 13, textAlign: 'left', fontFamily: 'inherit',
        }}>
          <span style={{ width: 18 }}>⏻</span>Logout
        </button>
      </div>
    </aside>
  );
}

function DashHeader({ user }) {
  const now = new Date(2026, 3, 26);
  const day = now.toLocaleDateString('ro-RO', { weekday: 'long', day: 'numeric', month: 'long' });
  return (
    <div style={{ marginBottom: 32, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
      <div>
        <h1 className="display" style={{ fontSize: 36, margin: 0 }}>Bună, <span style={{ color: 'var(--accent-1)' }}>{user?.name?.split(' ')[0] || 'Andra'}</span> 👋</h1>
        <div className="mono" style={{ fontSize: 12, color: 'var(--txt-3)', marginTop: 6 }}>Ultima actualizare puncte: 1 aprilie 2026 · {day}</div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn btn-glass btn-sm">🔔 <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent-1)', boxShadow: '0 0 8px var(--accent-1)' }}/></button>
        <button className="btn btn-glass btn-sm">⚙</button>
      </div>
    </div>
  );
}

function PointsCard({ onNav }) {
  const points = 1247;
  const expDays = 23; // simulated
  const expColor = expDays < 30 ? '#F59E0B' : 'var(--accent-1)';
  return (
    <div className="card-glass" style={{ padding: 32, position: 'relative', overflow: 'hidden', marginBottom: 24 }}>
      <div className="mesh" style={{ inset: 'auto -10% -50% auto', width: '60%', height: '200%', opacity: 0.6 }} />
      <div style={{ position: 'relative', zIndex: 2, display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'center' }} className="pts-grid">
        <div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 12 }}>● PUNCTELE TALE 4U</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 16 }}>
            <div className="display mono" style={{ fontSize: 'clamp(56px, 8vw, 96px)', lineHeight: 1, color: 'var(--accent-1)', textShadow: '0 0 60px rgba(82,242,15,.3)' }}>
              <Counter to={points} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <span className="display" style={{ fontSize: 18, color: 'var(--txt-2)' }}>4U Points</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--success)' }}>+247 luna asta</span>
            </div>
          </div>
          <div style={{ marginTop: 24, maxWidth: 480 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 }}>
              <span style={{ color: expColor }}>⚠ Expiră în {expDays} zile (19 mai 2026)</span>
              <span className="mono" style={{ color: 'var(--txt-3)' }}>{Math.round((expDays / 30) * 100)}%</span>
            </div>
            <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-3)', overflow: 'hidden' }}>
              <div style={{ width: `${(expDays / 30) * 100}%`, height: '100%', background: `linear-gradient(90deg, var(--accent-1), ${expColor})`, transition: 'width 1s' }}/>
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <button className="btn btn-primary btn-lg" onClick={() => onNav('shop')}>Mergi la Cadouri →</button>
          <button className="btn btn-glass" onClick={() => onNav('orders')}>Istoric comenzi</button>
        </div>
      </div>
      <style>{`@media (max-width: 800px) { .pts-grid { grid-template-columns: 1fr !important; }}`}</style>
    </div>
  );
}

function StatsGrid() {
  const items = [
    { ico: '💎', label: 'Diamante luna', val: 124758, sub: '+18% vs. martie' },
    { ico: '⏱', label: 'Ore live', val: 84, suf: 'h', sub: '21 zile active' },
    { ico: '📅', label: 'Zile active', val: 21, suf: '/30', sub: 'streak personal' },
    { ico: '🏆', label: 'Rang Hall of Fame', val: 1, pre: '#', sub: 'în Diamond tier' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }} className="stat4-grid">
      {items.map((s, i) => (
        <div key={i} className="card" style={{ padding: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
            <span style={{ fontSize: 18, opacity: 0.6 }}>{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: 32, lineHeight: 1 }}>
            <Counter to={s.val} prefix={s.pre || ''} suffix={s.suf || ''} />
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--txt-2)' }}>{s.label}</div>
          <div className="mono" style={{ marginTop: 4, fontSize: 10, color: 'var(--txt-3)' }}>{s.sub}</div>
        </div>
      ))}
      <style>{`@media (max-width: 1100px) { .stat4-grid { grid-template-columns: 1fr 1fr !important; }}`}</style>
    </div>
  );
}

function PointsHistory() {
  const data = [380, 420, 510, 620, 580, 720, 890, 1050, 1180, 1090, 1247];
  const max = Math.max(...data);
  const labels = ['Iun','Iul','Aug','Sep','Oct','Noi','Dec','Ian','Feb','Mar','Apr'];
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Evoluție puncte</div>
          <div className="display" style={{ fontSize: 22, marginTop: 6 }}>Ultimele 11 luni</div>
        </div>
        <div className="pill"><span className="mono" style={{ fontSize: 10 }}>+227% YoY</span></div>
      </div>
      <div style={{ position: 'relative', height: 180 }}>
        <svg viewBox="0 0 600 180" style={{ width: '100%', height: '100%', overflow: 'visible' }} preserveAspectRatio="none">
          <defs>
            <linearGradient id="ptsArea" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#52F20F" stopOpacity="0.3"/>
              <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={180 * y} x2="600" y2={180 * y} stroke="#27272A" strokeDasharray="2 4" strokeWidth="0.5"/>
          ))}
          <path d={`M ${data.map((d, i) => `${(i / (data.length - 1)) * 600},${180 - (d / max) * 160}`).join(' L ')} L 600,180 L 0,180 Z`} fill="url(#ptsArea)"/>
          <path d={`M ${data.map((d, i) => `${(i / (data.length - 1)) * 600},${180 - (d / max) * 160}`).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={180 - (d / max) * 160} 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 }}>
        {labels.map((l, i) => (
          <span key={l} className="mono" style={{ fontSize: 9, color: i === labels.length - 1 ? 'var(--accent-1)' : 'var(--txt-3)' }}>{l}</span>
        ))}
      </div>
    </div>
  );
}

function Achievements() {
  const badges = [
    { ico: '🥉', label: 'First Live', unlocked: true },
    { ico: '🥈', label: '100h streamed', unlocked: true },
    { ico: '🥇', label: '1M diamonds', unlocked: true },
    { ico: '💎', label: '5M diamonds', unlocked: true, glow: true },
    { ico: '👑', label: 'Top 10 RO', unlocked: false, progress: 78 },
    { ico: '🌍', label: 'Global Top 100', unlocked: false, progress: 32 },
  ];
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Realizări</div>
          <div className="display" style={{ fontSize: 22, marginTop: 6 }}>4 / 6 deblocate</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {badges.map((b, i) => (
          <div key={i} style={{
            background: b.unlocked ? 'rgba(82,242,15,.06)' : 'var(--bg-3)',
            border: '.5px solid', borderColor: b.unlocked ? 'rgba(82,242,15,.25)' : 'var(--line)',
            borderRadius: 10, padding: 12, textAlign: 'center', position: 'relative',
            opacity: b.unlocked ? 1 : 0.55, transition: 'all .25s',
            boxShadow: b.glow ? '0 0 16px rgba(82,242,15,.3)' : 'none',
          }}>
            <div style={{ fontSize: 24, filter: b.unlocked ? 'none' : 'grayscale(1)' }}>{b.ico}</div>
            <div style={{ fontSize: 11, marginTop: 6, color: b.unlocked ? 'var(--txt-1)' : 'var(--txt-3)' }}>{b.label}</div>
            {!b.unlocked && b.progress != null && (
              <div style={{ marginTop: 8, height: 2, borderRadius: 1, background: 'var(--bg-1)', overflow: 'hidden' }}>
                <div style={{ width: b.progress + '%', height: '100%', background: 'var(--accent-1)' }}/>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function RecentOrders() {
  const orders = [
    { date: '12 apr', name: 'iPhone 15 Pro', pts: 850, status: 'Expediată' },
    { date: '4 apr', name: 'Sony WH-1000XM5', pts: 320, status: 'Livrată' },
    { date: '28 mar', name: 'Pachet skincare premium', pts: 75, status: 'Livrată' },
  ];
  const statusColor = { 'Expediată': 'var(--warning)', 'Livrată': 'var(--success)', 'În pregătire': 'var(--txt-2)' };
  return (
    <div className="card" style={{ padding: 24, marginTop: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Cumpărături recente</div>
          <div className="display" style={{ fontSize: 20, marginTop: 6 }}>Comenzi în curs</div>
        </div>
        <a className="ulink" style={{ fontSize: 13 }}>Vezi tot →</a>
      </div>
      {orders.map((o, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 100px 120px', alignItems: 'center', gap: 16, padding: '12px 0', borderTop: '.5px solid var(--line-soft)' }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{o.date}</div>
          <div style={{ fontSize: 14 }}>{o.name}</div>
          <div className="mono" style={{ fontSize: 13, color: 'var(--accent-1)' }}>💎 {o.pts}</div>
          <div style={{ textAlign: 'right' }}>
            <span className="pill" style={{ fontSize: 10, color: statusColor[o.status], borderColor: statusColor[o.status] + '40', background: statusColor[o.status] + '12' }}>● {o.status}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function ReferralBanner() {
  return (
    <div className="card-glass" style={{ marginTop: 24, padding: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 100% 50%, rgba(255,215,0,.1), transparent 60%)' }}/>
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div className="display" style={{ fontSize: 20 }}>Recomandă un prieten →</div>
        <div style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 4 }}>Primești <strong style={{ color: 'var(--accent-1)' }}>+5 puncte</strong> pentru fiecare creator înscris.</div>
      </div>
      <button className="btn btn-primary" style={{ position: 'relative', zIndex: 2 }}>Copiază link</button>
    </div>
  );
}

window.DashboardPage = DashboardPage;
window.DashSidebar = DashSidebar;
