// ===== page-lookup.jsx =====
// 用户找回订单：输入订单号 + 访问令牌 → 验证 → 跳转报告页
// 用于用户换设备/清缓存后还能查看已购报告

const { useState: useSL, useEffect: useEL } = React;

function LookupPage({ navigate }) {
  const [orderId, setOrderId] = useSL('');
  const [token, setToken]     = useSL('');
  const [submitting, setSubmitting] = useSL(false);
  const [error, setError]     = useSL(null);

  const submit = async (e) => {
    e.preventDefault();
    if (!orderId.trim() || !token.trim() || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      // 通过获取报告来验证 token 合法
      const id = orderId.trim();
      const tk = token.trim();
      window.API.saveToken(id, tk);
      await window.API.getReport(id, tk);
      navigate('report', { id, token: tk });
    } catch (err) {
      console.error('lookup failed', err);
      const id = orderId.trim();
      const tk = token.trim();
      if (err?.code === 'report_not_ready') {
        // 报告未就绪：token 是合法的，保留并跳订单页继续等
        navigate('order', { id, token: tk });
      } else {
        window.API.clearToken(id);
        setError(err?.message || '验证失败：订单号或访问令牌不正确');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-ink-50 pt-12 pb-24">
      <div className="max-w-[640px] mx-auto px-6 lg:px-8">
        <div className="flex items-center gap-2 text-[12.5px] text-ink-500 mb-6">
          <a onClick={() => navigate('home')} className="hover:text-navy-900 cursor-pointer">首页</a>
          <I.Chevron size={12} />
          <span className="text-navy-900">找回订单</span>
        </div>

        <h1 className="text-[32px] sm:text-[36px] font-bold text-navy-900 tracking-tight">找回我的订单</h1>
        <p className="mt-2 text-[14.5px] text-ink-500">
          如果你换了设备或清理了浏览器缓存，输入订单号 + 访问令牌即可重新查看报告。
        </p>

        <Card className="mt-8 p-6 sm:p-8">
          <form onSubmit={submit} className="space-y-5">
            <div>
              <label className="text-[13px] font-semibold text-navy-900">订单号</label>
              <input
                type="text"
                value={orderId}
                onChange={(e) => setOrderId(e.target.value)}
                placeholder="例如：20260524-1085"
                className="mt-2 w-full h-11 px-3 rounded-lg ring-1 ring-ink-200 bg-white mono text-[14px] focus:outline-none focus:ring-2 focus:ring-brand-500"
                required
              />
              <p className="mt-1.5 text-[11.5px] text-ink-500">格式：YYYYMMDD-NNNN</p>
            </div>

            <div>
              <label className="text-[13px] font-semibold text-navy-900">访问令牌</label>
              <textarea
                value={token}
                onChange={(e) => setToken(e.target.value)}
                placeholder="粘贴你的访问令牌（一长串字符）"
                rows={3}
                className="mt-2 w-full px-3 py-2 rounded-lg ring-1 ring-ink-200 bg-white mono text-[13px] focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none break-all"
                required
              />
              <p className="mt-1.5 text-[11.5px] text-ink-500">
                上传时给出的 access_token，或保存的"完整访问链接"中 token 参数
              </p>
            </div>

            {error && (
              <div className="text-[12.5px] text-bad-600 bg-bad-50 ring-1 ring-bad-100 rounded-lg p-3">
                <I.AlertTriangle size={13} className="inline -mt-0.5 mr-1" />
                {error}
              </div>
            )}

            <Button kind="dark" size="lg" type="submit" disabled={submitting} className="w-full"
                    icon={submitting ? <I.Spinner size={14} /> : null}
                    iconRight={!submitting ? <I.ArrowRight size={16} /> : null}>
              {submitting ? '验证中 ...' : '查看报告'}
            </Button>
          </form>
        </Card>

        <div className="mt-6 p-5 rounded-xl bg-white ring-1 ring-ink-200">
          <div className="flex items-center gap-2 text-[13px] font-semibold text-navy-900">
            <I.Info size={14} className="text-brand-600" /> 找不到订单号或令牌？
          </div>
          <ul className="mt-3 space-y-2 text-[12.5px] text-ink-500 leading-relaxed">
            <li>· 上传论文后浏览器自动保存了访问凭证，<a className="text-brand-600 cursor-pointer hover:underline" onClick={() => navigate('home')}>回到首页</a>看是否还在同设备</li>
            <li>· 检查你的支付宝交易记录，金额尾数可对照订单</li>
            <li>· 联系客服：support@mojian.ai，提供付款时间 + 金额可帮你找回</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

window.LookupPage = LookupPage;
