/* playbook-flows.jsx — Playbook 的流程弹窗与浮条
   ❷ 邀请朋友  ❹ 发布（含登录、隐私检查）  ❺ Record 录制（确认弹窗 / 录制浮条 / 命名框）
   ❻ Import 导入  ❼ Review 草稿（展示 / 编辑）  ❽ 更新对比  （9）邮件通知预览 */
/* global React */
window.P21 = window.P21 || {};
(() => {
  const { C, MONO, SERIF, useP, Label, Btn, Check, Modal, ModalHead, X, Seg, AgentTags, AGENT_NAME, Md, D } = window.P21;
  const input = { width: '100%', border: `1px solid ${C.border}`, borderRadius: 6, padding: '8px 10px', font: 'inherit', fontSize: 14, outline: 0, color: C.ink };

  /* ───────── ❷ 邀请朋友 ───────── */
  function InviteModal({ onClose }) {
    const [copied, setCopied] = React.useState(false);
    return (
      <Modal width={560} onClose={onClose}>
        <ModalHead title="Invite a friend to share" onClose={onClose} />
        <div style={{ marginTop: 14, fontSize: 15, lineHeight: 1.55 }}>Know someone with a great way of working?<br />Invite them to publish it as a skill on Marketplace.</div>
        <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
          <div style={{ flex: 1, border: `1px solid ${C.border}`, borderRadius: 6, padding: '8px 12px', fontFamily: MONO, fontSize: 13, background: C.side }}>{D.inviteLink}</div>
          <Btn kind="primary" onClick={() => setCopied(true)}>{copied ? 'Copied ✓' : 'Copy link'}</Btn>
        </div>
      </Modal>
    );
  }

  /* ───────── ❹ 发布：没登录先登录 ───────── */
  function SignInModal({ m, onClose }) {
    const { set } = useP();
    const go = () => set({ signedOut: false, modal: m.next });
    return (
      <Modal width={420} onClose={onClose}>
        <ModalHead title="Sign in to publish" onClose={onClose} />
        <div style={{ marginTop: 10, color: C.muted, lineHeight: 1.55 }}>Publishing puts your skill on Marketplace under your name. Sign in first.</div>
        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Btn kind="primary" onClick={go} style={{ justifyContent: 'center', padding: '9px 14px' }}>Continue with Google</Btn>
          <Btn onClick={go} style={{ justifyContent: 'center', padding: '9px 14px' }}>Continue with Apple</Btn>
        </div>
      </Modal>
    );
  }

  function PublishModal({ m, onClose }) {
    const { s, set } = useP();
    const k = s.skills.find(x => x.id === m.skill);
    const [items, setItems] = React.useState(D.privacy.map(p => ({ ...p, state: 'open', value: p.token })));
    const [cat, setCat] = React.useState('Writing');
    const [desc, setDesc] = React.useState(k.desc);
    const left = items.filter(i => i.state === 'open' || i.state === 'editing').length;
    const upd = (id, patch) => setItems(items.map(i => i.id === id ? { ...i, ...patch } : i));

    const submit = () => {
      let published;
      if (m.pub) published = s.published.map(p => p.id === m.pub ? { ...p, status: 'review', submitted: 'Sep 30', desc } : p);
      else published = [{ id: 'p' + Date.now(), skill: k.id, name: k.name, desc, status: 'review', submitted: 'Sep 30' }, ...s.published];
      const pubId = m.pub || published[0].id;
      set({
        published,
        skills: s.skills.map(x => x.id === k.id ? { ...x, pub: pubId } : x),
        emails: [...s.emails, { kind: 'review', name: k.name }],
        modal: null, pbView: 'mine', mineTab: 'Published',
        toast: 'Submitted for review · We emailed you',
      });
    };

    return (
      <Modal width={600} onClose={onClose}>
        <ModalHead title={`Publish "${k.name}"`} onClose={onClose} />
        <div style={{ marginTop: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <Label>Privacy check</Label>
          <span style={{ fontSize: 12, color: left ? C.amber : C.green }}>{left ? `${left} to review` : 'All clear ✓'}</span>
        </div>
        <div style={{ marginTop: 8 }}>
          {items.map(i => (
            <div key={i.id} style={{ padding: '10px 0', borderTop: `1px solid ${C.line2}` }}>
              {i.state === 'editing' ? (
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span style={{ color: C.amber, fontWeight: 600, width: 12 }}>!</span>
                  <input autoFocus value={i.value} onChange={(e) => upd(i.id, { value: e.target.value })} style={{ ...input, flex: 1, padding: '5px 8px', fontSize: 13.5 }} />
                  <Btn small kind="primary" onClick={() => upd(i.id, { state: 'edited' })}>Done</Btn>
                </div>
              ) : (
                <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                  <span style={{ color: i.state === 'open' ? C.amber : C.green, fontWeight: 600, width: 12 }}>{i.state === 'open' ? '!' : '✓'}</span>
                  <span style={{ flex: 1, color: i.state === 'open' ? C.ink : C.muted }}>
                    {i.state === 'open' ? i.text : i.state === 'kept' ? `Kept "${i.token}"` : `Changed "${i.token}" to "${i.value}"`}
                  </span>
                  {i.state === 'open'
                    ? <><Btn small onClick={() => upd(i.id, { state: 'editing' })}>Edit</Btn><Btn small onClick={() => upd(i.id, { state: 'kept' })}>Keep</Btn></>
                    : <span onClick={() => upd(i.id, { state: 'open', value: i.token })} style={{ fontSize: 12.5, color: C.faint, cursor: 'pointer' }}>Undo</span>}
                </div>
              )}
            </div>
          ))}
        </div>
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '96px minmax(0,1fr)', gap: '12px 12px', alignItems: 'center' }}>
          <span style={{ color: C.muted }}>Category</span>
          <select value={cat} onChange={(e) => setCat(e.target.value)} style={{ ...input, width: 180, padding: '6px 8px', fontSize: 13.5, background: '#fff' }}>
            {D.categories.map(c => <option key={c}>{c}</option>)}
          </select>
          <span style={{ color: C.muted }}>Description</span>
          <input value={desc} onChange={(e) => setDesc(e.target.value)} style={input} />
          <span style={{ color: C.muted, alignSelf: 'start' }}>Price</span>
          <span><div>Free</div><div style={{ fontSize: 12.5, color: C.faint }}>Paid skills are not available yet.</div></span>
        </div>
        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Btn onClick={onClose}>Cancel</Btn>
          <Btn kind="primary" disabled={left > 0 || !desc.trim()} onClick={submit}>Submit for review</Btn>
        </div>
      </Modal>
    );
  }

  /* ───────── ❺ Record ───────── */
  function RecConfirmModal({ onClose }) {
    const { set } = useP();
    return (
      <Modal onClose={onClose}>
        <ModalHead title="Record a skill" onClose={onClose} />
        <div style={{ marginTop: 14, fontSize: 15, lineHeight: 1.55 }}>Show Persom how you do something, once. It turns what you do into a skill draft you can review and keep.</div>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 14.5 }}>
          {['Do it as you normally would', 'Click Stop, then name the skill', 'Review the draft in Suggestions'].map((t, i) => (
            <div key={t} style={{ display: 'flex', gap: 10 }}><span style={{ color: C.faint }}>{i + 1}.</span>{t}</div>
          ))}
        </div>
        <div style={{ marginTop: 16, fontSize: 13, color: C.muted }}>Tip: close anything you don't want in the skill.</div>
        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Btn onClick={onClose}>Cancel</Btn>
          <Btn kind="primary" onClick={() => set({ modal: null, rec: { phase: 'rec', sec: 0, name: '' } })}><span style={{ width: 8, height: 8, borderRadius: '50%', background: C.rec }} />Start recording</Btn>
        </div>
      </Modal>
    );
  }

  /* 录制浮条 → 命名框（浮在屏幕顶部正中） */
  function RecordBar() {
    const { s, set } = useP();
    const r = s.rec;
    const mm = `${String(Math.floor(r.sec / 60)).padStart(2, '0')}:${String(r.sec % 60).padStart(2, '0')}`;
    const create = () => {
      const name = r.name.trim(); if (!name) return;
      const id = 'r' + Date.now();
      set({ rec: null, sugg: [{ id, icon: '◉', name, note: 'Processing...', action: null, kind: 'rec', dur: mm }, ...s.sugg], page: 'Playbook', pbView: 'main', toast: 'Persom is turning this into a draft' });
      setTimeout(() => set(prev => ({ sugg: prev.sugg.map(g => g.id === id ? { ...g, note: 'Recorded today', action: 'Review' } : g) })), 3500);
    };
    const btnDark = { padding: '6px 12px', borderRadius: 6, border: '1px solid rgba(255,255,255,.25)', fontSize: 13, fontWeight: 500, cursor: 'pointer' };
    return (
      <div onClick={(e) => e.stopPropagation()}
        style={{ position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)', zIndex: 45, width: 380, background: C.ink, color: '#F3F4F1', borderRadius: 10, padding: '12px 14px', boxShadow: '0 20px 50px rgba(15,15,15,.35)', animation: 'p21pop .2s ease-out' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5, fontWeight: 500 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: C.rec, animation: r.phase === 'rec' ? 'p21blink 1.2s ease-in-out infinite' : 'none' }} />
            {r.phase === 'rec' ? 'Recording' : 'Recorded'}
          </span>
          <span style={{ fontFamily: MONO, fontSize: 13 }}>{mm}</span>
        </div>
        {r.phase === 'rec' ? (
          <div style={{ marginTop: 10, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <span onClick={() => set({ rec: null })} style={btnDark}>Cancel</span>
            <span onClick={() => set({ rec: { ...r, phase: 'name' } })} style={{ ...btnDark, background: '#F3F4F1', color: C.ink, border: '1px solid transparent' }}>Stop</span>
          </div>
        ) : (
          <>
            <div style={{ marginTop: 12, fontSize: 13, color: '#A9B0AB' }}>Name this skill</div>
            <input autoFocus value={r.name} onChange={(e) => set({ rec: { ...r, name: e.target.value } })} onKeyDown={(e) => { if (e.key === 'Enter' && !e.nativeEvent.isComposing) create(); }} placeholder="e.g. Write the weekly report"
              style={{ marginTop: 6, width: '100%', border: '1px solid rgba(255,255,255,.2)', borderRadius: 6, background: 'rgba(255,255,255,.06)', color: '#F3F4F1', padding: '8px 10px', font: 'inherit', fontSize: 13.5, outline: 0 }} />
            <div style={{ marginTop: 10, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <span onClick={() => set({ rec: null })} style={btnDark}>Discard</span>
              <span onClick={create} style={{ ...btnDark, border: '1px solid transparent', background: r.name.trim() ? C.green : '#5A5954', color: r.name.trim() ? '#fff' : '#A8A7A3', cursor: r.name.trim() ? 'pointer' : 'default' }}>Create skill</span>
            </div>
          </>
        )}
      </div>
    );
  }

  /* ───────── ❻ Import ───────── */
  function ImportModal({ onClose }) {
    const { s, set } = useP();
    const inPb = (i) => i.inPb || (s.imported || []).includes(i.id);
    const [sel, setSel] = React.useState(() => Object.fromEntries(D.importList.map(i => [i.id, !!i.on && !inPb(i)])));
    const picked = D.importList.filter(i => !inPb(i) && sel[i.id]);
    const doImport = () => {
      const add = picked.map(i => ({ id: 'k' + i.id + Date.now(), name: i.as || i.name, desc: i.desc, src: 'import', agents: [i.agent], ago: 'Just now' }));
      set({ skills: [...add, ...s.skills], imported: [...(s.imported || []), ...picked.map(i => i.id)], modal: null, toast: `Imported ${add.length} skills · in Mine › Installed` });
    };
    return (
      <Modal width={580} onClose={onClose}>
        <ModalHead title="Import skills" onClose={onClose} sub="Found 23 skills in 2 agents" />
        {['CC', 'CX'].map(a => (
          <div key={a} style={{ marginTop: 20 }}>
            <Label>{AGENT_NAME[a]}</Label>
            <div style={{ marginTop: 6 }}>
              {D.importList.filter(i => i.agent === a).map(i => {
                const dis = inPb(i);
                return (
                  <div key={i.id} onClick={() => !dis && setSel({ ...sel, [i.id]: !sel[i.id] })} style={{ padding: '9px 0', borderTop: `1px solid ${C.line2}`, cursor: dis ? 'default' : 'pointer' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <Check on={!dis && sel[i.id]} disabled={dis}><span style={{ fontWeight: 500 }}>{i.name}</span></Check>
                      <span style={{ flex: 1, fontSize: 13, color: C.faint, textAlign: 'right' }}>{dis ? 'In Playbook' : i.desc}</span>
                    </div>
                    {i.as && !dis && <div style={{ marginLeft: 26, marginTop: 3, fontSize: 12.5, color: C.amber }}>Will import as "{i.as}"</div>}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end' }}>
          <Btn kind="primary" disabled={!picked.length} onClick={doImport}>Import selected ({picked.length})</Btn>
        </div>
      </Modal>
    );
  }

  /* ───────── ❼ Review 草稿 ───────── */
  function ReviewModal({ m, onClose }) {
    const { s, set } = useP();
    const g = s.sugg.find(x => x.id === m.id);
    const rec = g.kind === 'rec';
    const src = rec ? D.recDraft : D.draft;
    const [v, setV] = React.useState({ name: g.name, desc: src.desc, body: src.body });
    const [edit, setEdit] = React.useState(null); // 编辑中的草稿副本
    const [seen, setSeen] = React.useState(false);
    const [inst, setInst] = React.useState({ CC: true, CX: false });
    const err = edit ? (!edit.name.trim() ? 'Name is required' : !edit.desc.trim() ? 'Description is required' : '') : '';

    const save = () => {
      const k = { id: 'k' + Date.now(), name: v.name, desc: v.desc, src: rec ? 'rec' : 'persom', agents: Object.keys(inst).filter(a => inst[a]), ago: 'Just now' };
      set({ skills: [k, ...s.skills], sugg: s.sugg.filter(x => x.id !== g.id), modal: null, toast: 'Saved · in Mine › Installed' });
    };
    const discard = () => set({ sugg: s.sugg.filter(x => x.id !== g.id), modal: null, toast: rec ? 'Recording discarded' : "Discarded · Persom won't draft this again" });

    return (
      <Modal width={660} onClose={onClose}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13, color: C.muted }}>
          <span onClick={onClose} style={{ cursor: 'pointer' }}>← Suggestions</span>
          <span style={{ color: rec ? C.rec : C.green }}>{rec ? '◉ Recorded' : '✦ Draft'}</span>
        </div>
        {!edit ? (<>
          <div style={{ marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-.01em' }}>{v.name}</span>
            <Btn small onClick={() => setEdit({ ...v })}>Edit</Btn>
          </div>
          <div style={{ marginTop: 4, fontSize: 15, color: C.muted }}>{v.desc}</div>
          {rec ? (
            <div style={{ marginTop: 12, fontSize: 13.5, color: C.muted }}>Recorded today · {g.dur || '03:24'}</div>
          ) : (<>
            <div onClick={() => setSeen(!seen)} style={{ marginTop: 12, fontSize: 13.5, color: C.green, cursor: 'pointer' }}>{seen ? '▾' : '▸'} {g.note}</div>
            {seen && (
              <div style={{ margin: '6px 0 0 18px', display: 'flex', flexDirection: 'column', gap: 3, fontSize: 13.5 }}>
                {src.seen.map(([d, t]) => <div key={d} style={{ display: 'flex', gap: 12 }}><span style={{ fontSize: 12, color: C.muted, width: 48 }}>{d}</span><span>{t}</span></div>)}
                <div style={{ color: C.faint }}>+ 4 more</div>
              </div>
            )}
          </>)}
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px solid ${C.line2}` }}><Md text={v.body} /></div>
          <div style={{ marginTop: 22, display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
            <span style={{ color: C.muted }}>Install to</span>
            {['CC', 'CX'].map(a => <Check key={a} on={inst[a]} onClick={() => setInst({ ...inst, [a]: !inst[a] })}>{AGENT_NAME[a]}</Check>)}
          </div>
          <div style={{ marginTop: 20, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <Btn kind="danger" onClick={discard}>Discard</Btn>
            <Btn kind="primary" onClick={save}>Save skill</Btn>
          </div>
        </>) : (
          <EditForm edit={edit} setEdit={setEdit} err={err} onCancel={() => setEdit(null)} onDone={() => { setV(edit); setEdit(null); }} />
        )}
      </Modal>
    );
  }

  /* 编辑状态：Name、Description 两个输入框 + Markdown 原文 */
  function EditForm({ edit, setEdit, err, onCancel, onDone }) {
    return (<>
      <div style={{ marginTop: 14, fontSize: 12.5, color: C.muted }}>Name</div>
      <input value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} style={{ ...input, marginTop: 4, fontSize: 15, fontWeight: 500, borderColor: !edit.name.trim() ? '#D9A99F' : C.border }} />
      <div style={{ marginTop: 12, fontSize: 12.5, color: C.muted }}>Description</div>
      <input value={edit.desc} onChange={(e) => setEdit({ ...edit, desc: e.target.value })} style={{ ...input, marginTop: 4, borderColor: !edit.desc.trim() ? '#D9A99F' : C.border }} />
      <textarea value={edit.body} onChange={(e) => setEdit({ ...edit, body: e.target.value })}
        style={{ ...input, marginTop: 12, height: 210, resize: 'vertical', fontFamily: MONO, fontSize: 13, lineHeight: 1.6 }} />
      <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
        <span style={{ fontSize: 13, color: C.red }}>{err}</span>
        <span style={{ display: 'flex', gap: 8 }}><Btn onClick={onCancel}>Cancel</Btn><Btn kind="primary" disabled={!!err} onClick={onDone}>Done</Btn></span>
      </div>
    </>);
  }

  /* ───────── ❽ 更新对比 ───────── */
  function UpdateModal({ m, onClose }) {
    const { s, set } = useP();
    const g = s.sugg.find(x => x.id === m.id);
    const u = D.updates[m.id];
    const [seen, setSeen] = React.useState(false);
    const newText = u.lines.filter(l => !l.startsWith('-')).map(l => l.startsWith('+') ? l.slice(1) : l).join('\n');
    const [edit, setEdit] = React.useState(null);
    const [edited, setEdited] = React.useState(null);
    const err = edit ? (!edit.name.trim() ? 'Name is required' : !edit.desc.trim() ? 'Description is required' : '') : '';
    const finish = (msg) => set({ sugg: s.sugg.filter(x => x.id !== g.id), modal: null, toast: msg });
    return (
      <Modal width={660} onClose={onClose}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13, color: C.muted }}>
          <span onClick={onClose} style={{ cursor: 'pointer' }}>← Suggestions</span><span>Update</span>
        </div>
        {edit ? (
          <EditForm edit={edit} setEdit={setEdit} err={err} onCancel={() => setEdit(null)} onDone={() => { setEdited(edit); setEdit(null); }} />
        ) : (<>
          <div style={{ marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-.01em' }}>{edited ? edited.name : g.name}</span>
            <Btn small onClick={() => setEdit(edited || { name: g.name, desc: (s.skills.find(k => k.name === g.name) || {}).desc || '', body: newText })}>Edit</Btn>
          </div>
          <div style={{ marginTop: 4, fontSize: 15, color: C.muted }}>{u.reason}</div>
          {u.seen && <div onClick={() => setSeen(!seen)} style={{ marginTop: 10, fontSize: 13.5, color: C.green, cursor: 'pointer' }}>{seen ? '▾' : '▸'} {u.seen}</div>}
          {seen && <div style={{ margin: '6px 0 0 18px', fontSize: 13.5, color: C.muted }}>{u.seenDetail}</div>}
          {edited && <div style={{ marginTop: 10, fontSize: 12.5, color: C.amber }}>You edited this update. Accept to apply your version.</div>}
          <div style={{ marginTop: 18, border: `1px solid ${C.line2}`, borderRadius: 10, padding: '10px 0', fontFamily: MONO, fontSize: 12.5, lineHeight: 1.7 }}>
            {u.lines.map((l, i) => {
              const p = l[0] === '+', mi = l[0] === '-', e = l.startsWith('⋯');
              return <div key={i} style={{ padding: '0 14px', whiteSpace: 'pre', background: p ? '#E9F1EA' : mi ? '#F7EEEB' : 'transparent', color: p ? C.green : mi ? C.red : e ? C.faint : C.ink }}>{p ? '+ ' + l.slice(1) : mi ? '- ' + l.slice(1) : '  ' + l}</div>;
            })}
          </div>
          {u.files.length > 0 && (
            <div style={{ marginTop: 14, fontSize: 13.5, display: 'flex', gap: 10 }}>
              <span style={{ color: C.muted }}>Files</span>
              <span style={{ fontFamily: MONO, fontSize: 12.5 }}>{u.files.join(', ')}</span>
              <span style={{ fontSize: 12, color: C.faint }}>read-only</span>
            </div>
          )}
          <div style={{ marginTop: 10, fontSize: 13.5, color: C.muted, display: 'flex', alignItems: 'center', gap: 6 }}>
            Installed in <span style={{ display: 'inline-flex', alignItems: 'center' }}><AgentTags ids={u.installed} />.</span> {u.installed.length > 1 ? 'Both' : 'It'} will be updated.
          </div>
          <div style={{ marginTop: 20, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <Btn onClick={() => finish("Ignored · Persom won't suggest this again")}>Ignore</Btn>
            <Btn kind="primary" onClick={() => finish(`Updated in Playbook and ${u.installed.map(a => AGENT_NAME[a]).join(', ')}`)}>Accept</Btn>
          </div>
        </>)}
      </Modal>
    );
  }

  /* ───────── （9）邮件通知预览 ───────── */
  const EMAILS = {
    review: { title: (u) => u ? 'Your skill update is in review' : 'Your skill is in review', body: (n, u) => [`We got ${u ? 'the update to ' : ''}"${n}" on Sep 30 at 16:42.`, 'Reviews usually take one to two days. We will email you when it is done.'], btn: 'View in Persom' },
    live: { title: (u) => u ? 'Your skill update is live on Marketplace' : 'Your skill is live on Marketplace', body: (n) => [`"${n}" went live on Marketplace on Oct 1 at 10:15.`, 'People can find it under its category and install it for free.'], btn: 'View on Marketplace' },
    rejected: { title: (u) => u ? "Your skill update wasn't approved" : "Your skill wasn't approved", body: (n) => [`"${n}" wasn't approved this time.`, 'Reason: the steps still mention a private project name.', 'How to fix it: remove or replace the name in the steps, then submit it again from Mine › Published.'], btn: 'Edit in Persom' },
  };
  function EmailsModal({ m, onClose }) {
    const { s } = useP();
    const [kind, setKind] = React.useState(m.kind || 'review');
    const [upd, setUpd] = React.useState(false);
    const last = [...s.emails].reverse().find(e => e.kind === kind);
    const name = last ? last.name : 'Weekly plan';
    const e = EMAILS[kind];
    return (
      <Modal width={600} onClose={onClose}>
        <ModalHead title="Email notifications" onClose={onClose} sub="Sent to the publisher. First publish and updates use the same three emails." />
        <div style={{ marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Seg small items={[['review', 'After submitting'], ['live', 'Approved'], ['rejected', 'Not approved']]} value={kind} onChange={setKind} />
          <Check on={upd} onClick={() => setUpd(!upd)}><span style={{ fontSize: 13 }}>Update</span></Check>
        </div>
        <div style={{ marginTop: 16, border: `1px solid ${C.line}`, borderRadius: 10, overflow: 'hidden' }}>
          <div style={{ padding: '10px 16px', background: C.side, fontSize: 12.5, color: C.muted, lineHeight: 1.6 }}>
            <div>From: Persom &lt;hello@persom.app&gt;</div><div>To: {D.user.email}</div>
            <div>Subject: <span style={{ color: C.ink, fontWeight: 500 }}>{e.title(upd)}</span></div>
          </div>
          <div style={{ padding: '22px 26px 26px' }}>
            <div style={{ fontFamily: SERIF, fontSize: 24 }}>{e.title(upd)}</div>
            {e.body(name, upd).map((p, i) => <div key={i} style={{ marginTop: 10, lineHeight: 1.6, color: i ? C.ink2 : C.ink }}>{p}</div>)}
            <div style={{ marginTop: 20 }}><Btn kind="primary">{e.btn}</Btn></div>
          </div>
        </div>
      </Modal>
    );
  }

  Object.assign(window.P21, { InviteModal, SignInModal, PublishModal, RecConfirmModal, RecordBar, ImportModal, ReviewModal, UpdateModal, EmailsModal });
})();
