// Skills.jsx — 技能工具箱 + 笔记技能足迹 + 分享面板
const { useState: useStateSK } = React;

function fmtUses(n) { return n >= 10000 ? (n / 10000).toFixed(1).replace(/\.0$/, '') + '万' : (n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n)); }

function loadCustomSkills() { try { return JSON.parse(localStorage.getItem('popor.skills.custom') || '[]'); } catch (_) { return []; } }
function saveCustomSkills(list) { localStorage.setItem('popor.skills.custom', JSON.stringify(list)); }

// —— 已安装技能 · 持久化（工具箱与书写台共享）——
function loadSkillInstall() { try { return JSON.parse(localStorage.getItem('popor.skills.install') || 'null'); } catch (_) { return null; } }
function saveSkillInstall(map) { localStorage.setItem('popor.skills.install', JSON.stringify(map)); }
function skillInstallMap() {
  let m = loadSkillInstall();
  if (!m) { m = {}; SKILLS.forEach(s => { if (s.installed) m[s.id] = true; }); }
  loadCustomSkills().forEach(s => { if (m[s.id] === undefined) m[s.id] = true; });
  return m;
}
function setSkillInstall(id, on) { const m = skillInstallMap(); m[id] = on; saveSkillInstall(m); }
function getInstalledSkills() {
  const m = skillInstallMap();
  return SKILLS.concat(loadCustomSkills()).filter(s => m[s.id]);
}
// 官方技能的提示词（自制技能用自己的 .prompt）。没有提示词的是影像类，走生成工具。
const SKILL_PROMPTS = {
  'text-gen':  '你是作者本人的续写助手。顺着下面这页的语气与思路，自然地接着往下写一到两段，只补充语境、不重复已有内容，不解释、不加标题。',
  'translate': '把下面这页文字翻成地道、克制的英文，保留原有分段。逐段输出中英对照：每段先原文中文，另起一行英文。',
  'summarize': '把下面这页内容提炼成 2–3 条可引用的摘录卡片，每条一句话，保留原意，用「· 」开头分行。',
  'layout':    '为下面这页拟一个清晰的结构：先一句主旨，再用小标题加要点把零散内容排成有节奏的大纲。',
};
const SKILL_TOOLMAP = { 'img-gen': 'image', 'compose': 'audio', 'video-edit': 'video', 'voice': 'tts' };
function skillPrompt(s) { return s.prompt || SKILL_PROMPTS[s.id] || null; }
function skillRunnable(s) { return !!skillPrompt(s) || !!SKILL_TOOLMAP[s.id]; }

// ========== 技能卡片 ==========
function SkillCard({ s, installed, onToggle, onDelete }) {
  const official = s.by === '官方';
  return (
    <div className={'sk-card' + (installed ? ' on' : '')}>
      <div className="sk-top">
        <span className="sk-ic"><Icon name={s.icon} size={18} /></span>
        <div className="sk-meta">
          <div className="sk-name">{s.name}</div>
          <div className="sk-by">
            {official
              ? <span className="sk-badge official">官方</span>
              : s.custom
                ? <span className="sk-badge mine">我自制</span>
                : <span className="sk-badge net">{s.byName || s.by}</span>}
            {s.shared && !official && !s.custom && <span className="sk-shared"><Icon name="route" size={10} /> 人脉分享</span>}
          </div>
        </div>
        {s.custom && <button className="sk-del" title="删除" onClick={() => onDelete(s.id)}><Icon name="x" size={12} /></button>}
      </div>
      <p className="sk-desc">{s.desc}</p>
      <div className="sk-foot">
        <span className="sk-cost">{s.custom ? <span><Icon name="spark" size={12} /> 走你接入的引擎</span> : <span><Icon name="spark" size={12} /> {s.credits} 积分/次</span>}</span>
        {!s.custom && <span className="sk-uses">{fmtUses(s.uses)} 人用过</span>}
        <button className={'sk-btn' + (installed ? ' got' : '')} onClick={() => onToggle(s.id)}>
          {installed ? <span><Icon name="check" size={12} /> 已装入</span> : <span><Icon name="plus" size={12} /> 装进本子</span>}
        </button>
      </div>
    </div>
  );
}

// ========== 订阅档位面板 ==========
function PlansPanel({ current, onPick, onClose }) {
  return (
    <div className="plans-wrap" onClick={e => { if (e.target.classList.contains('plans-wrap')) onClose(); }}>
      <div className="plans-card">
        <div className="plans-head">
          <div className="plans-t">订阅档位</div>
          <button className="ov-close sm" onClick={onClose}><Icon name="x" size={15} /></button>
        </div>
        <div className="plans-sub">订阅获得每月积分，深度模型与技能不再受限</div>
        <div className="plans-row">
          {PLANS.map(p => (
            <div key={p.id} className={'plan' + (current === p.id ? ' on' : '')}>
              <div className="plan-name">{p.name}</div>
              <div className="plan-price">{p.price === 0 ? '免费' : <span><em>¥{p.price}</em>{p.unit}</span>}</div>
              <div className="plan-credits"><Icon name="spark" size={12} /> 每月 {p.monthly} 积分</div>
              <div className="plan-blurb">{p.blurb}</div>
              <div className="plan-tiers">{p.tiers.map(t => (MODEL_TIERS.find(m => m.id === t) || {}).name).join(' · ')} 模型</div>
              <button className={'plan-btn' + (current === p.id ? ' cur' : '')} onClick={() => onPick(p.id)}>
                {current === p.id ? '当前档位' : (p.price === 0 ? '切换' : '升级')}
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ========== 技能工具箱（全屏）==========
function SkillStore({ onClose }) {
  const [cat, setCat] = useStateSK('all');
  const [custom, setCustom] = useStateSK(() => loadCustomSkills());
  const [installed, setInstalled] = useStateSK(() => skillInstallMap());
  const [plan, setPlan] = useStateSK(USER_WALLET.plan);
  const [showPlans, setShowPlans] = useStateSK(false);
  const [adding, setAdding] = useStateSK(false);
  const [form, setForm] = useStateSK({ name: '', desc: '', prompt: '', cat: 'create' });

  const connected = (typeof hasActiveKey === 'function') && hasActiveKey();
  const engineName = (typeof activeProviderName === 'function') ? activeProviderName() : '墨吞';

  const credits = (PLANS.find(p => p.id === plan) || PLANS[0]).monthly;
  const all = SKILLS.concat(custom);
  const list = all.filter(s => cat === 'all' ? true : (cat === 'mine' ? installed[s.id] : s.cat === cat));
  function toggle(id) { const on = !installed[id]; setSkillInstall(id, on); setInstalled(m => Object.assign({}, m, { [id]: on })); }

  function createSkill() {
    if (!form.name.trim() || !form.prompt.trim()) return;
    const id = 'my-' + Date.now();
    const sk = { id, name: form.name.trim(), desc: form.desc.trim() || '我自制的技能', prompt: form.prompt.trim(),
      icon: 'spark', cat: form.cat, by: '我自制', custom: true, credits: 0, uses: 0, installed: true };
    const next = custom.concat([sk]);
    setCustom(next); saveCustomSkills(next);
    setSkillInstall(id, true);
    setInstalled(m => Object.assign({}, m, { [id]: true }));
    setForm({ name: '', desc: '', prompt: '', cat: 'create' }); setAdding(false); setCat('mine');
  }
  function deleteSkill(id) {
    const next = custom.filter(s => s.id !== id);
    setCustom(next); saveCustomSkills(next);
    setSkillInstall(id, false);
    setInstalled(m => { const c = Object.assign({}, m); delete c[id]; return c; });
  }

  return (
    <div className="sheet" onClick={e => { if (e.target.classList.contains('sheet')) onClose(); }}>
      <div className="sheet-panel">
        <div className="sheet-bar">
          <button className="ov-back" onClick={onClose}><Icon name="arrowL" size={15} /> 返回工作台</button>
          <div className="sheet-title">技能工具箱<span className="sheet-sub">像插件一样调用 · 装进本子就能在书写台用</span></div>
          <div className="sheet-actions">
            <button className="wallet-pill" onClick={() => setShowPlans(true)}>
              <Icon name="spark" size={13} /> <em>{credits}</em> 积分
              <span className="wallet-plan">{(PLANS.find(p => p.id === plan) || {}).name}</span>
            </button>
          </div>
        </div>

        {/* 引擎横幅：技能跑在墨吞接入的引擎上（任意一家都行）*/}
        <div className={'sk-engine' + (connected ? ' on' : '')}>
          {connected ? (
            <React.Fragment>
              <span className="ske-dot on"></span>
              <span className="ske-t">技能运行在你接入的引擎上 · 当前 <b>{engineName}</b>　<i>DeepSeek / Gemini / Grok / ChatGPT / 千问 都行，不限 Claude</i></span>
              <button className="ske-btn" onClick={onClose}>去墨吞切换引擎</button>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <span className="ske-dot"></span>
              <span className="ske-t">技能要用 AI —— 先在顶栏「<b>墨吞</b>」接入任意一家引擎（DeepSeek / Gemini / Grok / ChatGPT / 千问）。调用时若没接入，会提醒你设置。</span>
              <button className="ske-btn" onClick={onClose}>去墨吞接入</button>
            </React.Fragment>
          )}
        </div>

        <div className="sk-filter">
          <button className={'rel-chip' + (cat === 'all' ? ' on' : '')} onClick={() => setCat('all')}>全部 <span className="rel-n">{all.length}</span></button>
          <button className={'rel-chip' + (cat === 'mine' ? ' on' : '')} onClick={() => setCat('mine')}>我的本子 <span className="rel-n">{Object.values(installed).filter(Boolean).length}</span></button>
          <span className="ct-filter-div"></span>
          {SKILL_CATS.map(c => (
            <button key={c.id} className={'rel-chip' + (cat === c.id ? ' on' : '')} onClick={() => setCat(c.id)}>{c.label}</button>
          ))}
          <button className="sk-newbtn" onClick={() => setAdding(a => !a)}><Icon name="plus" size={13} /> 新建技能</button>
        </div>

        <div className="sheet-scroll">
          {adding && (
            <div className="sk-new">
              <div className="sk-new-h"><Icon name="spark" size={14} /> 写一个你自己的技能 · 调用墨吞的引擎运行</div>
              <div className="sk-new-row">
                <input placeholder="技能名（如：解题助教 / 自动剪辑脚本）" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
                <select value={form.cat} onChange={e => setForm({ ...form, cat: e.target.value })}>
                  {SKILL_CATS.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
                </select>
              </div>
              <input placeholder="一句话说明" value={form.desc} onChange={e => setForm({ ...form, desc: e.target.value })} />
              <textarea placeholder="技能提示词 —— 调用时墨吞按这段指令工作。例：你是一名数学老师，请一步步引导学生解出下面的题，不要直接给答案。"
                value={form.prompt} onChange={e => setForm({ ...form, prompt: e.target.value })} />
              <div className="sk-new-acts">
                <button onClick={() => setAdding(false)}>取消</button>
                <button className="primary" onClick={createSkill}><Icon name="check" size={12} /> 保存并装入</button>
                <span className="sk-new-note">保存在本机 · 可在「分享技能」里传给他人</span>
              </div>
            </div>
          )}

          <div className="sk-grid">
            {list.map(s => <SkillCard key={s.id} s={s} installed={!!installed[s.id]} onToggle={toggle} onDelete={deleteSkill} />)}
          </div>
          <div className="sk-note">
            <Icon name="route" size={14} />
            <span>带 <b>人脉分享</b> 的技能来自你通讯录里的人；<b>我自制</b> 的技能调用你在墨吞接入的引擎运行，也能像这样传给别人。</span>
          </div>
        </div>
      </div>
      {showPlans && <PlansPanel current={plan} onPick={id => { setPlan(id); setShowPlans(false); }} onClose={() => setShowPlans(false)} />}
    </div>
  );
}

// ========== 笔记技能足迹（详情页内 · 这一页是怎么写成的）==========
function SkillTrace({ note, onShareSkill }) {
  const ids = noteSkillStack(note);
  const [shared, setShared] = useStateSK(false);
  if (!ids.length) return null;
  return (
    <div className="trace">
      <div className="trace-head">
        <span className="trace-t"><Icon name="layers" size={14} /> 这一页是怎么写成的</span>
        <button className={'trace-share' + (shared ? ' on' : '')} onClick={() => setShared(v => !v)}>
          <Icon name={shared ? 'check' : 'route'} size={12} /> {shared ? '已公开技能配方' : '共享这套技能'}
        </button>
      </div>
      <div className="trace-flow">
        {ids.map((id, i) => {
          const s = skillById(id); if (!s) return null;
          return (
            <React.Fragment key={id}>
              {i > 0 && <Icon name="chevRight" size={12} className="trace-arr" />}
              <span className={'trace-chip' + (s.by !== '官方' ? ' net' : '')}>
                <Icon name={s.icon} size={12} /> {s.name.split(' · ')[0]}
              </span>
            </React.Fragment>
          );
        })}
      </div>
      {shared && (
        <div className="trace-hint">
          <Icon name="users" size={12} /> 朋友打开这篇时，可一键把这套配方装进自己的本子 —— 内容与技能，分开分享。
        </div>
      )}
    </div>
  );
}

// ========== 分享面板（内容 / 技能 两路）==========
const SHARE_CHANNELS = [
  { id: 'popor', label: 'Popor 好友', dot: '伴', cls: 'popor' },
  { id: 'wechat', label: '微信', dot: '微', cls: 'wechat' },
  { id: 'instagram', label: 'Instagram', dot: 'IG', cls: 'ins' },
  { id: 'twitter', label: 'Twitter', dot: 'X', cls: 'tw' },
  { id: 'link', label: '复制链接', dot: '链', cls: 'link' },
];
function ShareSheet({ note, onClose }) {
  const [mode, setMode] = useStateSK('content');   // content | skill
  const [done, setDone] = useStateSK(null);
  const [picked, setPicked] = useStateSK({});
  const stack = noteSkillStack(note);

  function fire(ch) {
    if (mode === 'content' && ch.id === 'popor') return; // 站内好友走选择
    const what = mode === 'content' ? '这一页' : '这套技能配方';
    setDone(ch.id === 'link' ? '链接已复制（演示）' : `已把${what}分享到${ch.label}（演示）`);
    setTimeout(() => setDone(null), 1800);
  }

  return (
    <div className="share-wrap" onClick={e => { if (e.target.classList.contains('share-wrap')) onClose(); }}>
      <div className="share-card">
        <div className="share-head">
          <div className="share-t">分享</div>
          <button className="ov-close sm" onClick={onClose}><Icon name="x" size={15} /></button>
        </div>

        <div className="share-tabs">
          <button className={'share-tab' + (mode === 'content' ? ' on' : '')} onClick={() => setMode('content')}>
            <Icon name="book" size={14} /> 分享内容
            <span className="share-tab-s">这篇日记本身</span>
          </button>
          <button className={'share-tab' + (mode === 'skill' ? ' on' : '')} onClick={() => setMode('skill')}>
            <Icon name="layers" size={14} /> 分享技能
            <span className="share-tab-s">它是怎么写成的</span>
          </button>
        </div>

        <div className="share-preview">
          {mode === 'content' ? (
            <div className="sp-content">
              <div className="sp-title">{note.title}</div>
              <div className="sp-prev">{note.preview}</div>
              <div className="sp-meta">{note.date} · {note.city}</div>
            </div>
          ) : (
            <div className="sp-skill">
              <div className="sp-skill-h">这一页用到的技能配方</div>
              <div className="trace-flow">
                {stack.map((id, i) => {
                  const s = skillById(id); if (!s) return null;
                  return (
                    <React.Fragment key={id}>
                      {i > 0 && <Icon name="chevRight" size={12} className="trace-arr" />}
                      <span className={'trace-chip' + (s.by !== '官方' ? ' net' : '')}><Icon name={s.icon} size={12} /> {s.name.split(' · ')[0]}</span>
                    </React.Fragment>
                  );
                })}
              </div>
              <div className="sp-skill-f">对方可一键把这套配方装进自己的本子</div>
            </div>
          )}
        </div>

        {mode === 'content' && (
          <div className="share-friends">
            <div className="share-k">发给 Popor 好友</div>
            <div className="friend-row">
              {CONTACTS.slice(0, 6).map(c => (
                <button key={c.id} className={'friend' + (picked[c.id] ? ' on' : '')} onClick={() => setPicked(p => Object.assign({}, p, { [c.id]: !p[c.id] }))}>
                  <span className="friend-av" style={{ background: c.av }}>{c.name.slice(0, 1)}</span>
                  <span className="friend-n">{c.name}</span>
                  {picked[c.id] && <span className="friend-ck"><Icon name="check" size={10} /></span>}
                </button>
              ))}
            </div>
            {Object.values(picked).some(Boolean) && (
              <button className="friend-send" onClick={() => { setDone('已发给 ' + Object.keys(picked).filter(k => picked[k]).length + ' 位好友（演示）'); setTimeout(() => setDone(null), 1800); }}>
                <Icon name="send" size={13} /> 发送给所选好友
              </button>
            )}
          </div>
        )}

        <div className="share-k">分享到</div>
        <div className="share-channels">
          {SHARE_CHANNELS.filter(ch => !(mode === 'content' && ch.id === 'popor')).map(ch => (
            <button key={ch.id} className="share-ch" onClick={() => fire(ch)}>
              <span className={'src-dot ' + ch.cls}>{ch.dot}</span>
              <span>{ch.label}</span>
            </button>
          ))}
        </div>

        {done && <div className="share-done"><Icon name="check" size={14} /> {done}</div>}
      </div>
    </div>
  );
}

Object.assign(window, { SkillStore, SkillTrace, ShareSheet, PlansPanel,
  getInstalledSkills, skillInstallMap, setSkillInstall, skillPrompt, skillRunnable, SKILL_TOOLMAP });
