/* page-playbook.jsx — （5）Playbook：发现和创建 Skill
   主页：标题 + [ + ] 下拉 + [ Mine ]、SUGGESTIONS、MARKETPLACE
   Mine：Installed（我安装的）/ Published（我发布的） */
/* global React */
window.P21 = window.P21 || {};
(() => {
  const { C, useP, Label, More, Btn, Pill, Av, AgentTags, SRC_MARK, Ico, D } = window.P21;

  /* ───────── 主页 ───────── */
  function PlaybookMain() {
    const { s, set, openModal } = useP();
    const [plus, setPlus] = React.useState(false);
    const cats = ['All', ...D.categories];
    const cards = D.market.filter(x => s.mkCat === 'All' || x.cat === s.mkCat);
    const installed = (id) => s.skills.some(k => k.marketId === id);

    const openSugg = (g) => g.action === 'Review' ? openModal({ type: 'review', id: g.id }) : openModal({ type: 'update', id: g.id });

    return (
      <div onClick={() => setPlus(false)} style={{ maxWidth: 900, margin: '0 auto', padding: '52px 48px 140px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
          <div>
            <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1.2 }}>Playbook</div>
            <div style={{ marginTop: 6, fontSize: 15, color: C.muted }}>Find and create skills that work the way you do.</div>
          </div>
          <div style={{ display: 'flex', gap: 8, position: 'relative', marginTop: 4 }}>
            <span onClick={(e) => { e.stopPropagation(); setPlus(!plus); }} className="p21-h-soft" title="Create a skill"
              style={{ width: 34, height: 34, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 6, border: `1px solid ${C.border}`, background: plus ? C.soft : '#fff', cursor: 'pointer', fontSize: 18, lineHeight: 1 }}>+</span>
            <span onClick={() => set({ pbView: 'mine', mineTab: 'Installed' })} className="p21-h-soft"
              style={{ height: 34, display: 'inline-flex', alignItems: 'center', padding: '0 14px', borderRadius: 6, border: `1px solid ${C.border}`, background: '#fff', cursor: 'pointer', fontSize: 13.5, fontWeight: 500 }}>
              Mine
            </span>
            {plus && (
              <div onClick={(e) => e.stopPropagation()}
                style={{ position: 'absolute', top: 42, right: 0, width: 330, background: '#fff', border: `1px solid ${C.border}`, borderRadius: 10, padding: 6, boxShadow: '0 16px 40px rgba(15,15,15,.16)', zIndex: 20, animation: 'p21pop .15s ease-out' }}>
                {[['rec', 'Record a skill', 'Show Persom once, get a skill draft.', () => openModal({ type: 'recConfirm' })],
                  ['imp', 'Import skills', 'Bring in skills you already use in agents.', () => openModal({ type: 'import' })]].map(([k, t, d, fn]) => (
                  <div key={k} onClick={() => { setPlus(false); fn(); }} className="p21-h-soft" style={{ display: 'flex', gap: 12, padding: '10px 12px', borderRadius: 6, cursor: 'pointer' }}>
                    <span style={{ width: 16, display: 'flex', justifyContent: 'center', paddingTop: 5 }}>
                      {k === 'rec' ? <span style={{ width: 8, height: 8, borderRadius: '50%', background: C.rec }} /> : <span style={{ fontSize: 13, color: C.muted, lineHeight: 1 }}>⇥</span>}
                    </span>
                    <span><div style={{ fontWeight: 500 }}>{t}</div><div style={{ fontSize: 12.5, color: C.muted, marginTop: 1 }}>{d}</div></span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* SUGGESTIONS */}
        <div style={{ marginTop: 40 }}>
          <Label>Suggestions</Label>
        </div>
        <div style={{ marginTop: 8, borderBottom: `1px solid ${C.line}` }}>
          {s.sugg.length === 0 && <div style={{ padding: '14px 0', borderTop: `1px solid ${C.line}`, color: C.faint }}>Nothing to review right now.</div>}
          {s.sugg.map(g => (
            <div key={g.id} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.3fr) 90px', gap: 14, alignItems: 'center', padding: '11px 0', borderTop: `1px solid ${C.line}`, animation: 'p21fade .3s' }}>
              <span style={{ fontSize: 15, fontWeight: 500 }}><span style={{ display: 'inline-block', width: 20, color: g.icon === '◉' ? C.rec : C.green }}>{g.icon}</span>{g.name}</span>
              <span style={{ fontSize: 13.5, color: C.muted }}>
                {g.note === 'Processing...' ? <span style={{ animation: 'p21blink 1.4s ease-in-out infinite' }}>Processing...</span> : g.note}
              </span>
              <span style={{ textAlign: 'right' }}>{g.action && <Btn small onClick={() => openSugg(g)}>{g.action}</Btn>}</span>
            </div>
          ))}
        </div>

        {/* MARKETPLACE */}
        <div style={{ marginTop: 44, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Label>Marketplace</Label>
          <Btn small onClick={() => openModal({ type: 'invite' })}><Ico name="mail" size={14} />Invite a friend</Btn>
        </div>
        <div style={{ marginTop: 12, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {cats.map(c => <Pill key={c} on={s.mkCat === c} onClick={() => set({ mkCat: c })}>{c}</Pill>)}
        </div>
        <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0,1fr))', gap: 14 }}>
          {cards.map(x => (
            <div key={x.id} onClick={() => openModal({ type: 'skill', mode: 'market', id: x.id })} className="p21-h-soft"
              style={{ background: '#fff', border: `1px solid ${C.line}`, borderRadius: 10, padding: '16px 18px', cursor: 'pointer', display: 'flex', flexDirection: 'column' }}>
              <div style={{ fontSize: 15.5, fontWeight: 500 }}>{x.name}</div>
              <div style={{ marginTop: 2, fontSize: 12.5, color: C.faint }}>by {x.author} · {x.installs} installs · Free</div>
              <div style={{ marginTop: 8, color: C.muted, flex: 1 }}>{x.desc}</div>
              <div style={{ marginTop: 12, display: 'flex', justifyContent: 'flex-end' }}>
                {installed(x.id)
                  ? <span style={{ fontSize: 12.5, color: C.green, fontWeight: 500, padding: '5px 0' }}>Installed ✓</span>
                  : <Btn small onClick={(e) => { e.stopPropagation(); openModal({ type: 'skill', mode: 'market', id: x.id }); }}>Install</Btn>}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  /* ───────── Mine ───────── */
  const STATUS = {
    live: ['Live', '#2F5D45'],
    review: ['In review', '#7A5A2A'],
    rejected: ['Rejected', '#8A3B2E'],
  };

  /* 状态图标：Live 实心点 / In review 虚线空心圈 / Rejected 叉 */
  function StatusIcon({ status, color }) {
    if (status === 'rejected') return <span style={{ fontSize: 12, lineHeight: 1 }}>✕</span>;
    return <span style={{ width: 8, height: 8, borderRadius: '50%', background: status === 'live' ? color : 'transparent', border: status === 'live' ? 'none' : `1.5px dashed ${color}` }} />;
  }

  function PlaybookMine() {
    const { s, set, openModal } = useP();
    const sk = s.skills;
    const filters = [
      ['All', 'All', () => true],
      ['persom', '✦ By Persom', k => k.src === 'persom'],
      ['rec', '◉ Recorded', k => k.src === 'rec'],
      ['market', '↓ Marketplace', k => k.src === 'market'],
      ['CC', 'CC', k => k.agents.includes('CC')],
      ['CX', 'CX', k => k.agents.includes('CX')],
    ];
    const f = filters.find(x => x[0] === s.mineFilter) || filters[0];
    let list = sk.filter(f[2]);
    if (s.mineSort === 'Name') list = list.slice().sort((a, b) => a.name.localeCompare(b.name));
    const pubOf = (k) => k.pub && s.published.find(p => p.id === k.pub);

    return (
      <div style={{ maxWidth: 900, margin: '0 auto', padding: '26px 48px 140px' }}>
        <div style={{ fontSize: 14, color: C.muted, display: 'flex', alignItems: 'center' }}>
          <span onClick={() => set({ pbView: 'main' })} style={{ cursor: 'pointer', color: C.ink, display: 'inline-flex', alignItems: 'center', gap: 2 }}><Ico name="back" size={16} />Playbook</span><span style={{ margin: '0 8px' }}>/</span>Mine
        </div>
        <div style={{ marginTop: 28, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ display: 'flex', gap: 6 }}>
            <Pill on={s.mineTab === 'Installed'} onClick={() => set({ mineTab: 'Installed' })}>Installed <span style={{ opacity: .6 }}>{sk.length}</span></Pill>
            <Pill on={s.mineTab === 'Published'} onClick={() => set({ mineTab: 'Published' })}>Published <span style={{ opacity: .6 }}>{s.published.length}</span></Pill>
          </span>
          <span onClick={() => set({ mineSort: s.mineSort === 'Recent' ? 'Name' : 'Recent' })} style={{ fontSize: 13, color: C.muted, cursor: 'pointer' }}>Sort: {s.mineSort} ▾</span>
        </div>

        {s.mineTab === 'Installed' ? (<>
          <div style={{ marginTop: 14, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {filters.map(([k, label, fn]) => (
              <Pill key={k} on={f[0] === k} onClick={() => set({ mineFilter: k })} style={{ fontSize: 12.5, padding: '4px 11px' }}>
                {k === 'CC' || k === 'CX' ? <AgentTags ids={[k]} /> : label} <span style={{ opacity: .6 }}>{sk.filter(fn).length}</span>
              </Pill>
            ))}
          </div>
          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {list.map(k => {
              const p = pubOf(k);
              return (
                <div key={k.id} onClick={() => openModal({ type: 'skill', mode: 'installed', id: k.id })} className="p21-h-card"
                  style={{ background: '#fff', border: `1px solid ${C.line}`, borderRadius: 10, padding: '16px 22px', cursor: 'pointer', animation: k.ago === 'Just now' ? 'p21pop .3s' : 'none' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                    <span style={{ fontSize: 16.5, fontWeight: 500 }}>{k.name}</span>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: k.src === 'rec' ? C.rec : C.green }}>
                      {SRC_MARK[k.src] && <span title={{ persom: 'By Persom', rec: 'Recorded', market: 'Marketplace' }[k.src]}>{SRC_MARK[k.src]}</span>}
                      {p && <span title="Published" style={{ color: C.muted }}>⇪</span>}
                      <AgentTags ids={k.agents} />
                    </span>
                  </div>
                  <div style={{ marginTop: 4, color: C.muted }}>{k.desc}</div>
                  <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 28 }}>
                    <span style={{ fontSize: 12, color: C.faint }}>{k.author ? `by ${k.author} · ` : ''}{k.ago}</span>
                    {k.src !== 'market' && !p && <Btn small onClick={(e) => { e.stopPropagation(); openModal(s.signedOut ? { type: 'signin', next: { type: 'publish', skill: k.id } } : { type: 'publish', skill: k.id }); }}>Publish</Btn>}
                  </div>
                </div>
              );
            })}
          </div>
        </>) : (
          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {s.published.map(p => {
              const [label, color] = STATUS[p.status];
              return (
                <div key={p.id} className="p21-h-card" style={{ background: '#fff', border: `1px solid ${C.line}`, borderRadius: 10, padding: '16px 22px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                    <span style={{ fontSize: 16.5, fontWeight: 500 }}>{p.name}</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color, display: 'inline-flex', alignItems: 'center', gap: 6 }}><StatusIcon status={p.status} color={color} />{label}</span>
                  </div>
                  <div style={{ marginTop: 4, color: p.status === 'rejected' ? C.ink2 : C.muted }}>{p.status === 'rejected' ? `Reason: ${p.reason}` : p.desc}</div>
                  {p.updating && <div style={{ marginTop: 6, fontSize: 12.5, color: C.amber, display: 'flex', alignItems: 'center', gap: 6 }}><StatusIcon status="review" color={C.amber} />Update in review · Marketplace keeps the current version until it's approved</div>}
                  <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 28 }}>
                    <span style={{ fontSize: 12, color: C.faint }}>
                      {p.status === 'live' ? `${p.installs} installs · Live since ${p.since}` : p.status === 'review' ? `Submitted ${p.submitted}` : `Reviewed ${p.reviewed}`}
                    </span>
                    {p.status === 'live' && p.changed && !p.updating && (
                      <Btn small onClick={() => set({ published: s.published.map(x => x.id === p.id ? { ...x, updating: true } : x), emails: [...s.emails, { kind: 'review', name: p.name, update: true }], toast: 'Update submitted for review · We emailed you' })}>Submit update</Btn>
                    )}
                    {p.status === 'rejected' && <Btn small onClick={() => openModal({ type: 'publish', skill: p.skill, pub: p.id })}>Edit and resubmit</Btn>}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  function PlaybookPage() {
    const { s } = useP();
    return s.pbView === 'mine' ? <PlaybookMine /> : <PlaybookMain />;
  }

  Object.assign(window.P21, { PlaybookPage });
})();
