/* 主页面、技能详情和 Card 管理。好友发现仍属于 Network，不在本原型扩展。 */
(() => {
  const P = window.Playbook;
  const { Button, Tag, Logo, Markdown, AgentChoices } = P;
  function SkillRow({ k }) {
    const { openSkill, openModal } = P.useApp();
    return <div className="pb-skill" role="button" tabIndex={0} aria-label={`Open ${k.name}`} onClick={() => openSkill(k.id)} onKeyDown={e => { if (e.target === e.currentTarget && ['Enter', ' '].includes(e.key)) { e.preventDefault(); openSkill(k.id); } }}>
      <div className="pb-row"><span className="pb-skill-name">{k.name}</span>{k.update && <Button onClick={e => { e.stopPropagation(); openModal({ type: 'upstream', id: k.id }); }}>Update available</Button>}</div>
      <div className="pb-skill-desc">{k.desc}</div>
      <div className="pb-skill-meta"><span>{P.source(k)}</span>{k.origin === 'friend' && <span>· v{k.version}</span>}{k.refined && <span>· Refined by Persom</span>}{k.published && <Tag green>{P.unpublished(k) ? 'Unpublished changes' : 'Shared'}</Tag>}</div>
      <div className="pb-skill-usage">{P.agentSummary(k.agents)}</div>
    </div>;
  }
  function DraftCard({ k }) {
    const { openDraft } = P.useApp();
    return <article className="pb-draft" data-draft-id={k.id}><window.P21.MiniCard serif={false} title={k.name} desc={k.desc} meta={<><div>Persom discovered this method from your recent {k.id === 'd-writing' ? 'writing sessions' : 'work'}.</div><div className="pb-draft-foot"><Button small onClick={() => openDraft(k.id)}>Review draft</Button></div></>} /></article>;
  }
  function Discovery() {
    const { data, discoveryId, setDiscoveryId, setNav, detail, modal, askOpen } = P.useApp();
    const drafts = React.useMemo(() => P.orderDrafts(data.drafts), [data.drafts]);
    const current = drafts.find(k => k.id === discoveryId) || drafts[0];
    const [hovered, setHovered] = React.useState(false), [focused, setFocused] = React.useState(false);
    /* 每次离开悬停/焦点或返回主页都重新计时，不补播暂停期间的切换。 */
    React.useEffect(() => {
      if (drafts.length < 2 || hovered || focused || detail || modal || askOpen) return;
      const timer = setTimeout(() => { const i = drafts.findIndex(k => k.id === current.id); setDiscoveryId(drafts[(i + 1) % drafts.length].id); }, 6000);
      return () => clearTimeout(timer);
    }, [drafts, current?.id, hovered, focused, detail, modal, askOpen]);
    return <section className="pb-section pb-discovery"><div className="pb-row"><span className="pb-section-head">Discovered for you</span>{drafts.length >= 2 && <button className="pb-link" onClick={() => setNav({ view: 'drafts' })}>See all ({drafts.length})</button>}</div>
      {current ? <><div className="pb-explainer">Persom discovers how you work and turns it into skill drafts.</div><div className="pb-discovery-banner" aria-label="Discovered skill draft" onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} onFocusCapture={() => setFocused(true)} onBlurCapture={e => { if (!e.currentTarget.contains(e.relatedTarget)) setFocused(false); }}><DraftCard k={current} /></div></> : <div className="pb-explainer">Persom can discover reusable methods in your everyday work and turn them into skill drafts for you to review here.</div>}
    </section>;
  }
  function Home() {
    const { data, filter, setFilter, setNav, openModal, startChat } = P.useApp();
    const [plus, setPlus] = React.useState(false);
    const menu = React.useRef(null);
    React.useEffect(() => {
      if (!plus) return;
      const close = e => { if (!menu.current?.contains(e.target)) setPlus(false); };
      const key = e => e.key === 'Escape' && setPlus(false);
      document.addEventListener('pointerdown', close); document.addEventListener('keydown', key);
      return () => { document.removeEventListener('pointerdown', close); document.removeEventListener('keydown', key); };
    }, [plus]);
    const empty = !data.drafts.length && !data.skills.length;
    const filters = P.availableFilters(data.skills);
    const activeFilter = filters.includes(filter) ? filter : 'All';
    const list = data.skills.filter(k => P.matchesFilter(k, activeFilter));
    const addItems = [
      ['Create with chat', 'Use your memories to draft a skill with Persom.', () => startChat(null, 'create')],
      ['Record a skill', 'Show Persom once, get a skill draft.', () => openModal({ type: 'recordStart' })],
      ['Import skills', 'Bring in skills you already use in agents.', () => openModal({ type: 'import' })],
    ];
    return <div className="pb-page">
      <div className="pb-row pb-page-header"><div><div className="pb-title">Playbook</div><div className="pb-subtitle">Your skills, discovered, refined and shared.</div></div><div className="pb-actions"><Button onClick={() => setNav({ view: 'card' })}>My Card</Button><div ref={menu} className="pb-plus-wrap"><Button icon aria-label="Add a skill" aria-expanded={plus} onClick={() => setPlus(!plus)}><Ic.plus size={18} /></Button>{plus && <div className="pb-menu" role="menu">{addItems.map(([name, desc, fn]) => <button role="menuitem" key={name} onClick={() => { setPlus(false); fn(); }}><span>{name}</span><small>{desc}</small></button>)}</div>}</div></div></div>
      {empty ? <div className="pb-empty pb-page-empty"><Logo /><div className="pb-empty-title" style={{ marginTop: 18 }}>Your methods can become skills.</div><p>Persom can discover reusable methods in your everyday work<br />and turn them into skill drafts for you to review here.</p><div className="pb-actions"><Button onClick={() => openModal({ type: 'recordStart' })}>Record a skill</Button><Button onClick={() => openModal({ type: 'import' })}>Import skills</Button></div></div> : <>
        <Discovery />
        <section className="pb-section"><div className="pb-section-head">Your skills <span className="pb-caption">({data.skills.length})</span></div><div className="pb-filters" role="group" aria-label="Filter skills">{filters.map(f => <button className={`pb-filter ${activeFilter === f ? 'pb-filter-on' : ''}`} aria-pressed={activeFilter === f} key={f} onClick={() => setFilter(f)}>{f}</button>)}</div>
          {list.length ? list.map(k => <SkillRow key={k.id} k={k} />) : <div className="pb-empty"><div>Import skills you already use in agents, or save a draft above.</div><div className="pb-actions"><Button onClick={() => openModal({ type: 'import' })}>Import skills</Button></div></div>}
        </section>
      </>}
    </div>;
  }
  function Detail() {
    const { current: k, isDraft, detail, setNav, startChat, openModal, commit, error, saveDraft, discardDraft } = P.useApp();
    const [agents, setAgents] = React.useState([]);
    if (!k) return null;
    return <div className="pb-detail-body">
      <div className="pb-row pb-detail-top"><div className="pb-subtitle">{k.desc}</div><Button onClick={() => k.origin === 'friend' && !isDraft ? openModal({ type: 'copy', id: k.id }) : startChat(k, isDraft ? 'draft' : 'local')}>Edit with Persom</Button></div>
      {isDraft ? <><div className="pb-skill-meta"><Tag green>Draft</Tag><span>{detail.pending ? 'Created with Persom' : 'Discovered by Persom'}</span></div>{!!k.sources.length && <details className="pb-sources"><summary>{detail.pending ? 'Recording sources' : 'Discovery sources'}</summary>{k.sources.map((s, i) => <div key={i} className="pb-source"><span className="pb-caption">{s.date}</span><span>{s.title}</span></div>)}</details>}</> : <div className="pb-detail-meta">
        <div><span className="pb-meta-label">Source</span>{P.source(k)}{k.refined && <Tag green style={{ marginLeft: 8 }}>Refined by Persom</Tag>}{k.origin === 'friend' && <span className="pb-caption"> · Author: {k.author} · v{k.version}</span>}</div>
        <div className="pb-detail-agents"><div className="pb-row"><span className="pb-meta-label">Agents{Boolean(k.agents.length) && ` (${k.agents.length})`}</span><Button onClick={() => openModal({ type: 'agents', id: k.id })}>Manage agents</Button></div><div className="pb-agent-list">{k.agents.length ? k.agents.map(a => <div key={a}>{a}</div>) : <div>Not added to an agent</div>}</div></div>
        {k.origin !== 'friend' && <div className="pb-row"><span><span className="pb-meta-label">Sharing</span>{k.published ? P.unpublished(k) ? 'Unpublished changes' : 'On your card' : 'Not shared'}</span><div className="pb-actions">{k.published ? <><Button onClick={() => setNav({ view: 'card' })}>View on My Card</Button>{P.unpublished(k) && <Button onClick={() => openModal({ type: 'publish', id: k.id })}>Update on My Card</Button>}</> : <Button onClick={() => openModal({ type: 'share', id: k.id })}>Add to My Card</Button>}</div></div>}
        {k.update && <div className="pb-row"><span className="pb-muted">A new version is available from {k.friend}.</span><Button onClick={() => openModal({ type: 'upstream', id: k.id })}>Review update</Button></div>}
      </div>}
      <Markdown text={k.files['SKILL.md']} />
      <div className="pb-body-heading">Files</div><div className="pb-files">{Object.keys(k.files).map(path => <button className="pb-file" key={path} onClick={() => openModal({ type: 'file', path, skill: k })}><Ic.doc size={16} /><code>{path}</code><Ic.chevR size={14} /></button>)}</div>
      {isDraft && <div className="pb-detail-foot"><div className="pb-actions"><span className="pb-muted">Install to</span><AgentChoices value={agents} onChange={setAgents} /></div><div className="pb-row"><span className="pb-caption">You can save without adding it to an agent.</span><div className="pb-actions"><Button danger onClick={discardDraft}>Discard</Button><Button primary onClick={() => saveDraft(agents)}>Save skill</Button></div></div>{error && <div className="pb-error" role="alert">{error}</div>}</div>}
      {!isDraft && error && <div className="pb-error" role="alert">{error}</div>}
    </div>;
  }
  function DetailDialog() {
    const { current, detail, closeDetail, modal } = P.useApp();
    return <P.Modal title={current.name} titleClassName="pb-detail-title" className="pb-detail-modal" wide suspended={!!modal} onClose={closeDetail} sharedFocusId="pb-global-ask" overlayClassName="pb-detail-overlay"><Detail key={`${detail.id || 'pending'}-${detail.draft || detail.pending ? 'draft' : 'saved'}`} /></P.Modal>;
  }
  function Card() {
    const { data, setNav } = P.useApp();
    const shared = data.skills.filter(k => k.published);
    return <div className="pb-page"><button className="pb-link pb-back" onClick={() => setNav({ view: 'home' })}><Ic.chevL size={14} />Playbook</button><div className="pb-title">My Card</div><div className="pb-subtitle">Your approved friends can view this card.</div>
      <div className="pb-card-preview"><div className="pb-card-profile"><Avatar size={50} /><div><div className="pb-card-name">Joe</div><div className="pb-muted">Writing, product thinking and research.</div></div></div><div className="pb-section"><div className="pb-row"><span className="pb-section-head">On your card</span><Button onClick={() => setNav({ view: 'shared' })}>Manage shared skills</Button></div>
        {shared.length ? shared.map(k => <div key={k.id} className="pb-shared-row"><div className="pb-skill-name">{k.published.name}</div><div className="pb-skill-desc">{k.published.desc}</div><div className="pb-row" style={{ marginTop: 12 }}><span className="pb-caption">Skill content and included files</span><Button onClick={() => setNav({ view: 'published', id: k.id })}>View shared version</Button></div></div>) : <div className="pb-empty">No skills on your card yet.</div>}
      </div></div><div className="pb-note">Only shared skill content and included files appear here. Private memory and discovery sources are not shared.</div>
    </div>;
  }
  function Shared() {
    const { data, setNav, openModal, openSkill } = P.useApp();
    return <div className="pb-page"><button className="pb-link pb-back" onClick={() => setNav({ view: 'card' })}><Ic.chevL size={14} />My Card</button><div className="pb-row"><div className="pb-title">Shared skills</div><Button onClick={() => openModal({ type: 'shareSelect' })}>Add skills</Button></div><div className="pb-subtitle">Manage the skills your approved friends can use.</div>
      {data.skills.filter(k => k.published).map(k => <article className="pb-shared-row" key={k.id}><div className="pb-skill-name">{k.name}</div><div className="pb-skill-desc">{k.desc}</div><div className="pb-row" style={{ marginTop: 12 }}><span className="pb-caption">{P.unpublished(k) ? <Tag>Unpublished changes</Tag> : 'On your card'}</span>{P.unpublished(k) && <Button onClick={() => openModal({ type: 'publish', id: k.id })}>Update on My Card</Button>}</div><div className="pb-actions" style={{ marginTop: 14 }}><Button onClick={() => openSkill(k.id)}>View skill</Button><Button danger onClick={() => openModal({ type: 'unshare', id: k.id })}>Remove from My Card</Button></div></article>)}
      {!data.skills.some(k => k.published) && <div className="pb-empty">No shared skills. Add a saved local skill to your card.</div>}
    </div>;
  }
  function Published() {
    const { data, nav, setNav, openModal } = P.useApp();
    const k = data.skills.find(x => x.id === nav.id);
    if (!k?.published) return null;
    return <div className="pb-page"><button className="pb-link pb-back" onClick={() => setNav({ view: 'card' })}><Ic.chevL size={14} />My Card</button><Tag green>Shared version</Tag><div className="pb-detail-title" style={{ marginTop: 14 }}>{k.published.name}</div><div className="pb-subtitle">{k.published.desc}</div><div className="pb-note">This is the version your approved friends can view.</div><Markdown text={k.published.files['SKILL.md']} /><div className="pb-body-heading">Files</div><div className="pb-files">{Object.keys(k.published.files).map(path => <button className="pb-file" key={path} onClick={() => openModal({ type: 'file', path, skill: k.published })}><Ic.doc size={16} /><code>{path}</code></button>)}</div></div>;
  }
  function Drafts() {
    const { data, setNav } = P.useApp();
    const drafts = P.orderDrafts(data.drafts);
    return <div className="pb-page"><button className="pb-link pb-back" onClick={() => setNav({ view: 'home' })}><Ic.chevL size={14} />Back to Playbook</button><div className="pb-title">Discovered for you ({drafts.length})</div><div className="pb-explainer">Persom discovers how you work and turns it into skill drafts.</div>{drafts.length ? <div className="pb-drafts">{drafts.map(k => <DraftCard key={k.id} k={k} />)}</div> : <div className="pb-empty">No skill drafts to review</div>}</div>;
  }
  Object.assign(P, { Home, Detail, DetailDialog, Card, Shared, Published, Drafts });
})();
