/* page-demo-detail.jsx — 三级页：技术广场条目详情 (HuggingFace 式)
   Tabs: Card（介绍/链接/封面） · Files（文件 + 上传） · Comments（评论） */

function hueOf(it) { return it.hue || 222; }

const IcGit2 = (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.1.68-.22.68-.49v-1.7c-2.78.62-3.37-1.21-3.37-1.21-.45-1.18-1.11-1.49-1.11-1.49-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.56 2.36 1.11 2.94.85.09-.66.35-1.11.63-1.37-2.22-.26-4.56-1.14-4.56-5.06 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.27 2.75 1.05A9.4 9.4 0 0 1 12 6.84c.85 0 1.71.12 2.51.34 1.91-1.32 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.93-2.34 4.8-4.57 5.05.36.32.68.94.68 1.9v2.82c0 .27.18.6.69.49A10.26 10.26 0 0 0 22 12.25C22 6.58 17.52 2 12 2z" /></svg>;
const IcLink2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1" /><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1" /></svg>;
const IcDoc2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /><path d="M14 3v5h5" /></svg>;
const IcUp2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 16V4M7 9l5-5 5 5" /><path d="M5 20h14" /></svg>;
const IcFile2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /><path d="M14 3v5h5" /></svg>;
const IcStar2 = (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 2.6l2.9 6 6.5.9-4.7 4.6 1.1 6.5L12 18.9 6.1 21.1l1.1-6.5L2.5 9.5l6.5-.9L12 2.6z" /></svg>;
const IcFork2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="6" cy="5" r="2.4" /><circle cx="18" cy="5" r="2.4" /><circle cx="12" cy="19" r="2.4" /><path d="M6 7.4v2.1a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.4M12 12.5v4.1" /></svg>;
const IcExt2 = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M7 17L17 7M8 7h9v9" /></svg>;

function filesFor(it) {
  const base = [{ n: 'README.md', s: '4.2 kB' }];
  if (it.type === '模型') return [...base, { n: 'config.json', s: '1.1 kB' }, { n: 'model.safetensors', s: '1.3 GB' }, { n: 'tokenizer.json', s: '2.4 MB' }];
  if (it.type === '数据集') return [...base, { n: 'dataset_info.json', s: '0.8 kB' }, { n: 'data/train.jsonl', s: '128 MB' }, { n: 'data/test.jsonl', s: '14 MB' }];
  if (it.type === 'Skill') return [...base, { n: 'skill.yaml', s: '0.9 kB' }, { n: 'prompt.md', s: '3.1 kB' }, { n: 'examples/', s: '— 目录' }];
  if (it.type === 'Agent') return [...base, { n: 'agent.yaml', s: '1.4 kB' }, { n: 'tools/', s: '— 目录' }, { n: 'config.json', s: '1.0 kB' }];
  return [...base, { n: 'package.json', s: '0.7 kB' }, { n: 'src/index.ts', s: '8.6 kB' }];
}

function ItemComments({ idx }) {
  const db = useKataDB();
  const w = db.getWork(idx);
  const list = w ? w.comments : [];
  const [draft, setDraft] = React.useState('');
  const send = (e) => { e.preventDefault(); const v = draft.trim(); if (!v) return; db.addWorkComment(idx, v); setDraft(''); };
  return (
    <div className="panel comments event-glass">
      <h2>讨论与反馈</h2>
      <form className="reply" onSubmit={send} style={{ marginBottom: 8 }}>
        <Avatar name="你" hue={205} size={40} />
        <div className="field">
          <input className="input" placeholder="留下你的评论或问题…" value={draft} onChange={(e) => setDraft(e.target.value)} />
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
            <button className="btn btn-accent" type="submit" style={{ padding: '10px 22px', fontSize: 14 }}>发布评论</button>
          </div>
        </div>
      </form>
      <div style={{ marginTop: 10 }}>
        {list.map((c) => (
          <div className="cmt" key={c.id}>
            <Avatar name={c.name} hue={c.hue} size={40} />
            <div className="cbody">
              <div className="chead"><span className="n">{c.name}</span><span className="t">{c.t}</span></div>
              <div className="ctext">{c.text}</div>
              <span className="clike"><IcHeart />赞</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DemoDetailPage({ routeParam }) {
  const db = useKataDB();
  const idx = parseInt(routeParam, 10);
  const items = db.works();
  const i0 = Number.isFinite(idx) ? idx : 0;
  const it = items[i0];
  const [tab, setTab] = React.useState('card');
  if (!it) {
    return <div className="kc dview"><a className="back" href="#demo"><Arrow size={14} />返回</a><div className="panel nm-rise"><p>没有找到这个条目。</p></div></div>;
  }
  const liked = db.isWorkLiked(i0);
  const grad = `linear-gradient(150deg, hsl(${hueOf(it)} 62% 58%), hsl(${hueOf(it) + 26} 60% 46%))`;
  const related = items.filter((x) => x !== it && x.type === it.type);
  const others = items.filter((x) => x !== it && x.type !== it.type);
  const relAny = [...related, ...others].slice(0, 3);
  const files = filesFor(it);
  const srcUrl = it.source_url || it.homepage || '';
  const isHF = /huggingface\.co/.test(srcUrl);
  const isGH = /github\.com/.test(srcUrl);
  const sourceName = isHF ? 'Hugging Face' : (isGH ? 'GitHub' : '源站');
  const links = srcUrl
    ? [{ icon: isHF ? <span className="hf-emoji">🤗</span> : <IcGit2 />,
         label: isHF ? '在 Hugging Face 打开' : (isGH ? '在 GitHub 打开' : '打开源站'),
         href: srcUrl }]
    : [
        { icon: <span className="hf-emoji">🤗</span>, label: 'Hugging Face', href: '' },
        { icon: <IcGit2 />, label: 'GitHub', href: '' },
        { icon: <IcDoc2 />, label: 'arXiv', href: '' },
      ];

  return (
    <div className="kc dview demo-detail">
      <div className="event-page-glow" aria-hidden="true" />
      <a className="back" href="#demo"><Arrow size={14} />返回技术广场</a>

      <div className="item-hero">
        <span className="thumb-lg" style={{ background: grad }}><WorkIcon type={it.type} size={30} stroke={1.9} /></span>
        <div className="ttl">
          <h1>{it.name}</h1>
          <div className="by"><span className="tbadge nm-sink-sm">{it.type}</span><span>@{it.author}</span><span>·</span><b>{it.task}</b></div>
          <div className="link-row">
            {links.map((l) => <a key={l.label} className="link-chip" href={l.href || '#'} target={l.href ? '_blank' : undefined} rel={l.href ? 'noopener noreferrer' : undefined} onClick={l.href ? undefined : (e) => e.preventDefault()}>{l.icon}{l.label}</a>)}
          </div>
        </div>
      </div>

      <div className="dtabs">
        <button className={tab === 'card' ? 'on' : ''} onClick={() => setTab('card')}>Card</button>
        <button className={tab === 'files' ? 'on' : ''} onClick={() => setTab('files')}>Files</button>
        <button className={tab === 'comments' ? 'on' : ''} onClick={() => setTab('comments')}>Comments</button>
      </div>

      <div className="dcols">
        <div className="dmain">
          {tab === 'card' && (
            <React.Fragment>
              {it.cover
                ? (/\.(mp4|webm|mov)(\?|$)/i.test(it.cover)
                    ? <video src={it.cover} controls className="card-cover" style={{ display: 'block', width: '100%', borderRadius: 20, marginBottom: 18 }} />
                    : <img src={it.cover} alt={it.name} className="card-cover" style={{ display: 'block', width: '100%', borderRadius: 20, marginBottom: 18 }} />)
                : <image-slot id={'cover-' + i0} class="card-cover" shape="rounded" radius="20" placeholder="封面图 / 截图（可选）"></image-slot>}
              <div className="panel event-glass readme">
                <div className="readme-bar"><h2 style={{ margin: 0 }}>简介</h2><span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-faint)' }}>收录自 {sourceName}</span></div>
                <p>「{it.name}」是一个面向 <b>{it.task}</b> 场景的 {it.type}，由 {it.org || ('@' + it.author)} 在 {sourceName} 发布并维护。</p>
                {it.blurb && <p style={{ whiteSpace: 'pre-wrap' }}>{it.blurb}</p>}
                <p>本条目由技术广场自动收录，仅展示公开信息与摘要（作者、许可证、热度等）。完整说明、使用方式与文件请前往 {sourceName} 原始页面查看；如需体验、下载或集成，请遵循其 {it.license && it.license !== '未标注' ? it.license : '原始'} 许可证。</p>
                {srcUrl && <p className="readme-source"><a href={srcUrl} target="_blank" rel="noopener noreferrer">前往 {sourceName} 查看完整内容 <IcExt2 style={{ width: 13, height: 13 }} /></a></p>}
                <div className="taglist" style={{ marginTop: 18 }}>
                  <span className="ptag">#{it.task}</span><span className="ptag">#{it.type}</span>{it.license && it.license !== '未标注' && <span className="ptag">#{it.license}</span>}
                </div>
              </div>
            </React.Fragment>
          )}

          {tab === 'files' && (
            <div className="panel event-glass">
              <div className="demo-empty">
                <span className="de-ic"><IcFile2 style={{ width: 22, height: 22 }} /></span>
                <h3>文件托管在源站</h3>
                <p>这是技术广场从 {sourceName} 收录的条目，本站不托管权重、数据集或代码。完整文件与版本请前往原始页面查看。</p>
                {srcUrl
                  ? <a className="btn btn-accent" href={srcUrl} target="_blank" rel="noopener noreferrer">在 {sourceName} 查看文件 <IcExt2 style={{ width: 14, height: 14 }} /></a>
                  : <span className="muted" style={{ fontSize: 13 }}>暂无源站链接</span>}
              </div>
            </div>
          )}

          {tab === 'comments' && <ItemComments idx={i0} />}
        </div>

        <aside className="dside">
          <div className="panel meta-card event-glass">
            <h2 style={{ fontSize: 16 }}>信息</h2>
            <div className="mrow"><span className="k">类型</span><span className="v">{it.type}</span></div>
            <div className="mrow"><span className="k">任务</span><span className="v">{it.task}</span></div>
            <div className="mrow"><span className="k">作者</span><span className="v">@{it.author}</span></div>
            <div className="mrow"><span className="k">更新</span><span className="v">{it.updated}</span></div>
            <div className="mrow"><span className="k">许可证</span><span className="v">{it.license || '未标注'}</span></div>
            {srcUrl && <div className="mrow"><span className="k">来源</span><span className="v">{sourceName}</span></div>}
            <div className="meta-stats">
              <span className="item-stat">{isGH ? <IcStar2 style={{ width: 15, height: 15 }} /> : <IcHeart />}<b>{it.likes}</b> {isGH ? 'Star' : '点赞'}</span>
              <span className="item-stat">{isGH ? <IcFork2 style={{ width: 15, height: 15 }} /> : <IcUp style={{ transform: 'rotate(180deg)' }} />}<b>{it.runs}</b> {isGH ? 'Fork' : '下载'}</span>
            </div>
            <button className="btn btn-accent btn-full" style={{ marginTop: 16 }} onClick={() => db.toggleLikeWork(i0)}>{liked ? '已喜欢 ✓' : '喜欢这个作品'} <IcHeart style={{ width: 15, height: 15, fill: liked ? 'currentColor' : 'none' }} /></button>
          </div>
          <div className="panel event-glass">
            <h2 style={{ fontSize: 16 }}>相关推荐</h2>
            <div className="rel">
              {relAny.map((r) => (
                <a key={r.name} href={'#demo_item/' + items.indexOf(r)}>
                  <span className="sq" style={{ background: `linear-gradient(150deg, hsl(${hueOf(r)} 62% 58%), hsl(${hueOf(r) + 26} 60% 46%))` }}><WorkIcon type={r.type} size={16} stroke={1.9} /></span>
                  <span style={{ minWidth: 0 }}><div className="nm">{r.name}</div><div className="ty">{r.type} · {r.task}</div></span>
                </a>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

(window.__KATA_PAGES = window.__KATA_PAGES || {}).demo_item = { Comp: DemoDetailPage, active: 'demo' };
