// albums.jsx — My Album management (editor / detail / card / share)
(function () {
  const { useState } = React;
  const { Icon, Avatar, Cover, AlbumCover, TrackCard } = window;

  const SERVICE_KEYS = ['spotify', 'apple', 'yt', 'amazon'];

  // album "open" link: pasted playlist URL wins, else service search for the title
  function albumUrl(album) {
    if (album.playlistUrl && /^https?:\/\//.test(album.playlistUrl)) return album.playlistUrl;
    const q = encodeURIComponent(album.title);
    switch (album.service) {
      case 'spotify': return `https://open.spotify.com/search/${q}`;
      case 'apple':   return `https://music.apple.com/jp/search?term=${q}`;
      case 'yt':      return `https://music.youtube.com/search?q=${q}`;
      case 'amazon':  return `https://music.amazon.co.jp/search/${q}`;
      default: return null;
    }
  }
  window.albumUrl = albumUrl;

  // ── Album editor (create / edit) ────────────────────────────
  function AlbumEditor({ app }) {
    const T = app.theme;
    const editing = app.editingAlbum;
    const [title, setTitle] = useState(editing ? editing.title : '');
    const [desc, setDesc] = useState(editing ? editing.desc : '');
    const [tracks, setTracks] = useState(editing ? [...editing.tracks] : []);
    const [service, setService] = useState(editing ? editing.service : 'spotify');
    const [url, setUrl] = useState(editing ? editing.playlistUrl : '');
    const [q, setQ] = useState('');

    const meta = window.PF.SERVICE_META;
    const list = window.PF.TRACKS.filter(t => !q.trim() || (t.title + t.artist).toLowerCase().includes(q.toLowerCase()));
    const toggle = (id) => setTracks(ts => ts.includes(id) ? ts.filter(x => x !== id) : [...ts, id]);
    const hasUrl = /^https?:\/\//.test((url || '').trim());
    // 既存プレイリストURLを貼ればそれだけで保存OK（曲の手追加は任意）
    const canSave = !!title.trim() && (tracks.length > 0 || hasUrl);

    const save = () => {
      if (!canSave) return;
      app.saveAlbum({ id: editing ? editing.id : 'al' + Date.now(), owner: 'you', title: title.trim(), desc: desc.trim(), tracks, service, playlistUrl: url.trim() });
    };

    return (
      <div style={{ position: 'absolute', inset: 0, background: T.bg, zIndex: 84, display: 'flex', flexDirection: 'column' }}>
        <div style={{ paddingTop: 54, paddingBottom: 10, borderBottom: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: 'max(54px, env(safe-area-inset-top)) 14px 10px' }}>
          <button onClick={() => app.closeAlbumEditor()} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, color: T.text, display: 'flex' }}><Icon.close size={24} /></button>
          <span style={{ fontWeight: 800, color: T.text }}>{editing ? 'アルバムを編集' : 'アルバムを作成'}</span>
          <button onClick={save} disabled={!canSave} style={{
            border: 'none', borderRadius: 20, padding: '9px 18px', fontWeight: 800, fontSize: 14.5,
            background: canSave ? T.accent : T.surface2, color: canSave ? '#fff' : T.faint,
            cursor: canSave ? 'pointer' : 'default', fontFamily: 'inherit',
          }}>保存</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '16px 18px 60px' }}>
          {/* title + desc */}
          <input value={title} onChange={e => setTitle(e.target.value)} placeholder="アルバム名（例：夜の洗い物BGM）"
            style={{ width: '100%', background: 'none', border: 'none', outline: 'none', color: T.text,
              fontSize: 22, fontWeight: 800, fontFamily: T.display, padding: '2px 0' }} />
          <input value={desc} onChange={e => setDesc(e.target.value)} placeholder="ひとこと説明（任意）"
            style={{ width: '100%', background: 'none', border: 'none', outline: 'none', color: T.sub,
              fontSize: 14, fontFamily: 'inherit', padding: '6px 0', borderBottom: `1px solid ${T.border}` }} />

          {/* selected count */}
          <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 10 }}>
            <AlbumCover album={{ tracks }} size={56} radius={12} />
            <div>
              <div style={{ fontWeight: 800, color: T.text, fontSize: 15 }}>{tracks.length > 0 ? `${tracks.length} 曲` : (hasUrl ? 'プレイリストURLで共有' : '0 曲')}</div>
              <div style={{ color: T.faint, fontSize: 12.5 }}>{hasUrl ? 'URLを開くと全曲が再生できます' : '下のURLを貼るか、曲を選んで追加'}</div>
            </div>
          </div>

          {/* service link picker */}
          <div style={{ marginTop: 22, fontSize: 12.5, fontWeight: 800, color: T.faint, letterSpacing: 0.5 }}>メインのサブスク</div>
          <div style={{ color: T.sub, fontSize: 12.5, lineHeight: 1.55, margin: '4px 0 10px' }}>
            「アルバムを開く」ボタンが、選んだサービスにつながります。
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {SERVICE_KEYS.map(k => {
              const m = meta[k]; const on = service === k;
              return (
                <button key={k} onClick={() => setService(k)} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '11px 12px', borderRadius: 13,
                  background: on ? T.surface2 : T.surface, cursor: 'pointer', textAlign: 'left', font: 'inherit',
                  border: `1.5px solid ${on ? T.accent : T.border}`,
                }}>
                  <span style={{ width: 26, height: 26, borderRadius: 7, background: m.color, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 900, fontSize: 13, flexShrink: 0 }}>{m.glyph}</span>
                  <span style={{ flex: 1, fontSize: 13, fontWeight: 700, color: T.text }}>{m.label}</span>
                  {on && <span style={{ color: T.accent }}><Icon.check size={18} /></span>}
                </button>
              );
            })}
          </div>

          {/* paste URL */}
          <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 8, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 12, padding: '10px 12px' }}>
            <span style={{ color: T.faint }}><Icon.link size={17} /></span>
            <input value={url} onChange={e => setUrl(e.target.value)} placeholder="既存プレイリストのURLを貼る（任意）"
              style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: T.text, fontSize: 13.5, fontFamily: 'inherit' }} />
          </div>
          <div style={{ color: T.faint, fontSize: 11.5, lineHeight: 1.6, marginTop: 8 }}>
            ※ アカウント連携（ログイン）なしで共有できます。自動同期したい場合のみ、あとで連携を追加できます。
          </div>

          {/* track picker */}
          <div style={{ marginTop: 22, fontSize: 12.5, fontWeight: 800, color: T.faint, letterSpacing: 0.5, marginBottom: 10 }}>曲を追加（任意）</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 = tracks.includes(t.id);
              return (
                <button key={t.id} onClick={() => toggle(t.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '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={42} radius={9} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, color: T.text, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</div>
                    <div style={{ color: T.sub, fontSize: 12.5 }}>{t.artist}</div>
                  </div>
                  <span style={{ width: 24, height: 24, borderRadius: '50%', flexShrink: 0,
                    border: `1.5px solid ${on ? T.accent : T.border}`, background: on ? T.accent : 'none',
                    color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    {on ? <Icon.check size={15} /> : <Icon.plus size={15} />}
                  </span>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ── Album detail ────────────────────────────────────────────
  function AlbumDetail({ app, albumId }) {
    const T = app.theme;
    const album = app.albums.find(a => a.id === albumId);
    if (!album) return null;
    const meta = window.PF.SERVICE_META[album.service];
    const url = albumUrl(album);
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.bg, zIndex: 84, display: 'flex', flexDirection: 'column' }}>
        <div style={{ paddingTop: 54, paddingBottom: 10, borderBottom: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: 'max(54px, env(safe-area-inset-top)) 14px 10px' }}>
          <button onClick={() => app.closeAlbumDetail()} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, color: T.text, display: 'flex' }}><Icon.back size={22} /></button>
          <span style={{ fontWeight: 800, color: T.text }}>アルバム</span>
          <button onClick={() => app.openAlbumEditor(album)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: T.accent, fontWeight: 800, fontSize: 14, fontFamily: 'inherit' }}>編集</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '20px 18px 50px' }}>
          <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            <AlbumCover album={album} size={108} radius={16} />
            <div style={{ minWidth: 0 }}>
              <h1 style={{ fontFamily: T.display, fontSize: 22, fontWeight: 900, color: T.text, margin: 0, lineHeight: 1.3 }}>{album.title}</h1>
              {album.desc && <p style={{ color: T.sub, fontSize: 13, lineHeight: 1.55, margin: '6px 0 0' }}>{album.desc}</p>}
              <div style={{ color: T.faint, fontSize: 12.5, marginTop: 6 }}>{album.tracks.length} 曲</div>
            </div>
          </div>

          {/* open button */}
          {url && (
            <a href={url} target="_blank" rel="noreferrer" style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, textDecoration: 'none',
              marginTop: 18, padding: '14px', borderRadius: 14, background: meta ? meta.color : T.accent, color: '#fff',
              fontWeight: 800, fontSize: 15.5,
            }}>
              <Icon.play size={18} />{meta ? `${meta.label} で開く` : 'プレイリストを開く'}
            </a>
          )}
          {album.playlistUrl && <div style={{ color: T.faint, fontSize: 11.5, marginTop: 8, wordBreak: 'break-all' }}>🔗 {album.playlistUrl}</div>}

          {/* tracks */}
          <div style={{ marginTop: 22, fontSize: 12.5, fontWeight: 800, color: T.faint, marginBottom: 4 }}>収録曲</div>
          {album.tracks.map(id => app.trackById[id] && <TrackCard key={id} track={app.trackById[id]} />)}
        </div>
      </div>
    );
  }

  // ── Album card (for profile list) ───────────────────────────
  function AlbumCard({ album, app }) {
    const T = app.theme;
    const meta = window.PF.SERVICE_META[album.service];
    return (
      <button onClick={() => app.openAlbumDetail(album.id)} style={{
        display: 'flex', alignItems: 'center', gap: 13, padding: '10px 18px', width: '100%',
        background: 'none', border: 'none', borderBottom: `1px solid ${T.border}`, cursor: 'pointer', textAlign: 'left', font: 'inherit',
      }}>
        <AlbumCover album={album} size={60} radius={12} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 800, color: T.text, fontSize: 15.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{album.title}</div>
          <div style={{ color: T.sub, fontSize: 12.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{album.tracks.length}曲{album.desc ? ` · ${album.desc}` : ''}</div>
          {meta && <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 5 }}>
            <span style={{ width: 16, height: 16, borderRadius: 4, background: meta.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 900, fontSize: 9 }}>{meta.glyph}</span>
            <span style={{ fontSize: 11, color: T.faint, fontWeight: 700 }}>{meta.label}</span>
          </div>}
        </div>
        <span style={{ color: T.faint }}><Icon.back size={18} style={{ transform: 'scaleX(-1)' }} /></span>
      </button>
    );
  }

  function primaryBtn(T) {
    return { width: '100%', marginTop: 4, padding: '15px', borderRadius: 14, border: 'none',
      background: T.accent, color: '#fff', fontWeight: 800, fontSize: 16, cursor: 'pointer',
      fontFamily: 'inherit', boxShadow: `0 6px 18px ${T.accent}55` };
  }
  function ghostBtn(T) {
    return { width: '100%', marginTop: 10, padding: '13px', borderRadius: 14,
      border: `1px solid ${T.border}`, background: 'none', color: T.sub,
      fontWeight: 700, fontSize: 14.5, cursor: 'pointer', fontFamily: 'inherit' };
  }

  Object.assign(window, { AlbumEditor, AlbumDetail, AlbumCard });
})();
