// DetailView.jsx — 笔记详情：时空坐标 + 正文(markdown) + 墨吞占位
const { useState: useStateDV } = React;

// —— 轻量 markdown 渲染 —— //
function mdInline(text) {
  // 转义 + 行内：**粗** *斜* `代码` [链](url)
  const parts = [];
  let key = 0;
  const re = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g;
  let last = 0, m;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) parts.push(text.slice(last, m.index));
    const tok = m[0];
    if (tok.startsWith('**')) parts.push(<strong key={key++}>{tok.slice(2, -2)}</strong>);
    else if (tok.startsWith('`')) parts.push(<code key={key++}>{tok.slice(1, -1)}</code>);
    else if (tok.startsWith('[')) {
      const mm = /\[([^\]]+)\]\(([^)]+)\)/.exec(tok);
      parts.push(<a key={key++} href={mm[2]} onClick={e => e.preventDefault()}>{mm[1]}</a>);
    } else parts.push(<em key={key++}>{tok.slice(1, -1)}</em>);
    last = m.index + tok.length;
  }
  if (last < text.length) parts.push(text.slice(last));
  return parts;
}

function Markdown({ src }) {
  const lines = src.split('\n');
  const out = [];
  let i = 0, key = 0;
  while (i < lines.length) {
    const line = lines[i];
    if (line.startsWith('```')) {
      const buf = [];
      i++;
      while (i < lines.length && !lines[i].startsWith('```')) { buf.push(lines[i]); i++; }
      i++;
      out.push(<pre key={key++}><code>{buf.join('\n')}</code></pre>);
      continue;
    }
    if (line.startsWith('### ')) { out.push(<h3 key={key++}>{mdInline(line.slice(4))}</h3>); i++; continue; }
    if (line.startsWith('## ')) { out.push(<h2 key={key++}>{mdInline(line.slice(3))}</h2>); i++; continue; }
    if (line.startsWith('# ')) { out.push(<h1 key={key++}>{mdInline(line.slice(2))}</h1>); i++; continue; }
    if (line.startsWith('---')) { out.push(<hr key={key++} />); i++; continue; }
    if (line.startsWith('> ')) {
      const buf = [];
      while (i < lines.length && lines[i].startsWith('>')) { buf.push(lines[i].replace(/^>\s?/, '')); i++; }
      out.push(<blockquote key={key++}>{buf.filter(Boolean).map((b, j) => <p key={j}>{mdInline(b)}</p>)}</blockquote>);
      continue;
    }
    if (/^[-*] /.test(line)) {
      const buf = [];
      while (i < lines.length && /^[-*] /.test(lines[i])) { buf.push(lines[i].slice(2)); i++; }
      out.push(<ul key={key++}>{buf.map((b, j) => <li key={j}>{mdInline(b)}</li>)}</ul>);
      continue;
    }
    if (line.startsWith('|') && lines[i + 1] && /^\|[\s:|-]+\|/.test(lines[i + 1])) {
      const head = line.split('|').slice(1, -1).map(s => s.trim());
      i += 2;
      const rows = [];
      while (i < lines.length && lines[i].startsWith('|')) {
        rows.push(lines[i].split('|').slice(1, -1).map(s => s.trim())); i++;
      }
      out.push(
        <table key={key++}>
          <thead><tr>{head.map((hc, j) => <th key={j}>{mdInline(hc)}</th>)}</tr></thead>
          <tbody>{rows.map((r, j) => <tr key={j}>{r.map((c, k) => <td key={k}>{mdInline(c)}</td>)}</tr>)}</tbody>
        </table>
      );
      continue;
    }
    if (line.trim() === '') { i++; continue; }
    out.push(<p key={key++}>{mdInline(line)}</p>);
    i++;
  }
  return <div className="prose">{out}</div>;
}

// —— 数字凭证（哈希确权 · 可展开折叠）—— //
function DigitalSeal({ note }) {
  const [open, setOpen] = useStateDV(false);
  const stamp = note.date + ' ' + (note.time || '00:00') + ' UTC+8';
  const hash = poporHash(note.id + '|' + note.date + note.time + '|' + note.body);
  const keyline = (note.body.match(/^>\s?(.+)$/m) || [null, note.preview])[1].slice(0, 40);
  return (
    <div className={'evidence' + (open ? ' open' : ' collapsed')}>
      <button className="ev-bar" onClick={() => setOpen(o => !o)}>
        <span className="ev-seal"><Icon name="fingerprint" size={20} /></span>
        <span className="ev-bar-main">
          <span className="ev-title">数字凭证 · Proof of Authorship</span>
          {!open && <span className="ev-bar-hash mono">{hash.slice(0, 16)}… · {note.date}</span>}
        </span>
        <Icon name="chevDown" size={16} className={'ev-chev' + (open ? ' open' : '')} />
      </button>
      {open && (
        <div className="ev-body">
          <div className="ev-row"><span className="ev-k">确权时间</span><span className="ev-v mono">{stamp}</span></div>
          <div className="ev-row"><span className="ev-k">内容哈希</span><span className="ev-v mono hash">{hash}</span></div>
          <div className="ev-row"><span className="ev-k">留存此句</span><span className="ev-v quote">“{keyline}”</span></div>
          <div className="ev-note">时间戳与哈希一同写入，作为这页文字、图像与创意属于你的数字证据。</div>
        </div>
      )}
    </div>
  );
}

// —— 这一页的来历与去向 · 整合（怎么写成的 / 变成作品 / 数字凭证）—— //
function PageAfterword({ note }) {
  const ids = (typeof noteSkillStack === 'function') ? noteSkillStack(note) : [];
  const [shared, setShared] = useStateDV(false);
  const [results, setResults] = useStateDV([]);
  const [busy, setBusy] = useStateDV(null);
  const [sealOpen, setSealOpen] = useStateDV(false);

  const stamp = note.date + ' ' + (note.time || '00:00') + ' UTC+8';
  const hash = poporHash(note.id + '|' + note.date + note.time + '|' + note.body);
  const keyline = (note.body.match(/^>\s?(.+)$/m) || [null, note.preview])[1].slice(0, 40);

  function run(tool) {
    if (busy) return;
    setBusy(tool.id);
    const rid = Date.now();
    setResults(r => [{ rid, tool, status: 'gen' }, ...r]);
    setTimeout(() => { setResults(r => r.map(x => x.rid === rid ? Object.assign({}, x, { status: 'done' }) : x)); setBusy(null); }, 1100);
  }

  return (
    <section className="dt-after">
      {/* 1 · 怎么写成的 */}
      <div className="da-row">
        <div className="da-head">
          <span className="da-k"><Icon name="layers" size={13} /> 怎么写成的</span>
          {ids.length > 0 && (
            <button className={'da-share' + (shared ? ' on' : '')} onClick={() => setShared(s => !s)}>
              <Icon name={shared ? 'check' : 'route'} size={11} /> {shared ? '已公开配方' : '共享配方'}
            </button>
          )}
        </div>
        {ids.length > 0 ? (
          <div className="da-trace">
            {ids.map((id, i) => {
              const s = skillById(id); if (!s) return null;
              return (
                <React.Fragment key={id}>
                  {i > 0 && <Icon name="chevRight" size={11} className="da-arr" />}
                  <span className={'da-chip' + (s.by !== '官方' ? ' net' : '')}><Icon name={s.icon} size={11} /> {s.name.split(' · ')[0]}</span>
                </React.Fragment>
              );
            })}
          </div>
        ) : <div className="da-muted">还没有技能足迹。</div>}
        {shared && <div className="da-hint">朋友打开这篇时，可一键把这套配方装进自己的本子 —— 内容与技能，分开分享。</div>}
      </div>

      {/* 2 · 变成作品 */}
      <div className="da-row">
        <div className="da-head">
          <span className="da-k"><Icon name="spark" size={13} /> 变成作品</span>
          <span className="da-sub">让创意从文字，走向数字化生成</span>
        </div>
        <div className="da-tools">
          {MOTUN_TOOLS.map(tl => {
            const C = GIcon[tl.ico];
            return (
              <button key={tl.id} className={'da-tool' + (busy === tl.id ? ' busy' : '')} disabled={!!busy} onClick={() => run(tl)}>
                <C size={17} /> <span>{tl.name}</span>
              </button>
            );
          })}
        </div>
        {results.length > 0 && (
          <div className="da-gen">
            {results.map(r => {
              const C = GIcon[r.tool.ico];
              return (
                <div key={r.rid} className={'da-gencard' + (r.status === 'gen' ? ' gen' : '')}>
                  <div className="da-gentop"><C size={12} /> <span className="da-genname">{r.tool.name}</span>
                    {r.status === 'gen'
                      ? <span className="da-genstate"><Icon name="refresh" size={10} className="spin" /> 生成中</span>
                      : <span className="da-genstate done"><Icon name="check" size={10} /> {r.tool.label}</span>}
                  </div>
                  <div className="da-genbody">{r.status === 'gen' ? <div className="gen-skel" /> : <ResultBody kind={r.tool.kind} />}</div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* 3 · 数字凭证 */}
      <button className={'da-row da-seal' + (sealOpen ? ' open' : '')} onClick={() => setSealOpen(o => !o)}>
        <span className="da-k"><Icon name="fingerprint" size={13} /> 数字凭证</span>
        <span className="da-sealhash mono">{hash.slice(0, 16)}… · {note.date}</span>
        <Icon name="chevDown" size={14} className={'da-chev' + (sealOpen ? ' open' : '')} />
      </button>
      {sealOpen && (
        <div className="da-sealbody">
          <div className="ev-row"><span className="ev-k">确权时间</span><span className="ev-v mono">{stamp}</span></div>
          <div className="ev-row"><span className="ev-k">内容哈希</span><span className="ev-v mono hash">{hash}</span></div>
          <div className="ev-row"><span className="ev-k">留存此句</span><span className="ev-v quote">“{keyline}”</span></div>
          <div className="ev-note">时间戳与哈希一同写入，作为这页文字、图像与创意属于你的数字证据。</div>
        </div>
      )}
    </section>
  );
}

// —— 详情页 —— //
function DetailView({ note, notebook, onBack, onWrite, onShare }) {
  if (!note) return null;
  return (
    <div className="overlay">
      <div className="ov-inner">
        <div className="dt-topbar">
          <button className="ov-back" onClick={onBack}><Icon name="arrowL" size={14} /> 返回</button>
          <div className="dt-topbar-r">
            <button className="dt-share" onClick={() => onShare && onShare(note)}>
              <Icon name="share" size={13} /> 分享
            </button>
            <button className="dt-write" onClick={() => onWrite(note)}>
              <Icon name="pencil" size={14} /> 在书写视图中打开
            </button>
          </div>
        </div>

        <h1 className="dt-title"><span className="cjk">{note.title}</span> <span style={{ fontStyle: 'italic', color: 'var(--ink-2)', fontSize: 20 }}>{note.en}</span></h1>

        <div className="dt-coords">
          <span className="dt-coord"><Icon name="calendar" size={13} /> 制作 <span className="v">{note.date}</span></span>
          <span className="dt-coord"><Icon name="download" size={13} /> 导入 <span className="v">{note.imported}</span></span>
          <span className="dt-coord"><Icon name="mapPin" size={13} /> <span className="v">{note.city}</span></span>
          <span className="dt-coord"><Icon name={SCENE_ICON[note.scene] || 'home'} size={13} /> <span className="v">{note.scene}</span></span>
          <span className="dt-coord"><Icon name="globe" size={13} /> <span className="v" style={{ fontFamily: 'var(--mono)', fontSize: 10.5 }}>{note.gps}</span></span>
        </div>

        <div className="dt-tags">
          <Tag kind="cat">{note.cat}</Tag>
          {note.notes.map(t => <Tag key={t} kind="note">{t}</Tag>)}
          {note.locs.map(t => <Tag key={t} kind="loc" icon="mapPin">{t}</Tag>)}
        </div>

        <hr className="dt-hr" />

        {note.img ? (
          <img className="dt-photo" src={note.img} alt={'原始手写照片 · ' + note.title}
               onError={e => { e.target.style.display = 'none'; }} />
        ) : note.hasPhoto ? (
          <div className="dt-photo-ph">
            <Icon name="image" size={22} />
            原始手写照片 · {note.title}
          </div>
        ) : null}

        <Markdown src={note.body} />

        {/* 来历与去向 · 整合：怎么写成的 / 变成作品 / 数字凭证 */}
        <PageAfterword note={note} />
      </div>
    </div>
  );
}

Object.assign(window, { DetailView, Markdown });
