/* 接收页 ReceiveScreen —— 万鳞甲式正反馈:全网鳞片汇向龙身,缝上龙颈。
   参《哪吒》万鳞甲:族人各献一片鳞。clay 底 + 真实龙 + 真实旧布鳞片 + 火花迸发。
   phase: gather(群鳞汇聚) → burst(火花冲击 + 龙身鳞甲亮) → settle(文案/计数)
   导出 window.WL.ReceiveScreen */
(function () {
  function ReceiveScreen({ draft, result, onViewAll, onAgain, onScaleClick }) {
    const NS = window.U4e07U9cdeWU00e0nlU00ednDesignSystem_56bec1 || {};
    const { Button, Toast } = NS;
    const { DragonCanvas } = window.WL;
    const D = window.WL_DATA;
    const FABS = D.cloths.map((c) => c.img);
    const clothImg = (k) => (D.cloths.find((c) => c.key === k) || {}).img;

    // submit 结果：online=已落库（带服务端权威编号）；offline=离线入队/未确认
    const online = !!(result && result.state === "ok" && result.scale);
    const offline = !!(result && result.state && result.state !== "ok");

    const [phase, setPhase] = React.useState("gather");
    // 立即进入即开始庆祝（乐观基数 mountTotal+1，mount 时冻结、免疫后台轮询）；
    // submit 在后台 resolve 后，online 变真 → finalN 校正为服务端权威编号（通常在开场动画阶段就完成，看不出跳变）。
    const mountTotal = React.useMemo(() => D.total, []);
    const finalN = online ? result.scale.id : (mountTotal + 1);
    const baseScales = React.useMemo(() => D.scales.slice(), []);   // 快照龙身鳞片集，避免中途被替换重排
    const [count, setCount] = React.useState(Math.max(0, mountTotal + 1 - 40));

    // 汇聚锚点(覆盖在 DragonCanvas 龙颈一带)
    const ANCHOR = { left: "30%", top: 150 };

    // 群鳞:四面八方持续飞来的 24 片(真实旧布)
    const swarm = React.useMemo(() => {
      const N = 24, arr = [];
      for (let i = 0; i < N; i++) {
        const a = (i / N) * Math.PI * 2 + 0.6;
        const dist = 250 + ((i * 37) % 200);
        arr.push({
          i,
          sx: Math.round(Math.cos(a) * dist),
          sy: Math.round(Math.sin(a) * dist * 0.8),
          r: ((i * 47) % 70) - 35,
          delay: (i * 44) % 980,
          img: FABS[i % FABS.length],
          w: 26 + ((i * 3) % 14),
        });
      }
      return arr;
    }, []);

    React.useEffect(() => {
      const t1 = setTimeout(() => setPhase("burst"), 1480);
      const t2 = setTimeout(() => setPhase("settle"), 2060);
      return () => { clearTimeout(t1); clearTimeout(t2); };
    }, []);

    React.useEffect(() => {
      if (phase === "gather") return;
      let raf, start; const from = Math.max(0, finalN - 40), dur = 1100;
      const tick = (ts) => {
        if (!start) start = ts;
        const p = Math.min(1, (ts - start) / dur), e = 1 - Math.pow(1 - p, 3);
        setCount(Math.round(from + (finalN - from) * e));
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => cancelAnimationFrame(raf);
    }, [phase, finalN]);

    const newScale = online
      ? result.scale
      : { id: finalN, cloth: draft.cloth, text: draft.text, place: draft.place || "某处", author: draft.author || "佚名", t: "刚刚" };
    const scales = [newScale, ...baseScales];
    const ceremony = phase !== "gather";
    const heroImg = clothImg(draft.cloth) || FABS[0];

    return (
      <div style={{ position: "relative", minHeight: "100%", display: "flex", flexDirection: "column", background: "var(--surface-page)", overflow: "hidden" }}>

        {/* 龙身(收到鳞片时愉快地转一个圈) */}
        <div className={phase !== "gather" ? "wl-spin" : ""} style={{ padding: "26px 20px 0", position: "relative", zIndex: 1, transformOrigin: "center 60%" }}>
          <DragonCanvas scales={scales} total={150} height={360} ceremony={ceremony} onScaleClick={onScaleClick} />
        </div>

        {/* 汇聚特效层(锚定龙颈) */}
        <div style={{ position: "absolute", left: ANCHOR.left, top: ANCHOR.top, zIndex: 10, pointerEvents: "none" }}>
          {/* 龙颈暖光晕(settle 后保留) */}
          <span className={"wl-halo" + (phase === "settle" ? " wl-halo-on" : "")} />

          {/* 群鳞:四面八方飞来,落点被吸入龙身,各冒 +1 */}
          {phase !== "settle" && swarm.map((s) => (
            <React.Fragment key={s.i}>
              <span className="wl-swarm" style={{
                position: "absolute", width: s.w * 1.25, height: s.w,
                background: `url("${s.img}") center/cover`,
                clipPath: "url(#wlBodyFan)",
                filter: "drop-shadow(0 0 7px color-mix(in srgb,var(--brass-500) 65%,transparent))",
                ["--sx"]: s.sx + "px", ["--sy"]: s.sy + "px", ["--r"]: s.r + "deg",
                animationDelay: s.delay + "ms",
              }} />
              <span className="wl-plus" style={{ animationDelay: (s.delay + 720) + "ms" }}>+1</span>
            </React.Fragment>
          ))}

          {/* 你的鳞片:最大、最后落、引爆火花 */}
          {phase !== "settle" && (
            <span className="wl-hero" style={{
              position: "absolute", width: 108, height: 86, left: -54, top: -43,
              background: `url("${heroImg}") center/cover`,
              clipPath: "url(#wlBodyFan)",
              filter: "drop-shadow(0 0 12px color-mix(in srgb,var(--brass-500) 80%,transparent))",
              animationDelay: "360ms",
            }} />
          )}
        </div>

        {/* 文案 */}
        <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", padding: "16px 24px 52px", gap: 16 }}>
          <div style={{ opacity: phase === "settle" ? 1 : 0, transform: phase === "settle" ? "none" : "translateY(12px)", transition: "opacity .55s var(--ease-out), transform .55s var(--ease-out)", display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
            <span style={{ font: "var(--type-kicker)", textTransform: "uppercase", letterSpacing: "var(--tracking-widest)", color: "var(--text-accent)" }}>{offline ? "已记下 · 待联网缝上" : "万鳞甲 · 又添一片"}</span>
            <h1 style={{ font: "var(--type-display)", color: "var(--text-strong)", letterSpacing: "var(--tracking-wide)", margin: 0 }}>
              {offline
                ? "你的鳞片，已经记下"
                : <React.Fragment>你的鳞片,已是第 <span style={{ color: "var(--accent)", fontFamily: "var(--font-mono)" }}>{count.toLocaleString("zh-CN")}</span> 片</React.Fragment>}
            </h1>
            <p style={{ font: "var(--type-body)", color: "var(--text-muted)", maxWidth: 480, margin: 0 }}>
              {offline
                ? "网络不太稳，这句话已先存在你的设备上，等连上网会自动缝上龙身——不会丢。"
                : "全网的人,一人一片旧布,缝成同一条龙。它已缝在龙颈上——每个路过的人,都能点开它,读到你写的这句话。"}
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 6 }}>
              <Button variant="primary" size="lg" onClick={onViewAll}>看看整条龙</Button>
              <Button variant="ghost" size="lg" onClick={onAgain}>再缝一片</Button>
            </div>
          </div>
        </div>

        {phase === "settle" && (
          <div style={{ position: "absolute", top: 20, right: 20, zIndex: 12, animation: "wlToastIn .5s var(--ease-thread) both" }}>
            <Toast tone="success" title={offline ? "已记下，待联网缝上" : "鳞片已系上龙身"} message={offline ? "网络恢复后会自动同步到龙身。" : "它在龙颈第一段,刚刚加入万鳞甲。"} />
          </div>
        )}

        <style>{`
          @media (prefers-reduced-motion: no-preference){
            .wl-swarm{left:0;top:0;transform-origin:center;opacity:0;animation:wlConverge 1.25s var(--ease-out) both}
            @keyframes wlConverge{
              0%{transform:translate(var(--sx),var(--sy)) rotate(var(--r)) scale(.8);opacity:0}
              12%{opacity:1}
              82%{transform:translate(0,0) rotate(0) scale(1.05);opacity:1}
              100%{transform:translate(0,0) rotate(0) scale(.2);opacity:0}
            }
            .wl-plus{position:absolute;left:0;top:0;font-family:var(--font-mono);font-size:13px;font-weight:700;color:var(--brass-600);text-shadow:0 1px 4px rgba(255,253,248,.8);opacity:0;animation:wlPlus .9s var(--ease-out) both}
            @keyframes wlPlus{0%{opacity:0;transform:translate(-6px,6px) scale(.6)}30%{opacity:1}100%{opacity:0;transform:translate(-4px,-46px) scale(1.05)}}
            .wl-hero{animation:wlHero 1.16s var(--ease-thread) both}
            @keyframes wlHero{
              0%{transform:translate(34vw,-30vh) rotate(28deg) scale(.5);opacity:0}
              18%{opacity:1}
              70%{transform:translate(0,0) rotate(0) scale(1.06);opacity:1}
              100%{transform:translate(0,0) rotate(0) scale(.32);opacity:0}
            }
            .wl-spin{animation:wlSpin 1.05s var(--ease-thread) both}
            @keyframes wlSpin{
              0%{transform:translateY(0) rotate(0) scale(1)}
              16%{transform:translateY(-14px) rotate(0) scale(.95)}
              58%{transform:translateY(-9px) rotate(360deg) scale(.88)}
              78%{transform:translateY(3px) rotate(360deg) scale(1.03)}
              100%{transform:translateY(0) rotate(360deg) scale(1)}
            }
            .wl-halo-on{animation:wlHaloPulse 2.6s ease-in-out infinite}
            @keyframes wlHaloPulse{0%,100%{opacity:.5;transform:scale(.92)}50%{opacity:.82;transform:scale(1.08)}}
          }
          .wl-halo{position:absolute;left:0;top:0;width:300px;height:300px;margin:-150px 0 0 -150px;border-radius:50%;background:radial-gradient(circle,rgba(201,164,74,.42),rgba(201,164,74,.12) 44%,transparent 70%);opacity:0;transition:opacity .6s var(--ease-out);pointer-events:none}
          .wl-halo-on{opacity:.8}
          @keyframes wlToastIn{from{opacity:0;transform:translateX(16px)}to{opacity:1;transform:none}}
        `}</style>
      </div>
    );
  }
  window.WL = window.WL || {};
  window.WL.ReceiveScreen = ReceiveScreen;
})();
