// screen-secondary.jsx — Edit profile, Public profile, Balance & transactions
const { useState: useSecState, useEffect: useSecEffect } = React;

/* ----------------------------------------------------------------
   Edit profile
----------------------------------------------------------------- */
function EditProfileScreen({ currentUser, goBack, onSave }) {
  const Icon = window.Icon;
  const u = currentUser || {};
  const nameParts = (u.name || 'Heba Ali').split(' ');
  const [form, setForm] = useSecState({
    first: nameParts[0] || 'Heba',
    last: nameParts.slice(1).join(' ') || 'Ali',
    role: u.role || 'UX / UI Designer',
    email: u.email || '',
    phone: u.phone || '',
    bio: u.bio || 'Product designer focused on internal tools and innovation systems.',
  });
  const [saving, setSaving] = useSecState(false);
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const handleSave = async () => {
    setSaving(true);
    try {
      const updated = await window.API.updateMe({ name: `${form.first} ${form.last}`, role: form.role, bio: form.bio, phone: form.phone });
      onSave(updated);
    } catch (e) {
      onSave(null);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="page fade-in" style={{ maxWidth: 880 }}>
      <button className="btn btn-ghost btn-sm" onClick={goBack} style={{ marginBottom: 18 }}><Icon name="chevLeft" size={16} />Back to profile</button>
      <div className="page-head"><div><div className="page-title">Edit profile</div><div className="page-sub">Update your details and how you appear across IdeaMint.</div></div></div>

      <div className="card" style={{ padding: 28 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, paddingBottom: 24, borderBottom: '1px solid var(--line)' }}>
          <div style={{ position: 'relative' }}>
            <window.Avatar src={window.AV.heba} size={92} />
            <button className="icon-btn" style={{ position: 'absolute', right: -6, bottom: -6, width: 34, height: 34, background: 'var(--accent-600)', color: 'var(--on-accent)', boxShadow: 'var(--sh-md)' }} title="Change photo"><Icon name="image" size={17} /></button>
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--ink-900)' }}>Profile photo</div>
            <div className="muted" style={{ fontSize: 13.5, marginTop: 3, marginBottom: 12 }}>PNG or JPG, at least 400×400px.</div>
            <div style={{ display: 'flex', gap: 9 }}>
              <button className="btn btn-outline btn-sm"><Icon name="upload" size={15} />Upload new</button>
              <button className="btn btn-ghost btn-sm">Remove</button>
            </div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '22px 24px', marginTop: 24 }}>
          <EditField label="First name" value={form.first} onChange={set('first')} />
          <EditField label="Last name" value={form.last} onChange={set('last')} />
          <EditField label="Job title" value={form.role} onChange={set('role')} />
          <EditField label="Email" value={form.email} onChange={set('email')} type="email" />
          <EditField label="Phone" value={form.phone} onChange={set('phone')} />
        </div>

        <div style={{ marginTop: 22 }}>
          <label style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: 'var(--ink-800)', marginBottom: 8 }}>Bio</label>
          <textarea className="fld" rows={4} value={form.bio} onChange={set('bio')} style={{ resize: 'none' }} />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 20 }}>
        <button className="btn btn-ghost" onClick={goBack}>Cancel</button>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}><Icon name="check" size={17} />{saving ? 'Saving…' : 'Save changes'}</button>
      </div>
    </div>
  );
}
function EditField({ label, value, onChange, type }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: 'var(--ink-800)', marginBottom: 8 }}>{label}</label>
      <input className="fld" type={type || 'text'} value={value} onChange={onChange} />
    </div>
  );
}

/* ----------------------------------------------------------------
   Public profile (another user)
----------------------------------------------------------------- */
function PublicProfileScreen({ user, goBack, openIdea, votes, onVote }) {
  const Icon = window.Icon;
  const [following, setFollowing] = useSecState(false);
  const u = user || window.NAMES[0];
  const ideas = window.IDEAS.filter((_, i) => i % 2 === 0).slice(0, 4).map(x => ({ ...x, author: u.name, avatar: u.av }));

  return (
    <div className="page fade-in">
      <button className="btn btn-ghost btn-sm" onClick={goBack} style={{ marginBottom: 18 }}><Icon name="chevLeft" size={16} />Back</button>

      {/* banner */}
      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <div style={{ height: 150, background: `linear-gradient(120deg, var(--accent-700), var(--accent-600))`, position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 0, opacity: .18, background: `url(${window.HERO}) center/cover` }} />
        </div>
        <div style={{ padding: '0 28px 26px', display: 'flex', alignItems: 'flex-end', gap: 20, marginTop: -46 }}>
          <div style={{ borderRadius: '50%', padding: 4, background: 'var(--surface)' }}><window.Avatar src={u.av} size={104} /></div>
          <div style={{ flex: 1, paddingBottom: 6 }}>
            <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--ink-900)', letterSpacing: '-.02em' }}>{u.name}</div>
            <div className="muted" style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>{u.role}</div>
          </div>
          <div style={{ display: 'flex', gap: 10, paddingBottom: 6 }}>
            <button className="btn btn-outline btn-sm"><Icon name="mail" size={16} />Message</button>
            <button className="btn btn-sm" onClick={() => setFollowing(f => !f)} style={{ background: following ? 'var(--ink-50)' : 'var(--accent-600)', color: following ? 'var(--ink-700)' : 'var(--on-accent)', boxShadow: following ? 'none' : '0 6px 16px rgba(var(--accent-rgb),.32)' }}>
              {following ? <><Icon name="check" size={16} />Following</> : <><Icon name="plus" size={16} />Follow</>}
            </button>
          </div>
        </div>
      </div>

      {/* stat strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18, margin: '22px 0' }}>
        {[['Published ideas', '30', 'checkCircle', '#15a564'], ['Total upvotes', '4.2k', 'thumbUp', '#0a66ff'], ['Idea views', '12.8k', 'eye', '#6d5cf0'], ['Rank', '#3', 'award', '#e8930c']].map(([l, v, ic, c]) => (
          <div key={l} className="card" style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
            <div className="stat-ic" style={{ background: c + '18', color: c, width: 44, height: 44 }}><Icon name={ic} size={22} /></div>
            <div><div className="tnum" style={{ fontSize: 22, fontWeight: 800, color: 'var(--ink-900)' }}>{v}</div><div className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>{l}</div></div>
          </div>
        ))}
      </div>

      <div className="section-label" style={{ marginBottom: 16 }}>{u.name.split(' ')[0]}'s ideas</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 18 }}>
        {ideas.map(i => (
          <div key={i.id} className="card" style={{ padding: 20, cursor: 'pointer' }} onClick={() => openIdea(i)}>
            <div className="spread" style={{ marginBottom: 10 }}><window.CatChip name={i.category} /><window.StatusBadge status={i.status} /></div>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--coral-500)', marginBottom: 7 }}>{i.title}</div>
            <p style={{ margin: '0 0 14px', fontSize: 13.5, color: 'var(--ink-500)', lineHeight: 1.55, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{i.desc}</p>
            <window.StatChips idea={i} vote={votes[i.id]} onVote={(d) => onVote(i.id, d)} />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ----------------------------------------------------------------
   Balance & transactions detail
----------------------------------------------------------------- */
const ALL_TX = [
  { id: 1, label: 'Idea published — "Carbon-neutral delivery"', date: 'May 14, 2025', amount: +150, kind: 'earn' },
  { id: 2, label: 'Redeemed — Free flight ticket to Cairo', date: 'May 10, 2025', amount: -250, kind: 'spend' },
  { id: 3, label: 'Upvotes milestone bonus (500 upvotes)', date: 'May 7, 2025', amount: +80, kind: 'earn' },
  { id: 4, label: 'Idea published — "Smart meeting summaries"', date: 'May 2, 2025', amount: +150, kind: 'earn' },
  { id: 5, label: 'Redeemed — A full day off from work', date: 'Apr 28, 2025', amount: -50, kind: 'spend' },
  { id: 6, label: 'Idea of the month award', date: 'Apr 22, 2025', amount: +200, kind: 'earn' },
  { id: 7, label: 'Idea published — "Mentorship matching"', date: 'Apr 15, 2025', amount: +150, kind: 'earn' },
  { id: 8, label: 'Comment milestone bonus', date: 'Apr 9, 2025', amount: +40, kind: 'earn' },
  { id: 9, label: 'Redeemed — Premium standing desk', date: 'Apr 1, 2025', amount: -600, kind: 'spend' },
];

function BalanceDetailScreen({ balance, goBack }) {
  const Icon = window.Icon;
  const [filter, setFilter] = useSecState('All');
  const [allTx, setAllTx] = useSecState(ALL_TX);
  useSecEffect(() => {
    window.API.transactions().then(setAllTx).catch(() => {});
  }, []);
  const earned = allTx.filter(t => t.kind === 'earn').reduce((s, t) => s + Math.abs(t.amount), 0);
  const spent = allTx.filter(t => t.kind === 'spend').reduce((s, t) => s + Math.abs(t.amount), 0);
  const rows = filter === 'All' ? allTx : allTx.filter(t => filter === 'Earned' ? t.kind === 'earn' : t.kind === 'spend');

  return (
    <div className="page fade-in">
      <button className="btn btn-ghost btn-sm" onClick={goBack} style={{ marginBottom: 18 }}><Icon name="chevLeft" size={16} />Back to trade</button>
      <div className="page-head"><div><div className="page-title">Balance & transactions</div><div className="page-sub">A complete history of points you've earned and redeemed.</div></div></div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginBottom: 26 }}>
        <div className="card" style={{ padding: 24, background: 'linear-gradient(120deg, var(--ink-900), #243150)', border: 'none', color: '#fff', position: 'relative', overflow: 'hidden' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,.6)' }}>Current balance</div>
          <div className="tnum" style={{ fontSize: 34, fontWeight: 800, marginTop: 6 }}>{window.fmt(balance)} <span style={{ fontSize: 15, color: 'rgba(255,255,255,.6)' }}>USD</span></div>
          <div style={{ position: 'absolute', right: -10, bottom: -16, color: 'rgba(255,255,255,.08)' }}><Icon name="coins" size={96} /></div>
        </div>
        <div className="card" style={{ padding: 24 }}>
          <div className="stat-ic" style={{ background: 'var(--success-bg)', color: 'var(--success)', width: 44, height: 44, marginBottom: 14 }}><Icon name="trendUp" size={22} /></div>
          <div className="tnum" style={{ fontSize: 28, fontWeight: 800, color: 'var(--ink-900)' }}>+{window.fmt(earned)}</div>
          <div className="muted" style={{ fontSize: 13, fontWeight: 600 }}>Total earned</div>
        </div>
        <div className="card" style={{ padding: 24 }}>
          <div className="stat-ic" style={{ background: 'var(--danger-bg)', color: 'var(--danger)', width: 44, height: 44, marginBottom: 14 }}><Icon name="trendDown" size={22} /></div>
          <div className="tnum" style={{ fontSize: 28, fontWeight: 800, color: 'var(--ink-900)' }}>−{window.fmt(spent)}</div>
          <div className="muted" style={{ fontSize: 13, fontWeight: 600 }}>Total redeemed</div>
        </div>
      </div>

      <div className="table-card">
        <div className="table-head-row">
          <div className="section-label">Transaction history</div>
          <div className="table-tools">
            <div className="chip-row">
              {['All', 'Earned', 'Redeemed'].map(f => <button key={f} className={`chip ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>{f}</button>)}
            </div>
          </div>
        </div>
        {rows.map((t, i) => (
          <div key={t.id} className="spread" style={{ padding: '16px 22px', borderBottom: i < rows.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' : 'gift'} 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, { EditProfileScreen, PublicProfileScreen, BalanceDetailScreen });
