// screen-profile-trade.jsx — Profile and Trade Balance screens
const { useState: usePTState, useEffect: usePTEffect } = React;

function ProfileScreen({ currentUser, onEdit }) {
  const Icon = window.Icon;
  const u = currentUser || {};
  const nameParts = (u.name || 'Heba Ali').split(' ');
  const firstName = nameParts[0] || '';
  const lastName = nameParts.slice(1).join(' ') || '';

  const [stats, setStats] = usePTState(window.PROFILE_STATS);
  usePTEffect(() => {
    if (!u.id) return;
    window.API.getUser(u.id).then(data => {
      setStats([
        { label: 'All ideas',            value: Number(data.idea_count ?? 0) },
        { label: 'Ideas under review',   value: Number(data.review_count ?? 0) },
        { label: 'Published ideas',      value: Number(data.published_count ?? 0) },
        { label: 'Rejected ideas',       value: Number(data.rejected_count ?? 0) },
        { label: 'Ideas views',          value: (data.ideas || []).reduce((s, i) => s + Number(i.views || 0), 0) },
      ]);
    }).catch(() => {});
  }, [u.id]);

  return (
    <div className="page fade-in">
      <div className="page-head"><div><div className="page-title">My profile</div><div className="page-sub">Manage your information and track your idea performance.</div></div></div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'start' }}>
        <div className="card" style={{ padding: 28 }}>
          <div className="spread" style={{ alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', gap: 20 }}>
              <window.Avatar src={u.avatar} size={96} />
              <div style={{ paddingTop: 6 }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--ink-900)', letterSpacing: '-.02em' }}>{u.name || 'Heba Ali'}</div>
                <div className="muted" style={{ fontSize: 15, fontWeight: 600, marginTop: 4, whiteSpace: 'nowrap' }}>{u.role || 'UX / UI Designer'}</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  {['#e8930c', '#0a66ff', '#e23b56'].map(c => <div key={c} style={{ color: c }}><Icon name="award" size={28} /></div>)}
                </div>
              </div>
            </div>
            <button className="btn btn-dark btn-sm" onClick={onEdit}><Icon name="edit" size={16} />Edit profile</button>
          </div>
          <div style={{ height: 1, background: 'var(--line)', margin: '26px 0' }} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '22px 32px' }}>
            <InfoRow label="First name" value={firstName} />
            <InfoRow label="Last name" value={lastName} />
            <InfoRow label="Email" value={u.email || ''} icon="mail" />
            <InfoRow label="Phone" value={u.phone || '—'} icon="phone" />
          </div>
          <div style={{ marginTop: 22 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-400)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 8 }}>Bio</div>
            <p style={{ margin: 0, fontSize: 14.5, color: 'var(--ink-600)', lineHeight: 1.7 }}>{u.bio || 'Product designer focused on internal tools and innovation systems.'}</p>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="card" style={{ padding: 22 }}>
            <div className="section-label" style={{ marginBottom: 6 }}>General stats</div>
            {stats.map((s, i) => (
              <div key={s.label} className="spread" style={{ padding: '13px 0', borderBottom: i < stats.length - 1 ? '1px solid var(--line)' : 'none' }}>
                <span style={{ fontSize: 14, color: 'var(--ink-600)', fontWeight: 500, whiteSpace: 'nowrap' }}>{s.label}</span>
                <span className="tnum" style={{ fontSize: 17, fontWeight: 800, color: 'var(--ink-900)' }}>{window.fmt(s.value)}</span>
              </div>
            ))}
          </div>
          <div className="card" style={{ padding: 22 }}>
            <div className="section-label" style={{ marginBottom: 14 }}>Achievements</div>
            <div style={{ display: 'flex', gap: 14 }}>
              {[['#e8930c', 'Top voice'], ['#0a66ff', 'Innovator'], ['#e23b56', '50 ideas']].map(([c, t]) => (
                <div key={t} style={{ flex: 1, textAlign: 'center', background: 'var(--ink-50)', borderRadius: 'var(--r)', padding: '16px 6px' }}>
                  <div style={{ color: c }}><Icon name="award" size={36} /></div>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-600)', marginTop: 6 }}>{t}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function InfoRow({ label, value, icon }) {
  const Icon = window.Icon;
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-400)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 7, fontSize: 15.5, color: 'var(--ink-800)', fontWeight: 600 }}>
        {icon && <span style={{ color: 'var(--ink-300)' }}><Icon name={icon} size={18} /></span>}{value}
      </div>
    </div>
  );
}

function TradeScreen({ balance, onRedeem, onHistory }) {
  const Icon = window.Icon;
  const [awards, setAwards] = usePTState(window.AWARDS);
  const [txns, setTxns] = usePTState(window.TRANSACTIONS);
  usePTEffect(() => {
    window.API.getAwards().then(setAwards).catch(() => {});
    window.API.transactions().then(setTxns).catch(() => {});
  }, []);
  return (
    <div className="page fade-in">
      <div className="page-head"><div><div className="page-title">Trade your balance</div><div className="page-sub">Convert the points you've earned from great ideas into real rewards.</div></div></div>

      <div className="card" style={{ padding: 26, marginBottom: 26, display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'linear-gradient(120deg, var(--ink-900), #243150)', border: 'none', color: '#fff', overflow: 'hidden', position: 'relative' }}>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'rgba(255,255,255,.6)', letterSpacing: '.04em' }}>Available balance</div>
          <div className="tnum" style={{ fontSize: 44, fontWeight: 800, letterSpacing: '-.02em', marginTop: 4, display: 'flex', alignItems: 'baseline', gap: 8 }}>{window.fmt(balance)} <span style={{ fontSize: 18, color: 'rgba(255,255,255,.6)' }}>USD</span></div>
        </div>
        <button className="btn" onClick={onHistory} style={{ background: 'rgba(255,255,255,.14)', color: '#fff', position: 'relative', zIndex: 2 }}><Icon name="coins" size={18} />Balance & transactions</button>
        <div style={{ position: 'absolute', right: 180, top: '50%', transform: 'translateY(-50%)', color: 'rgba(255,255,255,.08)' }}><Icon name="coins" size={200} /></div>
      </div>

      <div className="section-label" style={{ marginBottom: 16 }}>List of awards</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginBottom: 30 }}>
        {awards.map(a => {
          const can = balance >= a.cost;
          return (
            <div key={a.id} className="card" style={{ padding: 22, display: 'flex', flexDirection: 'column' }}>
              <div style={{ width: 56, height: 56, borderRadius: 'var(--r)', background: 'var(--ink-50)', display: 'grid', placeItems: 'center', fontSize: 30 }}>{a.emoji}</div>
              <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink-900)', marginTop: 16, lineHeight: 1.35, minHeight: 44 }}>{a.title}</div>
              <div className="spread" style={{ marginTop: 14 }}>
                <span className="tnum" style={{ fontSize: 18, fontWeight: 800, color: 'var(--coral-500)' }}>{window.fmt(a.cost)} <span style={{ fontSize: 12.5, color: 'var(--ink-400)', fontWeight: 700 }}>USD</span></span>
                <button className="btn btn-sm" onClick={() => can && onRedeem(a)} disabled={!can}
                  style={{ background: can ? 'var(--accent-600)' : 'var(--ink-100)', color: can ? '#fff' : 'var(--ink-400)', boxShadow: can ? '0 4px 12px rgba(var(--accent-rgb),.28)' : 'none', cursor: can ? 'pointer' : 'not-allowed' }}>
                  {can ? 'Redeem' : 'Not enough'}
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <div className="section-label" style={{ marginBottom: 16 }}>Recent transactions</div>
      <div className="table-card">
        {txns.map((t, i) => (
          <div key={t.id} className="spread" style={{ padding: '16px 22px', borderBottom: i < txns.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: t.kind === 'earn' ? 'var(--success-bg)' : 'var(--danger-bg)', color: t.kind === 'earn' ? 'var(--success)' : 'var(--danger)' }}>
                <Icon name={t.kind === 'earn' ? 'trendUp' : 'trendDown'} size={20} />
              </div>
              <div style={{ minWidth: 0 }}><div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink-800)', lineHeight: 1.4 }}>{t.label}</div><div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{t.date}</div></div>
            </div>
            <span className="tnum" style={{ fontSize: 16, fontWeight: 800, color: t.kind === 'earn' ? 'var(--success)' : 'var(--ink-700)', flex: 'none', paddingLeft: 14 }}>{t.amount > 0 ? '+' : ''}{window.fmt(t.amount)} USD</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ProfileScreen, TradeScreen });
