import React, { useState } from 'react'

const SCOPES = [
  ['substance', '实质'],
  ['form', '形式'],
  ['feeling', '感受'],
  ['effect', '作用'],
  ['intent', '意图'],
]
const SC_CN = Object.fromEntries(SCOPES)
const TYPE_CN = { how: 'How', what: 'What', why: 'Why' }
const TYPE_LABEL = { how: '怎么做', what: '是什么', why: '为什么' }

const STEPS = [
  ['读懂帖子', '把图、视频读成文字'],
  ['判断是否是创作知识', '不是就整帖跳过'],
  ['拆出知识', '拆成 How / What / Why'],
  ['校验 how 的严谨性', '假工序拆回 What / Why'],
  ['给知识归类', '标作用域并定位分类树'],
  ['生成 payload', '整理成统一入库格式'],
]

function mediaUrl(asset) {
  return asset?.cdn_url || asset?.oss_url || asset?.source_url || ''
}

function compactJson(value) {
  return JSON.stringify(value || {}, null, 2)
}

function stageList(value) {
  if (Array.isArray(value)) return value
  return value ? [value] : []
}

function sourceImages(item) {
  return (item?.media_assets || [])
    .filter((asset) => ['image', 'cover', 'frame'].includes(asset.media_type))
    .map(mediaUrl)
    .filter(Boolean)
}

function sourceVideo(item) {
  const asset = (item?.media_assets || []).find((row) => row.media_type === 'video')
  return asset ? mediaUrl(asset) : ''
}

function scopeClass(scopeType) {
  return `s-${scopeType || 'intent'}`
}

function ScopeChip({ scope, showType = false }) {
  return (
    <span className={`sv ${scopeClass(scope.scope_type)}`}>
      {showType && <span className="k">{SC_CN[scope.scope_type] || scope.scope_type}</span>}
      {scope.scope_value || scope.value}
      <span className="mk mk-new">新</span>
    </span>
  )
}

function KScopes({ scopes }) {
  if (!scopes?.length) return null
  return (
    <div className="kscopes">
      <span className="lab">作用域（5 棵树）：</span>
      {scopes.map((scope, idx) => <ScopeChip key={`${scope.scope_type}-${scope.scope_value}-${idx}`} scope={scope} showType />)}
    </div>
  )
}

export function Ribbon() {
  return (
    <div className="ribbon">
      <div className="rcap">这套系统怎么「从帖子拆解知识」——从真实单例跑出的状态回看</div>
      <div className="rsteps">
        {STEPS.map(([label, desc], idx) => (
          <React.Fragment key={label}>
            {idx > 0 && <span className="rarrow">→</span>}
            <div className={`rstep ${idx === 5 ? 'auto' : ''}`}>
              <div className="rtop"><span className="rn">{idx + 1}</span><span className="rlab">{label}</span></div>
              <div className="rdesc">{desc}</div>
              <div className="rbtn">{idx === 5 ? '⚙️ 程序自动' : '已完成'}</div>
            </div>
          </React.Fragment>
        ))}
      </div>
    </div>
  )
}

export function SourceDetails({ item, readText, onZoom, originalText = "" }) {
  const images = sourceImages(item)
  const video = sourceVideo(item)
  return (
    <details className="src" open>
      <summary>原帖：{item?.title || '无标题'}（这一帖的原料）· {item?.platform || 'unknown'}{video ? ' · 视频' : images.length ? ` · ${images.length} 图` : ''}</summary>
      <div className="srcbody">
        {item?.canonical_url && <a href={item.canonical_url} target="_blank" rel="noreferrer">{item.canonical_url}</a>}
        {video ? (
          <div className="srcvideo"><video src={video} controls /></div>
        ) : (
          <div className="srcimgs">
            {images.map((url, idx) => <img key={url} src={url} title={url} onClick={() => onZoom(url)} alt={`原帖图 ${idx + 1}`} />)}
          </div>
        )}
        {originalText && <div className="src-original-text">② 原帖全文：{originalText}</div>}
        {readText && <div className="srcread">① 读懂后的内容：{readText}</div>}
      </div>
    </details>
  )
}

function HowTable({ knowledge }) {
  const steps = knowledge.steps || []
  const scOf = (step, type) => (step['作用域'] || []).filter((scope) => scope.scope_type === type)
  return (
    <div className="twrap">
      <table className="proc">
        <thead>
          <tr>
            <th className="c-idx" rowSpan="2">#</th>
            <th className="g-frame" colSpan="5">② 拆框架</th>
            <th className="g-scope" colSpan="5">③ 作用域</th>
          </tr>
          <tr>
            <th className="c-intent">输入</th>
            <th className="c-cstage cstage-h">创作<br />阶段 ▸</th>
            <th className="c-act">动作<br />（模型推导）</th>
            <th className="c-dir">方法</th>
            <th className="c-out">产出</th>
            {SCOPES.map(([key, label]) => <th key={key} className={`c-scope s-${key}`}>{label}</th>)}
          </tr>
        </thead>
        <tbody>
          {steps.map((step, idx) => {
            return (
              <tr className="step" key={step.id || idx}>
                <td className="idx">{idx + 1}</td>
                <td className="intent">
                  <span className="in-txt">{step.input || '未写'}</span>
                </td>
                <td className="cstage">{step['创作阶段'] && <span className="cstage-chip">{step['创作阶段']}</span>}</td>
                <td className="act">{step['动作'] && <span className="act-chip">{step['动作']}</span>}</td>
                <td className="dir"><span className="dir-txt">{step.directive || '未写'}</span></td>
                <td className="out"><span className="out-txt">{step.output || '未写'}</span></td>
                {SCOPES.map(([key]) => (
                  <td key={key} className={`scope s-${key}`}>
                    {scOf(step, key).map((scope, scopeIdx) => <ScopeChip key={scopeIdx} scope={scope} />)}
                  </td>
                ))}
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

function WhatCard({ knowledge, scopes }) {
  const body = knowledge.body || []
  return (
    <div>
      {(knowledge['概要'] || knowledge.kind) && (
        <div className="def">
          {knowledge.kind && <span className={`kindb kind-${knowledge.kind}`}>{knowledge.kind}</span>}
          {knowledge['维度拆分规则'] && <span className="dimrule">按「{knowledge['维度拆分规则']}」拆</span>}
          {knowledge['概要'] && <>概要：{knowledge['概要']}</>}
        </div>
      )}
      {body.length > 0 && (
        <table className="elem">
          <tbody>
            {body.map((row, idx) => (
              <tr key={`${row.item_name || 'row'}-${idx}`}>
                <td className="el">{row.item_name || `条目 ${idx + 1}`}</td>
                <td>{row.item_desc || '暂无描述'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      <KScopes scopes={scopes} />
    </div>
  )
}

function WhyCard({ knowledge, scopes }) {
  return (
    <div>
      {(knowledge['阐述'] || knowledge.desc) && <div className="why-exp">{knowledge['阐述'] || knowledge.desc}</div>}
      <KScopes scopes={scopes} />
    </div>
  )
}

export function KnowledgeCard({ particle, idx, scopes, payload, onJson }) {
  const knowledge = particle.content || {}
  const type = particle.particle_type || knowledge.type || 'what'
  return (
    <div className="kcard" id={`k-${particle.id}`}>
      <div className="khead">
        <span className="kno">第{idx + 1}颗知识</span>
        <span className={`ktype ty-${type}`}>{TYPE_CN[type] || type}</span>
        <span className="ktitle">{particle.title || knowledge.title || '未命名知识'}</span>
        <span className="krole">{TYPE_LABEL[type] || type}</span>
        {stageList(particle.business_stage || knowledge['业务阶段']).map((stage) => <span className="kbiz" key={stage}>业务阶段：{stage}</span>)}
        <span className="kacts">{payload && <button className="lbtn" onClick={() => onJson(payload.payload)}>⚙️ 入库 payload</button>}</span>
      </div>
      <div className="kbody">
        {type === 'how' && <HowTable knowledge={knowledge} />}
        {type === 'what' && <WhatCard knowledge={knowledge} scopes={scopes} />}
        {type === 'why' && <WhyCard knowledge={knowledge} scopes={scopes} />}
      </div>
    </div>
  )
}

export function PayloadModal({ payload, onClose }) {
  const [copied, setCopied] = useState(false)
  if (!payload) return null
  const copy = () => {
    navigator.clipboard?.writeText(compactJson(payload)).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 1200)
    })
  }
  return (
    <div className="modal" onClick={onClose}>
      <div className="mbox" onClick={(event) => event.stopPropagation()}>
        <h2>
          ⚙️ ingest payload（给机器看）
          <button className="lbtn copybtn" onClick={copy}>{copied ? '✓ 已复制' : '📋 复制 JSON'}</button>
          <span className="x" onClick={onClose}>×</span>
        </h2>
        <div className="body"><pre>{compactJson(payload)}</pre></div>
      </div>
    </div>
  )
}
