// ===== page-trial-report.jsx =====
// 免费试用：粘贴 100-2000 字文本 → LLM 实时分析前 1000 字 → 展示部分结果 + 锁定剩余 + CTA

const { useState: useSTR, useEffect: useETR, useRef: useRTR } = React;

const SAMPLE_TEXT = '在新时代的背景下，我们要充分认识到文化遗产保护的重要性。值得注意的是，文化遗产数字化保护是一项系统性工程，需要多方协同。综上所述，加强文化遗产数字化保护，对于传承中华优秀传统文化具有重要意义，能够有效推动文化事业的高质量发展。本研究将从多个维度对该问题进行深入剖析，构建系统化的理论分析框架，为后续研究提供有益参考。本文采用文献研究法、问卷调查法、案例分析法相结合的研究方法，全方位、多层次地剖析青年消费者品牌忠诚度的形成机制。从总体上看，研究表明，社交媒体互动对品牌忠诚度具有显著的正向影响。具体而言，互动频率、互动质量与互动深度均发挥着积极的促进作用。';

const LEVEL_META_TRIAL = {
  low:        { label: '低风险',    tone: 'ok',   desc: '前 1000 字呈现明显的人类写作特征。可以放心继续写作。' },
  mid:        { label: '中风险',    tone: 'warn', desc: '前 1000 字部分段落呈现可疑特征，建议改写后再做全文检测。' },
  'mid-high': { label: '中高风险',  tone: 'bad',  desc: '前 1000 字已发现明显 AI 生成痕迹，建议改写后再做全文检测。' },
  high:       { label: '高风险',    tone: 'bad',  desc: '前 1000 字呈现强烈的 AI 生成统计特征，建议系统性改写。' },
};

function TrialReportPage({ navigate }) {
  // States: idle → analyzing → result → error
  const [stage, setStage]   = useSTR('idle');
  const [text, setText]     = useSTR('');
  const [result, setResult] = useSTR(null);
  const [error, setError]   = useSTR(null);

  const submit = async () => {
    if (text.trim().length < 100) return;
    setStage('analyzing');
    setError(null);
    try {
      const data = await window.API.trial(text);
      setResult(data);
      setStage('result');
      setTimeout(() => window.scrollTo({ top: 200, behavior: 'smooth' }), 50);
    } catch (err) {
      console.error('trial failed', err);
      setError(err);
      setStage('error');
    }
  };

  const useSample = () => setText(SAMPLE_TEXT);
  const reset = () => { setStage('idle'); setResult(null); setError(null); };

  return (
    <div className="min-h-screen bg-ink-50">
      <div className="bg-warn-50 border-b border-warn-100">
        <div className="max-w-[1200px] mx-auto px-6 lg:px-8 h-10 flex items-center justify-between gap-4">
          <div className="flex items-center gap-2 text-[12.5px] text-warn-600">
            <I.AlertCircle size={13} />
            <span><strong className="font-semibold">免费试用模式</strong> · 仅分析前 1000 字 · 完整报告需上传论文文件</span>
          </div>
          <a onClick={() => navigate('upload')} className="text-[12.5px] text-navy-900 font-medium hover:text-brand-600 cursor-pointer hidden sm:inline-flex items-center gap-1">
            上传完整论文 <I.ArrowRight size={12} />
          </a>
        </div>
      </div>

      <div className="max-w-[1200px] mx-auto px-6 lg:px-8 py-10">
        {/* idle: 输入区 */}
        {stage === 'idle' && (
          <TrialInputCard text={text} setText={setText} onSubmit={submit} useSample={useSample} />
        )}

        {/* analyzing */}
        {stage === 'analyzing' && <TrialAnalyzing />}

        {/* error */}
        {stage === 'error' && (
          <Card className="p-8 text-center max-w-[640px] mx-auto">
            <div className="w-14 h-14 mx-auto rounded-full bg-bad-50 text-bad-600 flex items-center justify-center"><I.AlertTriangle size={26} /></div>
            <h3 className="mt-4 text-[20px] font-bold text-navy-900">试用失败</h3>
            <p className="mt-2 text-[13.5px] text-ink-500">{error?.message || '检测引擎暂时不可用，请稍后重试'}</p>
            <Button kind="dark" size="lg" onClick={reset} className="mt-6">重新试用</Button>
          </Card>
        )}

        {/* result */}
        {stage === 'result' && result && (
          <TrialResultView result={result} onRetry={reset} navigate={navigate} />
        )}
      </div>
    </div>
  );
}

function TrialInputCard({ text, setText, onSubmit, useSample }) {
  const len = text.trim().length;
  const ok = len >= 100 && len <= 2000;
  return (
    <div className="max-w-[760px] mx-auto">
      <div className="text-center mb-7">
        <Badge tone="brand"><I.Sparkles size={11} /> FREE TRIAL</Badge>
        <h1 className="mt-4 text-[32px] sm:text-[40px] font-bold text-navy-900 tracking-tight leading-tight">
          粘贴一段你写的文本 <span className="text-brand-600">免费检测</span>
        </h1>
        <p className="mt-3 text-[14px] text-ink-500 max-w-xl mx-auto leading-relaxed">
          直接粘贴 100–2000 字到下方，30 秒内拿到 AIGC 概率初判 + 风险标记。无需注册，结果即时生成。
        </p>
      </div>

      <Card className="p-6 sm:p-7">
        <div className="flex items-center justify-between mb-3">
          <label className="text-[13px] font-semibold text-navy-900">粘贴待检测文本</label>
          <button onClick={useSample} className="text-[12px] text-brand-600 hover:text-brand-700 inline-flex items-center gap-1">
            <I.Sparkles size={11} /> 使用示例文本
          </button>
        </div>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          rows={12}
          maxLength={2000}
          placeholder="粘贴 100–2000 字中文论文片段..."
          className="w-full px-4 py-3 rounded-lg ring-1 ring-ink-200 bg-white text-[14px] text-ink-700 leading-relaxed focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none"
        />
        <div className="mt-2 flex items-center justify-between text-[12px]">
          <span className={`${ok ? 'text-ok-600' : len > 0 ? 'text-warn-600' : 'text-ink-400'}`}>
            {len === 0 ? '至少 100 字才能开始检测' : ok ? `${len} 字 · 已满足` : `${len} 字 · ${len < 100 ? `还需 ${100 - len} 字` : '超出 2000 字上限'}`}
          </span>
          <span className="text-ink-400">本文本不入库，检测后立即丢弃</span>
        </div>

        <div className="mt-5 flex flex-col sm:flex-row items-stretch gap-3">
          <Button kind="primary" size="lg" onClick={onSubmit} disabled={!ok} iconRight={<I.ArrowRight size={16} />} className="flex-1">
            开始免费检测
          </Button>
          <Button kind="secondary" size="lg" onClick={() => location.hash = '#/upload'} icon={<I.Upload size={14} />} className="sm:flex-shrink-0">
            上传完整论文（¥4.9）
          </Button>
        </div>

        <div className="mt-5 pt-5 border-t border-ink-200 grid grid-cols-3 gap-3 text-center">
          <div>
            <div className="num text-[20px] font-bold text-navy-900">30s</div>
            <div className="text-[11px] text-ink-500">出结果</div>
          </div>
          <div>
            <div className="num text-[20px] font-bold text-navy-900">5</div>
            <div className="text-[11px] text-ink-500">维度模型</div>
          </div>
          <div>
            <div className="num text-[20px] font-bold text-navy-900">FREE</div>
            <div className="text-[11px] text-ink-500">完全免费</div>
          </div>
        </div>
      </Card>
    </div>
  );
}

function TrialAnalyzing() {
  return (
    <div className="max-w-[640px] mx-auto pt-16">
      <div className="text-center">
        <div className="relative inline-flex">
          <div className="w-20 h-20 rounded-full bg-brand-50 ring-1 ring-brand-100 flex items-center justify-center">
            <I.Cpu size={32} className="text-brand-600 pulse-dot" />
          </div>
          <div className="absolute inset-0 rounded-full ring-2 ring-brand-500 opacity-30 animate-ping" />
        </div>
        <h2 className="mt-6 text-[22px] font-bold text-navy-900 tracking-tight">检测引擎分析中</h2>
        <p className="mt-2 text-[13.5px] text-ink-500">正在与 8 大主流模型指纹比对...</p>
      </div>
      <div className="mt-8 space-y-2.5">
        {['加载文本预处理流水线', '计算困惑度与突发性指标', '比对 LLM 高频模板词', '生成段落级风险评估'].map((s, i) => (
          <div key={s} className="flex items-center gap-3 p-3 rounded-lg bg-white ring-1 ring-ink-200">
            <I.Spinner size={14} className="text-brand-600" />
            <span className="text-[13px] text-ink-700">{s}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TrialResultView({ result, onRetry, navigate }) {
  const meta = LEVEL_META_TRIAL[result.risk_level] || LEVEL_META_TRIAL.mid;
  const aigc = Math.round(result.aigc_probability);
  const dimsRaw = result.dimensions || {};
  const dims = {
    perplexity: Math.round(dimsRaw.perplexity || 0),
    burstiness: Math.round(dimsRaw.burstiness || 0),
    cliche:     Math.round(dimsRaw.cliche || 0),
    regularity: Math.round(dimsRaw.regularity || 0),
    voice:      Math.round(dimsRaw.voice || 0),
  };
  const lockedModels = [
    { name: 'ChatGPT (GPT-4)', match: 64 },
    { name: 'DeepSeek',        match: 58 },
    { name: 'Claude',          match: 41 },
    { name: '文心一言',         match: 29 },
    { name: '通义千问',         match: 24 },
    { name: '豆包',            match: 17 },
  ];
  const teaser = result.teaser || {};
  const hiddenCount = teaser.hidden_paragraphs || 0;

  return (
    <>
      <div className="flex flex-wrap items-start justify-between gap-4 mb-7">
        <div>
          <div className="flex items-center gap-2 text-[11.5px] tracking-wider uppercase text-ink-500 font-semibold">
            <I.FileText size={13} /> 试用结果
            <span className="text-ink-300">·</span>
            <span className="mono">前 {result.sample_word_count} 字</span>
          </div>
          <h1 className="mt-2 text-[26px] sm:text-[30px] font-bold text-navy-900 tracking-tight">
            试用版报告 · 已分析 <span className="num">{result.sample_paragraphs.length}</span> 段
          </h1>
          <p className="mt-1 text-[13.5px] text-ink-500">
            {hiddenCount > 0 ? `本检测共发现 ${result.sample_paragraphs.length + hiddenCount} 个段落，` : ''}
            上传完整论文可启用全部 5 维度模型 + 模型指纹比对 + 改写建议。
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button kind="secondary" size="md" onClick={onRetry} icon={<I.Refresh size={14} />}>重新试用</Button>
          <Button kind="dark" size="md" onClick={() => navigate('upload')} iconRight={<I.ArrowRight size={14} />}>
            ¥4.9 开始完整检测
          </Button>
        </div>
      </div>

      {/* Score visible */}
      <Card className="p-7 sm:p-9">
        <div className="grid lg:grid-cols-12 gap-8 items-center">
          <div className="lg:col-span-5 flex justify-center">
            <Gauge value={aigc} size={240} sublabel="试用估算" />
          </div>
          <div className="lg:col-span-7">
            <Badge tone={meta.tone}><I.AlertTriangle size={11} /> 试用估算 · {meta.label}</Badge>
            <h2 className="mt-3 text-[26px] font-bold tracking-tight" style={{ color: meta.tone === 'ok' ? '#059669' : meta.tone === 'warn' ? '#D97706' : '#DC2626' }}>
              {meta.label}
            </h2>
            <p className="mt-3 text-[14px] text-ink-700 leading-relaxed max-w-xl">{meta.desc}</p>
            <div className="mt-6 grid grid-cols-3 gap-3">
              <MetricChipT label="样本字数" value={result.sample_word_count} tone="ink" />
              <MetricChipT label="已分析段" value={result.sample_paragraphs.length} tone="brand" />
              {hiddenCount > 0 && <MetricChipT label="待解锁段" value={`${hiddenCount} 段`} tone="ok" />}
            </div>
          </div>
        </div>
      </Card>

      {/* Visible paragraphs */}
      <SectionTitleT n="01" title="段落级标记 · 试用部分" subtitle="以下为前 1000 字的真实段落标记结果。" extra={<RiskLegend />} />
      <Card className="p-7 sm:p-9">
        {result.sample_paragraphs.length > 0 ? (
          <ParagraphList paragraphs={result.sample_paragraphs} />
        ) : (
          <p className="text-center text-[13px] text-ink-500 py-6">本段未识别出明显段落特征</p>
        )}
      </Card>

      {/* Locked sections */}
      <div className="mt-12 relative">
        <SectionTitleT n="02" title="多维度分析 / 模型指纹 / 改写建议" subtitle="以下区块在试用版中已隐藏。" />

        <div className="relative rounded-2xl overflow-hidden ring-1 ring-ink-200 bg-white">
          <div className="select-none pointer-events-none" aria-hidden="true" style={{ filter: 'blur(10px)' }}>
            <div className="p-7 grid lg:grid-cols-12 gap-5">
              <div className="lg:col-span-6 flex justify-center">
                <Radar dims={dims} size={320} />
              </div>
              <div className="lg:col-span-6 space-y-3">
                {MOCK.DIMENSIONS.map(d => (
                  <div key={d.key} className="p-4 rounded-xl ring-1 ring-ink-200 bg-white">
                    <div className="flex items-center justify-between">
                      <div className="text-[14.5px] font-semibold text-navy-900">{d.label}</div>
                      <div className="num text-[22px] font-bold text-navy-900">{dims[d.key]}</div>
                    </div>
                    <div className="mt-2 h-1.5 bg-ink-100 rounded-full">
                      <div className="h-full rounded-full bg-brand-600" style={{ width: `${dims[d.key]}%` }} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="p-7 border-t border-ink-200">
              <ModelBars models={lockedModels} />
            </div>
            <div className="p-7 border-t border-ink-200 space-y-3">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="p-4 rounded-xl bg-ink-50">
                  <div className="h-3 bg-ink-200 rounded-full mb-2 w-3/4" />
                  <div className="h-3 bg-ink-200 rounded-full w-1/2" />
                </div>
              ))}
            </div>
          </div>

          <div className="absolute inset-0 bg-gradient-to-b from-white/30 via-white/60 to-white/95" />

          <div className="absolute inset-0 flex items-center justify-center p-6">
            <div className="max-w-[480px] w-full text-center">
              <div className="mx-auto w-14 h-14 rounded-2xl bg-navy-900 text-white flex items-center justify-center shadow-soft">
                <I.Lock size={22} />
              </div>
              <h3 className="mt-5 text-[26px] sm:text-[28px] font-bold text-navy-900 tracking-tight leading-tight" style={{ textWrap: 'balance' }}>
                {hiddenCount > 0 ? <>本检测共 <span className="text-bad-600">{hiddenCount + result.sample_paragraphs.length} 段</span><br />解锁完整报告</> : <>解锁全文 5 维度分析<br />模型指纹与改写建议</>}
              </h3>
              <p className="mt-3 text-[13.5px] text-ink-500 leading-relaxed">
                完整报告含<strong className="text-navy-900">全文段落分析</strong>、<strong className="text-navy-900">模型指纹匹配</strong>、<strong className="text-navy-900">改写建议</strong>
              </p>
              <div className="mt-6 inline-flex flex-col items-center gap-2">
                <Button kind="primary" size="lg" onClick={() => navigate('upload')} iconRight={<I.ArrowRight size={16} />}>
                  ¥4.9 上传论文 · 解锁完整报告
                </Button>
                <div className="text-[12px] text-ink-500">检测完成后 24h 自动删除 · 30 分钟超时全额退款</div>
              </div>

              <div className="mt-7 grid grid-cols-3 gap-3 text-left">
                {[
                  { icon: <I.Radar size={14} />,    label: '5 维度雷达图' },
                  { icon: <I.Layers size={14} />,   label: '8 大模型指纹' },
                  { icon: <I.FileText size={14} />, label: '全段改写建议' },
                ].map(b => (
                  <div key={b.label} className="flex items-center gap-2 p-2 rounded-lg bg-white ring-1 ring-ink-200">
                    <span className="w-7 h-7 rounded-md bg-brand-50 text-brand-600 flex items-center justify-center">{b.icon}</span>
                    <span className="text-[12px] text-ink-700">{b.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="mt-10 p-5 rounded-2xl bg-ink-100 text-[12.5px] text-ink-500 leading-relaxed">
        <strong className="text-navy-900">试用版说明：</strong>试用报告基于前 1000 字的初步统计，仅供方法演示参考。完整报告启用全部 5 维度统计模型与全文段落级标记，结果会更精确。
        <br />
        检测结果仅供作者自查改进使用，不构成最终学术鉴定。请以所在机构官方查重系统结果为准。
      </div>
    </>
  );
}

function MetricChipT({ label, value, tone = 'ink' }) {
  const tones = { ink: 'bg-ink-50', ok: 'bg-ok-50', brand: 'bg-brand-50' };
  return (
    <div className={`p-3 rounded-lg ring-1 ring-ink-200 ${tones[tone]}`}>
      <div className="text-[10.5px] uppercase tracking-wider text-ink-500 font-semibold">{label}</div>
      <div className="mt-1 num text-[20px] font-bold text-navy-900">{value}</div>
    </div>
  );
}

function SectionTitleT({ n, title, subtitle, extra }) {
  return (
    <div className="mt-12 mb-4 flex items-end justify-between gap-4 flex-wrap">
      <div>
        <div className="text-[11px] tracking-[0.18em] uppercase text-brand-600 font-semibold mono">{n} · SECTION</div>
        <h2 className="mt-1 text-[22px] sm:text-[24px] font-bold text-navy-900 tracking-tight">{title}</h2>
        {subtitle && <p className="mt-1 text-[13.5px] text-ink-500 max-w-2xl">{subtitle}</p>}
      </div>
      {extra}
    </div>
  );
}

window.TrialReportPage = TrialReportPage;
