// PasswordGate.jsx —— 精装纪念册翻开动画
// 流程：封面静置（烫金 2020—2026 17 班）
//  -> 点封面 -> 封面沿中线 3D 翻开 -> 露出扉页（写着请输入暗号）
//  -> 输入正确 -> 再翻一页 -> 进入同学录

const PasswordGate = ({ onUnlock, classInfo }) => {
  const [stage, setStage] = React.useState("cover"); // cover | inside | opening
  const [pwd, setPwd] = React.useState("");
  const [err, setErr] = React.useState(false);
  const [shake, setShake] = React.useState(false);

  const openCover = () => setStage("inside");

  const submit = (e) => {
    e?.preventDefault();
    if (pwd.trim().toLowerCase() === classInfo.password.toLowerCase()) {
      setStage("opening");
      setTimeout(onUnlock, 1400);
    } else {
      setErr(true);
      setShake(true);
      setTimeout(() => setShake(false), 500);
    }
  };

  return (
    <div style={gateStyles.stage}>
      <div style={gateStyles.bg} />
      <FloatingBits />

      {/* 顶部提示 */}
      <div style={{
        position: "absolute", top: "6vh", left: 0, right: 0,
        textAlign: "center", padding: "0 24px", zIndex: 3,
        opacity: stage === "opening" ? 0 : 1,
        transition: "opacity .4s",
      }}>
        <div style={{ fontSize: 12, color: "var(--c-sub)", letterSpacing: "0.3em" }}>
          CLASS OF 2026
        </div>
      </div>

      {/* 书本舞台 —— 3D 视角 */}
      <div style={{
        position: "absolute",
        top: "50%", left: "50%",
        transform: "translate(-50%, -50%)",
        width: "min(320px, 78vw)",
        aspectRatio: "3 / 4",
        perspective: "1600px",
        zIndex: 2,
      }}>
        <Book
          stage={stage}
          classInfo={classInfo}
          pwd={pwd} setPwd={setPwd}
          submit={submit} err={err} shake={shake}
          openCover={openCover}
        />
      </div>

      {/* 底部提示 */}
      <div style={{
        position: "absolute", bottom: "7vh", left: 0, right: 0,
        textAlign: "center",
        color: "var(--c-sub)", fontSize: 13,
        opacity: stage === "cover" ? 1 : 0,
        transition: "opacity .3s",
        zIndex: 3,
      }}>
        轻触封面 · 翻开这本册子
      </div>

      <style>{`
        @keyframes shake {
          0%,100% { transform: translateX(0); }
          25% { transform: translateX(-8px); }
          75% { transform: translateX(8px); }
        }
        @keyframes expand {
          0%   { transform: scale(0.1); border-radius: 50%; opacity: 0.8; }
          100% { transform: scale(25);  border-radius: 0;   opacity: 1; }
        }
      `}</style>
    </div>
  );
};

const Book = ({ stage, classInfo, pwd, setPwd, submit, err, shake, openCover }) => {
  // 封面的 rotateY：cover=0, inside=-170, opening=-170 后再翻一页
  const coverRotate = stage === "cover" ? 0 : -170;

  return (
    <div style={{
      position: "relative",
      width: "100%", height: "100%",
      transformStyle: "preserve-3d",
    }}>
      {/* 书背（底层，始终可见，渲染扉页/书页） */}
      <InsidePages
        visible={stage !== "cover"}
        classInfo={classInfo}
        pwd={pwd} setPwd={setPwd}
        submit={submit} err={err} shake={shake}
        isOpening={stage === "opening"}
      />

      {/* 封面 —— 绕左边缘翻开 */}
      <div
        onClick={stage === "cover" ? openCover : undefined}
        style={{
          position: "absolute", inset: 0,
          transformOrigin: "left center",
          transform: `rotateY(${coverRotate}deg)`,
          transition: "transform 1.1s cubic-bezier(.7,.05,.35,1)",
          transformStyle: "preserve-3d",
          cursor: stage === "cover" ? "pointer" : "default",
          zIndex: 3,
        }}
      >
        <CoverFront classInfo={classInfo} />
        <CoverBack />
      </div>

      {/* 解锁时扩散遮罩 */}
      {stage === "opening" && (
        <div style={{
          position: "absolute", left: "50%", top: "50%",
          width: 40, height: 40,
          background: "var(--c-paper)",
          borderRadius: 200,
          transform: "translate(-50%, -50%)",
          animation: "expand 1.4s cubic-bezier(.7,0,.3,1) 0.3s forwards",
          zIndex: 10,
        }} />
      )}
    </div>
  );
};

/* ---- 封面（青葱绿野） ---- */
const CoverFront = ({ classInfo }) => (
  <div style={{
    position: "absolute", inset: 0,
    background: "linear-gradient(165deg, #F0F7E4 0%, #C3E6A8 48%, #52B788 100%)",
    borderRadius: "4px 10px 10px 4px",
    boxShadow: "var(--shadow-card), inset -2px 0 0 rgba(255,255,255,0.45), inset 2px 0 0 rgba(30,70,40,0.18)",
    backfaceVisibility: "hidden",
    overflow: "hidden",
    animation: "bookFloat 4s ease-in-out infinite",
    color: "#1B4332",
  }}>
    {/* 柔和光晕 */}
    <div style={{
      position: "absolute", top: -70, right: -60,
      width: 220, height: 220, borderRadius: "50%",
      background: "radial-gradient(circle, rgba(232,245,212,0.95), transparent 65%)",
    }} />
    <div style={{
      position: "absolute", bottom: -70, left: -60,
      width: 200, height: 200, borderRadius: "50%",
      background: "radial-gradient(circle, rgba(82,183,136,0.35), transparent 70%)",
    }} />

    {/* 远山剪影 */}
    <svg viewBox="0 0 300 100" preserveAspectRatio="none" style={{
      position: "absolute", bottom: 68, left: 0, right: 0, width: "100%", height: 82, opacity: 0.55,
    }}>
      <path d="M 0 100 L 0 55 Q 40 30, 80 50 T 150 45 T 220 55 T 300 40 L 300 100 Z" fill="#74C69D" />
      <path d="M 0 100 L 0 72 Q 50 55, 100 66 T 180 62 T 260 72 T 300 62 L 300 100 Z" fill="#40916C" opacity="0.75" />
    </svg>

    {/* 叶子涂鸦 */}
    <div style={{ position: "absolute", top: 54, left: 32, fontSize: 20, color: "#2D6A4F", transform: "rotate(-15deg)" }}>❦</div>
    <div style={{ position: "absolute", top: 104, right: 40, fontSize: 14, color: "#40916C" }}>✿</div>
    <div style={{ position: "absolute", bottom: 140, right: 30, fontSize: 13, color: "#FFB703" }}>✦</div>
    <div style={{ position: "absolute", top: 224, left: 24, fontSize: 11, color: "#B7E4C7" }}>❧</div>

    {/* 太阳光斑 */}
    <div style={{
      position: "absolute", top: 46, right: 34,
      width: 44, height: 44, borderRadius: "50%",
      background: "radial-gradient(circle at 35% 35%, #FFF8D6, #FFE08A)",
      boxShadow: "0 0 26px rgba(255,224,138,0.7)",
    }} />

    {/* 顶部标签 */}
    <div style={{
      position: "absolute", top: 24, left: -12,
      background: "#2D6A4F",
      color: "#F0F7E4",
      padding: "4px 12px 4px 20px",
      fontSize: 10,
      fontWeight: 700,
      letterSpacing: "0.22em",
      transform: "rotate(-5deg)",
      boxShadow: "0 2px 6px rgba(0,0,0,0.15)",
    }}>
      CLASS OF 2026
    </div>

    {/* 主标题 */}
    <div style={{ position: "absolute", top: 138, left: 26, right: 26, zIndex: 3 }}>
      <div style={{
        fontSize: 11, color: "#2D6A4F",
        letterSpacing: "0.3em", marginBottom: 8, opacity: 0.85,
      }}>
        EVERGREEN YEARBOOK
      </div>
      <div style={{
        fontFamily: "var(--font-display)",
        fontSize: 68, lineHeight: 0.92,
        color: "#1B4332",
        fontWeight: 400,
        textShadow: "3px 3px 0 #F0F7E4, 5px 5px 0 rgba(27,67,50,0.15)",
      }}>
        同学录
      </div>
      <div style={{
        display: "inline-block",
        marginTop: 12,
        padding: "4px 12px",
        background: "#1B4332",
        color: "#F0F7E4",
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: "0.1em",
        transform: "rotate(-1.5deg)",
      }}>
        17 班 · 我们
      </div>
    </div>

    {/* 底部信息 */}
    <div style={{
      position: "absolute", bottom: 24, left: 24, right: 24,
      display: "flex", alignItems: "flex-end", justifyContent: "space-between",
      zIndex: 3,
    }}>
      <div>
        <div style={{ fontSize: 12, color: "#1B4332", fontWeight: 700, marginBottom: 2 }}>
          {classInfo.className}
        </div>
        <div style={{ fontSize: 10, color: "#2D6A4F" }}>
          {classInfo.school}
        </div>
      </div>
      <div style={{
        fontFamily: "serif",
        fontSize: 22,
        color: "#1B4332",
        letterSpacing: "0.05em",
        fontWeight: 700,
      }}>
        '20—'26
      </div>
    </div>

    {/* 书脊阴影 */}
    <div style={{
      position: "absolute", left: 0, top: 0, bottom: 0, width: 10,
      background: "linear-gradient(90deg, rgba(27,67,50,0.22), transparent)",
      pointerEvents: "none",
    }} />

    {/* 胶带 */}
    <div style={{
      position: "absolute", top: 6, left: "44%",
      width: 54, height: 16,
      background: "rgba(255,255,255,0.5)",
      border: "1px dashed rgba(27,67,50,0.25)",
      transform: "rotate(-3deg)",
    }} />

    <style>{`
      @keyframes bookFloat {
        0%, 100% { transform: translateY(0); }
        50%      { transform: translateY(-6px); }
      }
    `}</style>
  </div>
);

/* ---- 封面内侧 ---- */
const CoverBack = () => (
  <div style={{
    position: "absolute", inset: 0,
    background: "linear-gradient(135deg, #F0F7E4 0%, #D8F3DC 100%)",
    borderRadius: "10px 4px 4px 10px",
    transform: "rotateY(180deg)",
    backfaceVisibility: "hidden",
    boxShadow: "inset 2px 0 0 rgba(27,67,50,0.08)",
    padding: 20,
  }}>
    <div style={{
      position: "absolute", inset: 28,
      border: "2px dashed rgba(45,106,79,0.35)",
      borderRadius: 4,
      display: "flex",
      alignItems: "center", justifyContent: "center",
      color: "#1B4332",
      fontFamily: "var(--font-display)",
      fontSize: 17,
      textAlign: "center",
      lineHeight: 1.7,
    }}>
      愿你的故事
      <br/>
      四季常青
      <br/>
      ——17 班
    </div>
  </div>
);

/* ---- 扉页 —— 密码输入 ---- */
const InsidePages = ({ visible, classInfo, pwd, setPwd, submit, err, shake, isOpening }) => (
  <div style={{
    position: "absolute", inset: 0,
    background: "linear-gradient(180deg, #FFFEF5 0%, #FBF4E3 100%)",
    borderRadius: 4,
    boxShadow: "inset 8px 0 12px -6px rgba(0,0,0,0.15), 0 20px 40px -10px rgba(29,53,87,0.25)",
    opacity: visible ? 1 : 0,
    transition: "opacity .3s .4s",
    overflow: "hidden",
  }}>
    {/* 书脊沟 */}
    <div style={{
      position: "absolute", left: 0, top: 0, bottom: 0, width: 14,
      background: "linear-gradient(90deg, rgba(0,0,0,0.15), transparent)",
      pointerEvents: "none",
    }} />

    {/* 纸面纹理 */}
    <div style={{
      position: "absolute", inset: 0,
      backgroundImage:
        "radial-gradient(circle at 20% 30%, rgba(139,111,71,0.05), transparent 40%), " +
        "radial-gradient(circle at 80% 70%, rgba(230,57,70,0.04), transparent 40%)",
      pointerEvents: "none",
    }} />

    <form
      onSubmit={submit}
      style={{
        position: "absolute", inset: 0,
        padding: "36px 30px 30px 38px",
        display: "flex", flexDirection: "column",
        ...(shake ? { animation: "shake .5s" } : {}),
        ...(isOpening ? { opacity: 0, transition: "opacity .3s" } : {}),
      }}
    >
      {/* 纪念册扉页语 */}
      <div style={{ fontSize: 11, color: "var(--c-sub)", letterSpacing: "0.25em", textTransform: "uppercase" }}>
        Prologue
      </div>
      <div style={{ height: 1, background: "var(--c-line)", margin: "10px 0 18px" }} />

      <div style={{
        fontFamily: "var(--font-display)",
        fontSize: 22,
        color: "var(--c-deep)",
        lineHeight: 1.4,
      }}>
        翻开这本册子前，
        <br/>
        请先说出我们的
        <br/>
        <span style={{ color: "var(--c-primary)" }}>专属暗号</span>
      </div>

      <div style={{ flex: 1 }} />

      <div style={{ position: "relative" }}>
        <input
          type="text"
          value={pwd}
          onChange={(e) => setPwd(e.target.value)}
          placeholder="请输入暗号..."
          autoFocus
          style={{
            width: "100%",
            border: "none",
            borderBottom: `2px solid ${err ? "var(--c-primary)" : "var(--c-deep)"}`,
            background: "transparent",
            padding: "10px 0",
            fontSize: 20,
            color: "var(--c-deep)",
            outline: "none",
            letterSpacing: "0.08em",
          }}
        />
        {err && (
          <div style={{ fontSize: 12, color: "var(--c-primary)", marginTop: 6 }}>
            暗号不对，再想想？
          </div>
        )}
      </div>

      <button type="submit" style={{
        marginTop: 22,
        width: "100%",
        background: "var(--c-primary)",
        color: "#fff",
        padding: "13px",
        borderRadius: 999,
        fontSize: 15,
        fontWeight: 600,
        boxShadow: "0 6px 16px -4px rgba(230,57,70,0.45)",
      }}>
        翻开第一页 →
      </button>

      <div style={{ textAlign: "center", fontSize: 10, color: "var(--c-sub)", marginTop: 12 }}>
        暗号由班级群统一发送
      </div>
    </form>

    {/* 右下角页码 */}
    <div style={{
      position: "absolute", bottom: 14, right: 18,
      fontFamily: "serif", fontSize: 12, color: "var(--c-sub)",
    }}>— 1 —</div>
  </div>
);

const FloatingBits = () => {
  const bits = [
    { t: "★", x: "8%",  y: "18%", s: 18, d: 0   },
    { t: "♥", x: "88%", y: "22%", s: 14, d: 0.8 },
    { t: "✦", x: "12%", y: "72%", s: 20, d: 1.4 },
    { t: "✿", x: "86%", y: "78%", s: 22, d: 0.4 },
    { t: "★", x: "20%", y: "45%", s: 12, d: 2.0 },
    { t: "♥", x: "80%", y: "52%", s: 10, d: 1.1 },
  ];
  return (
    <>
      {bits.map((b, i) => (
        <div key={i} className="star" style={{
          left: b.x, top: b.y,
          fontSize: b.s,
          color: i % 2 ? "var(--c-primary)" : "var(--c-accent)",
          animationDelay: `${b.d}s`,
        }}>{b.t}</div>
      ))}
    </>
  );
};

const gateStyles = {
  stage: {
    position: "relative",
    width: "100%",
    minHeight: "100vh",
    minHeight: "100svh",
    background: "linear-gradient(170deg, var(--c-bg) 0%, var(--c-bg-warm) 100%)",
    overflow: "hidden",
  },
  bg: {
    position: "absolute", inset: 0,
    backgroundImage:
      "radial-gradient(circle at 20% 20%, rgba(168,218,220,0.2), transparent 40%), " +
      "radial-gradient(circle at 80% 70%, rgba(230,57,70,0.1), transparent 40%)",
    pointerEvents: "none",
  },
};

Object.assign(window, { PasswordGate });
