// screens.jsx — Home, PostDetail, Compose, Profile, Welcome
(function () {
  const { useState, useRef, useEffect } = React;
  const { Icon, Avatar, NameLine, PostCard, ReplyCard, TrackCard, Cover, Header, Wordmark } = window;

  // ── HOME ─────────────────────────────────────────────────────
  function HomeScreen({ app }) {
    const T = app.theme;
    return (
      <>
        <Header
          big={<Wordmark app={app} />}
          left={<button onClick={() => app.setTab('profile')} style={iconBtn}><Avatar user="you" size={30} /></button>}
          right={<span style={{ color: T.sub }}><Icon.search size={22} /></span>}
        />
        <div>
          {app.posts.map(p => (
            <PostCard key={p.id} post={p} onOpen={() => app.go('detail', { id: p.id })} />
          ))}
          <div style={{ textAlign: 'center', color: T.faint, fontSize: 12.5, padding: '22px 0 12px' }}>
            ここが、ぱぱFMの全部。<br/>いい曲はリプで盛り上げよう。
          </div>
        </div>
      </>
    );
  }

  // ── POST DETAIL ──────────────────────────────────────────────
  function DetailScreen({ app, postId }) {
    const T = app.theme;
    const post = app.posts.find(p => p.id === postId);
    if (!post) return <div style={{ padding: 40, color: T.sub }}>投稿が見つかりません。</div>;
    const track = app.trackById[post.track_id];
    const liked = app.isLiked(post.id);

    return (
      <>
        <Header
          title="投稿"
          left={<button onClick={() => app.back()} style={iconBtn}><span style={{ color: T.text }}><Icon.back size={22} /></span></button>}
        />
        <div>
          {/* main post */}
          <div style={{ padding: 16, borderBottom: `1px solid ${T.border}` }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <Avatar user={post.author} size={46} />
              <div style={{ minWidth: 0 }}>
                <NameLine user={post.author} app={app} />
                <div style={{ color: T.faint, fontSize: 13 }}>{post.time}</div>
              </div>
            </div>
            {post.text && <div style={{ color: T.text, fontSize: 17, lineHeight: 1.65, marginTop: 12 }}>{post.text}</div>}
            {track && <TrackCard track={track} />}
            <div style={{ display: 'flex', gap: 18, marginTop: 14, paddingTop: 14, borderTop: `1px solid ${T.border}`, color: T.sub, fontSize: 13.5 }}>
              <span><b style={{ color: T.text }}>{app.likeCount(post)}</b> いいね</span>
              <span><b style={{ color: T.text }}>{(post.replies || []).length}</b> リプ</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', marginTop: 6, paddingTop: 10, borderTop: `1px solid ${T.border}` }}>
              <button style={{ ...rowBtn, color: T.faint }} onClick={() => document.getElementById('pf-reply-input')?.focus()}><Icon.reply size={20} /></button>
              <button style={{ ...rowBtn, color: liked ? '#ff5a7a' : T.faint }} onClick={() => app.like(post.id, 'post')}>{liked ? <Icon.heartFill size={20} /> : <Icon.heart size={20} />}</button>
              <button style={{ ...rowBtn, color: T.faint }} onClick={() => app.share(post)}><Icon.share size={19} /></button>
            </div>
          </div>

          {/* replies */}
          <div style={{ padding: '12px 16px 6px', color: T.faint, fontSize: 12.5, fontWeight: 700, letterSpacing: 0.5 }}>
            リプライ（だれでも参加OK）
          </div>
          {(post.replies || []).length === 0 && (
            <div style={{ padding: '8px 16px 20px', color: T.faint, fontSize: 14 }}>まだリプがありません。最初のひとことを。</div>
          )}
          {(post.replies || []).map(r => <ReplyCard key={r.id} reply={r} app={app} />)}
          <div style={{ height: 90 }} />
        </div>
      </>
    );
  }

  // root-level reply bar (pinned to device bottom)
  function ReplyBar({ app, postId }) {
    const T = app.theme;
    const [text, setText] = useState('');
    const send = () => { const v = text.trim(); if (!v) return; app.addReply(postId, v); setText(''); };
    return (
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
        background: T.glass, backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
        borderTop: `1px solid ${T.border}`, padding: '10px 12px 30px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <Avatar user="you" size={34} />
        <input id="pf-reply-input" value={text} onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') send(); }}
          placeholder="リプを書く…（だれでもOK）" style={{
            flex: 1, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 20,
            padding: '10px 14px', color: T.text, fontSize: 14.5, fontFamily: 'inherit', outline: 'none',
          }} />
        <button onClick={send} disabled={!text.trim()} style={{
          border: 'none', borderRadius: 18, padding: '9px 16px', fontWeight: 800, fontSize: 14,
          background: text.trim() ? T.accent : T.surface2, color: text.trim() ? '#fff' : T.faint,
          cursor: text.trim() ? 'pointer' : 'default', fontFamily: 'inherit',
        }}>リプ</button>
      </div>
    );
  }

  // ── COMPOSE ──────────────────────────────────────────────────
  function ComposeScreen({ app }) {
    const T = app.theme;
    const [q, setQ] = useState('');
    const [picked, setPicked] = useState(null);
    const [text, setText] = useState('');
    const list = window.PF.TRACKS.filter(t =>
      !q.trim() || (t.title + t.artist).toLowerCase().includes(q.toLowerCase()));

    const post = () => {
      if (!picked) return;
      app.addPost(picked.id, text.trim());
      app.closeCompose();
      app.setTab('home');
    };

    return (
      <div style={{ position: 'absolute', inset: 0, background: T.bg, zIndex: 80, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          paddingTop: 54, paddingBottom: 10, borderBottom: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '54px 14px 10px',
        }}>
          <button onClick={() => app.closeCompose()} style={{ ...iconBtn, color: T.text }}><Icon.close size={24} /></button>
          <span style={{ fontWeight: 800, color: T.text }}>おすすめを投稿</span>
          <button onClick={post} disabled={!picked} style={{
            border: 'none', borderRadius: 20, padding: '9px 18px', fontWeight: 800, fontSize: 14.5,
            background: picked ? T.accent : T.surface2, color: picked ? '#fff' : T.faint,
            cursor: picked ? 'pointer' : 'default', fontFamily: 'inherit',
          }}>投稿</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '14px 16px 40px' }}>
          {/* author + comment */}
          <div style={{ display: 'flex', gap: 12 }}>
            <Avatar user="you" size={44} />
            <textarea value={text} onChange={e => setText(e.target.value)} rows={3}
              placeholder="この曲をおすすめする、ひとこと。（理由が一行あると伝わる）"
              style={{
                flex: 1, background: 'none', border: 'none', outline: 'none', resize: 'none',
                color: T.text, fontSize: 16, lineHeight: 1.6, fontFamily: 'inherit', paddingTop: 8,
              }} />
          </div>

          {picked && (
            <div style={{ marginLeft: 56 }}><TrackCard track={picked} /></div>
          )}

          {/* track picker */}
          <div style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: T.faint, fontSize: 12.5, fontWeight: 700, marginBottom: 10 }}>
              <Icon.link size={15} /> 曲を選ぶ（サブスクのリンクは自動でつきます）
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 12, padding: '9px 12px', marginBottom: 10 }}>
              <span style={{ color: T.faint }}><Icon.search size={18} /></span>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="曲名・アーティストで検索"
                style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: T.text, fontSize: 14.5, fontFamily: 'inherit' }} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {list.map(t => {
                const on = picked && picked.id === t.id;
                return (
                  <button key={t.id} onClick={() => setPicked(t)} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '8px 8px', borderRadius: 12,
                    background: on ? T.surface2 : 'none', border: on ? `1px solid ${T.accent}66` : '1px solid transparent',
                    cursor: 'pointer', textAlign: 'left', font: 'inherit',
                  }}>
                    <Cover track={t} size={44} radius={9} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 700, color: T.text, fontSize: 14.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</div>
                      <div style={{ color: T.sub, fontSize: 12.5 }}>{t.artist}</div>
                    </div>
                    {on && <span style={{ color: T.accent }}><Icon.check size={20} /></span>}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── PROFILE ──────────────────────────────────────────────────
  function ProfileScreen({ app }) {
    const T = app.theme;
    const u = app.users.you;
    const mine = app.posts.filter(p => p.author.id === app.me.id);
    const myAlbums = app.albums || [];
    const [invite, setInvite] = useState(null);
    const issueInvite = async () => {
      try {
        const r = await app.createInvite();
        setInvite(r);
        try { await navigator.clipboard.writeText(r.url); } catch {}
      } catch (e) { alert(e.message === 'no_invites_left' ? '招待枠がありません' : 'エラー: ' + e.message); }
    };
    return (
      <>
        <Header title="あなた" left={<span style={{ color: T.text, opacity: 0 }}><Icon.back size={22} /></span>} />
        <div style={{ padding: '18px 18px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <Avatar user="you" size={66} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontWeight: 900, fontSize: 19, color: T.text }}>{u.name}</span>
                {app.user.passed && <span style={{ color: T.accent }}><Icon.verified size={17} /></span>}
              </div>
              <div style={{ color: T.faint, fontSize: 13.5 }}>@{u.handle}</div>
            </div>
          </div>

          {/* status card */}
          <div style={{
            marginTop: 16, padding: 16, borderRadius: 16,
            background: T.surface, border: `1px solid ${app.user.passed ? T.accent + '55' : T.border}`,
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 46, height: 46, borderRadius: 12, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: app.user.passed ? `${T.accent}22` : T.surface2,
              color: app.user.passed ? T.accent : T.faint,
            }}>{app.user.passed ? <Icon.badgeFill size={26} /> : <Icon.lock size={22} />}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, color: T.text, fontSize: 15 }}>
                {app.user.passed ? '審査 合格 — 投稿できます' : '審査 未合格'}
              </div>
              <div style={{ color: T.sub, fontSize: 12.5, marginTop: 2 }}>
                {app.user.passed ? `ベスト ${app.user.exam_best}・パパDJ` : 'リプはOK。投稿は審査の先に。'}
              </div>
            </div>
            <button onClick={() => app.startExam()} style={{
              border: 'none', borderRadius: 12, padding: '9px 14px', fontWeight: 800, fontSize: 13,
              background: app.user.passed ? T.surface2 : T.accent, color: app.user.passed ? T.sub : '#fff',
              cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0,
            }}>{app.user.passed ? '審査' : '受ける'}</button>
          </div>

          {/* invite + admin + logout */}
          <div style={{ marginTop: 14, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <button onClick={issueInvite} style={{
              flex: 1, minWidth: 140, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              padding: '11px', borderRadius: 12, border: 'none', background: T.accent, color: '#fff',
              fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
            }}><Icon.link size={16} />招待リンクを発行{app.me.role !== 'admin' ? `（残${app.user.invites_remaining}）` : ''}</button>
            {app.me.role === 'admin' && (
              <button onClick={() => app.openAdmin()} style={{
                flex: 1, minWidth: 120, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                padding: '11px', borderRadius: 12, border: `1px solid ${T.border}`, background: T.surface, color: T.text,
                fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
              }}><Icon.badge size={16} />管理</button>
            )}
          </div>
          {invite && (
            <div style={{ marginTop: 10, padding: 12, borderRadius: 12, background: T.surface2, border: `1px solid ${T.border}` }}>
              <div style={{ color: T.sub, fontSize: 12, marginBottom: 5 }}>使い切り招待リンク（コピー済み・LINE等で送ってOK）</div>
              <div style={{ color: T.text, fontSize: 12.5, wordBreak: 'break-all', fontFamily: 'monospace' }}>{invite.url}</div>
            </div>
          )}

          {/* the rule */}
          <div style={{ marginTop: 14, padding: 14, borderRadius: 14, background: T.surface, border: `1px solid ${T.border}` }}>
            <div style={{ display: 'flex', gap: 10 }}>
              <span style={{ color: T.accent, flexShrink: 0, marginTop: 1 }}><Icon.sparkle size={18} /></span>
              <p style={{ color: T.sub, fontSize: 13, lineHeight: 1.7, margin: 0 }}>
                <b style={{ color: T.text }}>ぱぱFMのルール。</b> 投稿できるのは、そうきくんのパパの審査を突破した人だけ。合格すれば、あなたもおすすめを発信できる。リプはいつでも、だれでも。
              </p>
            </div>
          </div>

          <button onClick={() => app.logout()} style={{
            marginTop: 14, width: '100%', padding: '11px', borderRadius: 12, border: `1px solid ${T.border}`,
            background: 'none', color: T.faint, fontWeight: 700, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
          }}>ログアウト</button>
        </div>

        {/* my albums */}
        <div style={{ marginTop: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px 8px' }}>
            <div style={{ color: T.faint, fontSize: 12.5, fontWeight: 700 }}>マイアルバム</div>
            <button onClick={() => app.openAlbumEditor(null)} style={{
              display: 'flex', alignItems: 'center', gap: 5, border: 'none', background: 'none',
              color: T.accent, fontWeight: 800, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
            }}><Icon.plus size={16} />作成</button>
          </div>
          {myAlbums.length === 0 ? (
            <button onClick={() => app.openAlbumEditor(null)} style={{
              display: 'block', width: 'calc(100% - 36px)', margin: '0 18px', padding: '22px',
              borderRadius: 14, border: `1.5px dashed ${T.border}`, background: 'none',
              color: T.faint, fontSize: 13.5, lineHeight: 1.7, cursor: 'pointer', fontFamily: 'inherit',
            }}>＋ 最初のアルバムを作る<br/>好きな曲をまとめて、サブスクのリンクを添えて共有。</button>
          ) : myAlbums.map(a => <window.AlbumCard key={a.id} album={a} app={app} />)}
        </div>

        {/* my posts */}
        <div style={{ marginTop: 18 }}>
          <div style={{ padding: '0 18px 8px', color: T.faint, fontSize: 12.5, fontWeight: 700 }}>あなたの投稿</div>
          {mine.length === 0 ? (
            <div style={{ padding: '18px', textAlign: 'center', color: T.faint, fontSize: 13.5, lineHeight: 1.7 }}>
              {app.user.passed ? 'まだ投稿がありません。＋から一曲どうぞ。' : '審査に合格すると、ここに投稿が並びます。'}
            </div>
          ) : mine.map(p => <PostCard key={p.id} post={p} onOpen={() => app.go('detail', { id: p.id })} />)}
        </div>
      </>
    );
  }

  // ── WELCOME ──────────────────────────────────────────────────
  function WelcomeScreen({ app }) {
    const T = app.theme;
    return (
      <div style={{ position: 'absolute', inset: 0, zIndex: 90, background: T.bg, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '90px 28px 50px', textAlign: 'center' }}>
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 320, background: `radial-gradient(90% 100% at 50% 0%, ${T.accent}33, transparent 70%)`, pointerEvents: 'none' }} />
        <div style={{ position: 'relative' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 18, background: T.accent, margin: '0 auto',
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
            boxShadow: `0 12px 30px ${T.accent}66`,
          }}><Icon.music size={34} /></div>
          <h1 style={{ fontFamily: T.display, fontSize: 40, fontWeight: 900, color: T.text, margin: '22px 0 0', letterSpacing: 0.5 }}>{app.copy.appName}</h1>
          <p style={{ color: T.sub, fontSize: 15.5, lineHeight: 1.7, marginTop: 12 }}>{app.copy.tagline}</p>
        </div>

        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 14, color: T.sub, fontSize: 14, textAlign: 'left' }}>
          {[
            ['いい曲を、ひとことの理由とともに。', Icon.music],
            ['Spotify / Apple / YouTube / Amazon に一発で。', Icon.link],
            ['投稿は審査制。リプはだれでも自由。', Icon.badge],
          ].map(([txt, Ic], i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ color: T.accent, flexShrink: 0 }}><Ic size={20} /></span>{txt}
            </div>
          ))}
        </div>

        <div style={{ position: 'relative' }}>
          <button onClick={() => app.enter()} style={{
            width: '100%', padding: '16px', borderRadius: 16, border: 'none', background: T.accent,
            color: '#fff', fontWeight: 800, fontSize: 16.5, cursor: 'pointer', fontFamily: 'inherit',
            boxShadow: `0 8px 22px ${T.accent}55`,
          }}>はじめる</button>
          <p style={{ color: T.faint, fontSize: 12, marginTop: 14, lineHeight: 1.6 }}>
            そうきくんのパパ と 園のパパママのための、招待制ミュージックSNS。
          </p>
        </div>
      </div>
    );
  }

  const iconBtn = { background: 'none', border: 'none', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center' };
  const rowBtn = { background: 'none', border: 'none', cursor: 'pointer', padding: 8, display: 'flex', alignItems: 'center' };

  Object.assign(window, { HomeScreen, DetailScreen, ReplyBar, ComposeScreen, ProfileScreen, WelcomeScreen });
})();
