// Profile + Edit profile

const ProfileScreen = ({ user, subscribed, onEdit, onSettings, onOpen, onBadge }) => {
  const [tab, setTab] = React.useState('posts');
  const userPosts = POSTS.slice(0, user.stats.posts);
  const subEvents = EVENTS.filter(e => subscribed.has(e.id));

  return (
    <div className="screen">
      <StatusBar />
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 20px 16px' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.16em', marginBottom: 4 }}>@{user.handle}</div>
          <h1 style={{ fontSize: 22, margin: 0, fontWeight: 600, letterSpacing: '-0.02em' }}>Perfil</h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-nav" onClick={onEdit}><IconEdit size={18} /></button>
          <button className="btn btn-nav" onClick={onSettings}><IconSettings size={18} /></button>
        </div>
      </div>

      <div style={{ padding: '0 20px 20px' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 16 }}>
          <Avatar user={user} size={84} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 4 }}>{user.name}</div>
            <div style={{ fontSize: 12, color: 'var(--text-mute)' }}>{user.school}</div>
          </div>
        </div>

        <div style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.5, marginBottom: 14 }}>{user.bio}</div>

        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 }}>
          {user.interests.map(i => (
            <span key={i} className="chip amber" style={{ fontSize: 11 }}>{i}</span>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-primary" onClick={onEdit} style={{ flex: 1 }}>Editar perfil</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', margin: '8px 0 0' }}>
        {[
          { id: 'posts', label: 'Posts', icon: IconGrid },
          { id: 'events', label: 'Calendário', icon: IconCalendar },
        ].map(t => {
          const T = t.icon;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              flex: 1, padding: '14px 0',
              background: 'none', border: 'none',
              borderBottom: `2px solid ${tab === t.id ? 'var(--amber)' : 'transparent'}`,
              color: tab === t.id ? '#fff' : 'var(--text-mute)',
              cursor: 'pointer', font: 'inherit', fontSize: 12, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              marginBottom: -1,
            }}>
              <T size={15} /> {t.label}
            </button>
          );
        })}
      </div>

      {tab === 'posts' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 2, padding: 2 }}>
          {userPosts.concat(userPosts).slice(0, 6).map((p, i) => (
            <button key={i} onClick={() => onOpen(p)} style={{ padding: 0, border: 'none', background: 'none', cursor: 'pointer' }}>
              <Placeholder gradient={p.image} aspect="1/1" />
            </button>
          ))}
        </div>
      )}

      {tab === 'events' && (
        <div style={{ padding: 20 }}>
          {subEvents.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-mute)' }}>
              <IconCalendar size={36} stroke={1.4} />
              <div style={{ marginTop: 12, fontSize: 13 }}>Você ainda não se inscreveu em eventos.</div>
            </div>
          ) : subEvents.map(ev => {
            const day = EVENT_DAYS.find(d => d.id === ev.day);
            return (
              <div key={ev.id} style={{
                display: 'flex', gap: 12, padding: '12px 0',
                borderBottom: '1px solid var(--line)',
              }}>
                <div style={{ textAlign: 'center', minWidth: 44 }}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--amber)', letterSpacing: '0.1em' }}>{day?.label}</div>
                  <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>{day?.date}</div>
                </div>
                <div style={{ flex: 1 }}>
                  <TrackBadge track={ev.track} tag={ev.tag} />
                  <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6, lineHeight: 1.3 }}>{ev.title}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-mute)', marginTop: 4 }}>{ev.time} · {ev.room}</div>
                </div>
              </div>
            );
          })}
        </div>
      )}


    </div>
  );
};

const EditProfileScreen = ({ user, onBack, onSave }) => {
  const [draft, setDraft] = React.useState(user);
  const [avatarColor, setAvatarColor] = React.useState(user.color);
  const colors = ['#F5A623', '#3A56B0', '#E0457B', '#0FA89B', '#6B2EA8', '#FF5A5F'];
  const toggle = (i) => {
    setDraft(d => ({
      ...d,
      interests: d.interests.includes(i) ? d.interests.filter(x => x !== i) : [...d.interests, i],
    }));
  };
  const allInterests = ['Design', 'Economia', 'Publicidade', 'Arquitetura', 'Direito', 'Engenharia', 'Medicina', 'Computação', 'RI', 'Administração', 'Cinema', 'Psicologia'];

  return (
    <div className="screen">
      <StatusBar />
      <ScreenHeader title="Editar perfil" onBack={onBack} right={
        <button onClick={() => onSave({ ...draft, color: avatarColor })} style={{
          background: 'none', border: 'none', color: 'var(--amber)',
          font: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer', padding: 4,
        }}>Salvar</button>
      } />

      <div style={{ padding: '0 20px 40px' }}>
        {/* Avatar */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 20 }}>
          <div style={{ position: 'relative' }}>
            <Avatar user={{ ...draft, color: avatarColor }} size={96} />
            <button style={{
              position: 'absolute', bottom: 0, right: 0,
              width: 32, height: 32, borderRadius: '50%',
              background: 'var(--amber)', color: '#05080F',
              border: '3px solid #05080F', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><IconCamera size={14} stroke={2.2} /></button>
          </div>
          <button style={{
            background: 'none', border: 'none', color: 'var(--amber)',
            font: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer', marginTop: 10,
          }}>Alterar foto</button>

          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--text-mute)', marginTop: 8 }}>
            OU ESCOLHA UMA COR
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            {colors.map(c => (
              <button key={c} onClick={() => setAvatarColor(c)} style={{
                width: 28, height: 28, borderRadius: '50%', background: c,
                border: avatarColor === c ? '2px solid #fff' : '2px solid transparent',
                cursor: 'pointer', padding: 0,
                boxShadow: avatarColor === c ? '0 0 0 2px #05080F, 0 0 0 4px ' + c : 'none',
              }} />
            ))}
          </div>
        </div>

        <Field label="NOME">
          <input className="input" value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} />
        </Field>
        <Field label="USUÁRIO">
          <div style={{ position: 'relative' }}>
            <span style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-mute)', fontSize: 15 }}>@</span>
            <input className="input" style={{ paddingLeft: 30 }} value={draft.handle} onChange={e => setDraft({ ...draft, handle: e.target.value })} />
          </div>
        </Field>
        <Field label="BIO">
          <textarea className="input" value={draft.bio} onChange={e => setDraft({ ...draft, bio: e.target.value })}
            style={{ minHeight: 72, resize: 'none', fontFamily: 'inherit' }} />
          <div style={{ textAlign: 'right', fontSize: 11, color: 'var(--text-mute)', marginTop: 4 }}>{draft.bio.length}/150</div>
        </Field>
        <Field label="ESCOLA">
          <input className="input" value={draft.school} onChange={e => setDraft({ ...draft, school: e.target.value })} />
        </Field>

        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--text-mute)', marginBottom: 10, marginTop: 18 }}>
          ÁREAS DE INTERESSE
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {allInterests.map(i => (
            <button key={i} onClick={() => toggle(i)}
              className={'chip' + (draft.interests.includes(i) ? ' active' : '')}>
              {draft.interests.includes(i) && <IconCheck size={11} stroke={3} />} {i}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, children }) => (
  <div style={{ marginBottom: 14 }}>
    <label className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.14em', display: 'block', marginBottom: 6 }}>{label}</label>
    {children}
  </div>
);

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

// ============================================================
// UserProfileScreen — viewing another user; entry point for DM
// ============================================================

// Sample public profiles — keyed by handle. When the user taps someone,
// we either find their full record here or fall back to basic info.
const PUBLIC_PROFILES = {
  'marina.c': {
    name: 'Marina Castro', handle: 'marina.c', avatar: 'MC', color: '#F5A623',
    bio: 'Design + publicidade. Curiosa sobre tudo. Gosto de cafés e de typography.',
    school: 'Colégio Pio XII · 3º ano',
    interests: ['Design', 'Publicidade', 'Cinema'],
    stats: { posts: 18, connections: 142, events: 4 },
    mutuals: ['Pedro Hanazaki', '+ 6 conexões em comum'],
  },
  'p.hana': {
    name: 'Pedro Hanazaki', handle: 'p.hana', avatar: 'PH', color: '#3A56B0',
    bio: 'Futuro dev. Jogo mais xadrez do que videogame. Venho do interior.',
    school: 'Etapa Valinhos · 3º ano',
    interests: ['Computação', 'Engenharia', 'Economia'],
    stats: { posts: 24, connections: 198, events: 6 },
    mutuals: ['Júlia Arruda', '+ 4 conexões em comum'],
  },
  'juu.arruda': {
    name: 'Júlia Arruda', handle: 'juu.arruda', avatar: 'JA', color: '#E0457B',
    bio: 'Medicina ou psicologia, ainda não decidi. E tá tudo bem.',
    school: 'Bandeirantes · 2º ano',
    interests: ['Medicina', 'Psicologia'],
    stats: { posts: 11, connections: 87, events: 3 },
    mutuals: ['+ 3 conexões em comum'],
  },
};

const UserProfileScreen = ({ handle, onBack, onMessage, onOpenPost }) => {
  const profile = PUBLIC_PROFILES[handle] || {
    name: handle, handle, avatar: (handle[0] || '?').toUpperCase(), color: '#3A56B0',
    bio: 'Aluno do Forma Tour', school: '', interests: [],
    stats: { posts: 0, connections: 0, events: 0 }, mutuals: [],
  };
  const posts = POSTS.filter(p => p.user.handle === handle).slice(0, 6);

  return (
    <div className="screen">
      <StatusBar />
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '8px 16px 12px',
      }}>
        <button className="btn btn-nav" onClick={onBack}><IconChevronLeft size={20} /></button>
        <div style={{ fontSize: 14, fontWeight: 600 }}>@{profile.handle}</div>
        <button className="btn btn-nav"><IconMore size={18} /></button>
      </div>

      <div style={{ padding: '4px 20px 18px' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 14 }}>
          <Avatar user={profile} size={84} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 4 }}>{profile.name}</div>
            {profile.school && <div style={{ fontSize: 12, color: 'var(--text-mute)' }}>{profile.school}</div>}
          </div>
        </div>

        <div style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.5, marginBottom: 12 }}>{profile.bio}</div>

        {profile.interests?.length > 0 && (
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
            {profile.interests.map(i => (
              <span key={i} className="chip" style={{ fontSize: 11 }}>{i}</span>
            ))}
          </div>
        )}

        {profile.mutuals?.length > 0 && (
          <div style={{
            fontSize: 11, color: 'var(--text-mute)', marginBottom: 16,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <IconUser size={12} stroke={1.8} />
            {profile.mutuals.join(' · ')}
          </div>
        )}

        <button className="btn btn-primary" onClick={onMessage} style={{ width: '100%' }}>
          <IconMessage size={16} stroke={2} /> Mensagem
        </button>
      </div>

      <div style={{ borderTop: '1px solid var(--line)', padding: '14px 20px 10px' }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--text-mute)', marginBottom: 10 }}>
          POSTS
        </div>
        {posts.length === 0 ? (
          <div style={{ padding: '28px 0', textAlign: 'center', color: 'var(--text-mute)', fontSize: 13 }}>
            {profile.name.split(' ')[0]} ainda não publicou nada.
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 3, paddingBottom: 24 }}>
            {posts.map(p => (
              <button key={p.id} onClick={() => onOpenPost(p)} style={{ padding: 0, border: 'none', background: 'none', cursor: 'pointer' }}>
                <Placeholder gradient={p.image} aspect="1/1" />
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

const StatBlock = ({ label, value, accent }) => (
  <div style={{ textAlign: 'center' }}>
    <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em', color: accent ? 'var(--amber)' : '#fff' }}>{value}</div>
    <div style={{ fontSize: 10, color: 'var(--text-mute)', fontFamily: "'Geist Mono', monospace", letterSpacing: '0.1em' }}>{label}</div>
  </div>
);

Object.assign(window, { PUBLIC_PROFILES, UserProfileScreen });
