// HomePage.jsx —— 首页：顶部横幅 + 三块入口 + 同学墙
const HomePage = ({ classInfo, students, onOpenStudent, onOpenAlbums, layout }) => {
  return (
    <div style={{ paddingBottom: 80 }}>
      <HomeHero classInfo={classInfo} />

      <div style={{ padding: "0 20px", marginTop: -30, position: "relative", zIndex: 2 }}>
        <AlbumEntryCard onClick={onOpenAlbums} />
      </div>

      <div style={{ padding: "28px 20px 8px" }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <div>
            <div className="h1" style={{ fontSize: 24, color: "var(--c-deep)" }}>我们 40 位</div>
            <div className="handwrite" style={{ fontSize: 13, color: "var(--c-sub)", marginTop: 2 }}>
              点开每一位同学，看看家长写给 ta 的话
            </div>
          </div>
          <LayoutSwitcher />
        </div>
      </div>

      {layout === "grid"     && <StudentGrid     students={students} onOpen={onOpenStudent} />}
      {layout === "masonry"  && <StudentMasonry  students={students} onOpen={onOpenStudent} />}
      {layout === "flip"     && <StudentFlipbook students={students} onOpen={onOpenStudent} />}
    </div>
  );
};

const HomeHero = ({ classInfo }) => (
  <div style={{
    position: "relative",
    padding: "32px 24px 60px",
    background: "linear-gradient(165deg, var(--c-accent) 0%, var(--c-bg-warm) 100%)",
    overflow: "hidden",
  }}>
    {/* 装饰圆 */}
    <div style={{ position: "absolute", top: -50, right: -40, width: 160, height: 160, borderRadius: "50%", background: "rgba(230,57,70,0.15)" }} />
    <div style={{ position: "absolute", top: 40, right: 80, width: 24, height: 24, borderRadius: "50%", background: "var(--c-primary)" }} />
    <div style={{ position: "absolute", bottom: 60, left: -20, width: 100, height: 100, borderRadius: "50%", background: "rgba(29,53,87,0.08)" }} />

    <div style={{ position: "relative", zIndex: 1 }}>
      <div className="handwrite" style={{ fontSize: 14, color: "var(--c-deep)", opacity: 0.75 }}>
        {classInfo.school}
      </div>
      <div className="h1" style={{ fontSize: 36, color: "var(--c-deep)", lineHeight: 1.15, marginTop: 4 }}>
        {classInfo.className}
      </div>
      <div className="h1" style={{ fontSize: 20, color: "var(--c-primary)", marginTop: 8 }}>
        毕业同学录 · 2020 — 2026
      </div>
      <div className="handwrite" style={{ fontSize: 14, color: "var(--c-deep)", marginTop: 14, lineHeight: 1.6, maxWidth: 280 }}>
        六年的时光，四十个伙伴。
        <br/>
        愿这本册子，陪你长大很久很久。
      </div>
    </div>
  </div>
);

const AlbumEntryCard = ({ onClick }) => (
  <button
    onClick={onClick}
    style={{
      width: "100%",
      background: "var(--c-paper)",
      borderRadius: "var(--r-lg)",
      padding: 16,
      display: "flex",
      alignItems: "center",
      gap: 14,
      textAlign: "left",
      boxShadow: "var(--shadow-card)",
      position: "relative",
      overflow: "hidden",
    }}
  >
    {/* 迷你照片堆 */}
    <div style={{ position: "relative", width: 80, height: 80, flexShrink: 0 }}>
      {["#FFB7B2", "#B5EAD7", "#C7CEEA"].map((c, i) => (
        <div key={i} style={{
          position: "absolute",
          width: 56, height: 56, borderRadius: 8,
          background: `linear-gradient(135deg, ${c}, ${c}dd)`,
          border: "3px solid white",
          boxShadow: "0 4px 10px rgba(29,53,87,0.15)",
          left: i * 10, top: i * 8,
          transform: `rotate(${[-8, 4, -3][i]}deg)`,
        }} />
      ))}
    </div>
    <div style={{ flex: 1 }}>
      <div className="h1" style={{ fontSize: 18, color: "var(--c-deep)" }}>我们的相册</div>
      <div className="handwrite" style={{ fontSize: 13, color: "var(--c-sub)", marginTop: 4 }}>
        合影 · 春游 · 运动会 · 联欢会...
      </div>
    </div>
    <div style={{
      background: "var(--c-primary)", color: "white",
      width: 36, height: 36, borderRadius: "50%",
      display: "flex", alignItems: "center", justifyContent: "center",
      flexShrink: 0, fontSize: 18,
    }}>→</div>
  </button>
);

const LayoutSwitcher = () => {
  const layouts = [
    { id: "grid",    label: "网格",   icon: "▦" },
    { id: "masonry", label: "瀑布流", icon: "▥" },
    { id: "flip",    label: "翻页",   icon: "❖" },
  ];
  // 通过 window._app 访问 app state（简单做法）
  const current = window._app?.layout || "grid";
  return (
    <div style={{ display: "flex", gap: 4, background: "var(--c-paper)", padding: 4, borderRadius: 999, border: "1px solid var(--c-line)" }}>
      {layouts.map(l => (
        <button
          key={l.id}
          onClick={() => window._app?.setLayout(l.id)}
          style={{
            padding: "6px 10px",
            fontSize: 12,
            borderRadius: 999,
            background: current === l.id ? "var(--c-primary)" : "transparent",
            color: current === l.id ? "white" : "var(--c-sub)",
            fontWeight: current === l.id ? 600 : 400,
          }}
          title={l.label}
        >{l.icon}</button>
      ))}
    </div>
  );
};

/* ---- 三种布局 ---- */
const StudentGrid = ({ students, onOpen }) => (
  <div style={{
    display: "grid",
    gridTemplateColumns: "repeat(3, 1fr)",
    gap: 12,
    padding: "8px 20px 40px",
  }}>
    {students.map((s, i) => (
      <StudentCard key={s.id} student={s} onClick={() => onOpen(s.id)} index={i} />
    ))}
  </div>
);

const StudentCard = ({ student, onClick, index }) => (
  <button
    onClick={onClick}
    className="pop-in"
    style={{
      animationDelay: `${Math.min(index * 0.02, 0.5)}s`,
      padding: 0,
      background: "transparent",
      textAlign: "center",
    }}
  >
    <div style={{ position: "relative" }}>
      <Avatar student={student} size="full" />
      {/* 胶带 */}
      {index % 3 === 0 && (
        <div className="tape" style={{
          top: -8, left: "50%", transform: "translateX(-50%) rotate(-2deg)",
          width: 40, height: 14,
        }} />
      )}
    </div>
    <div style={{ marginTop: 8, fontSize: 13, fontWeight: 600, color: "var(--c-deep)" }}>{student.name}</div>
  </button>
);

const StudentMasonry = ({ students, onOpen }) => {
  // 两列瀑布流
  const cols = [[], []];
  students.forEach((s, i) => cols[i % 2].push(s));
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, padding: "8px 20px 40px" }}>
      {cols.map((col, ci) => (
        <div key={ci} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {col.map((s, i) => (
            <MasonryCard key={s.id} student={s} onClick={() => onOpen(s.id)} index={ci * 20 + i} offset={ci} />
          ))}
        </div>
      ))}
    </div>
  );
};

const MasonryCard = ({ student, onClick, index, offset }) => {
  const tilt = (index % 2 === 0 ? -1 : 1) * (1 + (index % 3));
  // 不同高度
  const aspect = [1, 1.25, 0.9, 1.1, 1.3][index % 5];
  return (
    <button
      onClick={onClick}
      className="pop-in"
      style={{
        animationDelay: `${Math.min(index * 0.03, 0.6)}s`,
        padding: 8,
        background: "var(--c-paper)",
        borderRadius: "var(--r-sm)",
        boxShadow: "var(--shadow-soft)",
        transform: `rotate(${tilt}deg)`,
        textAlign: "center",
      }}
    >
      <div style={{ aspectRatio: `1 / ${aspect}`, overflow: "hidden", borderRadius: 4 }}>
        <Avatar student={student} size="full" />
      </div>
      <div className="handwrite" style={{ fontSize: 14, color: "var(--c-deep)", marginTop: 8 }}>
        {student.name}
      </div>
    </button>
  );
};

const StudentFlipbook = ({ students, onOpen }) => {
  const [idx, setIdx] = React.useState(0);
  const containerRef = React.useRef(null);

  // 触摸滑动
  const touchStart = React.useRef(0);
  const onTouchStart = (e) => { touchStart.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (dx > 40 && idx > 0) setIdx(idx - 1);
    else if (dx < -40 && idx < students.length - 1) setIdx(idx + 1);
  };

  const s = students[idx];
  return (
    <div style={{ padding: "8px 20px 40px" }}>
      <div
        ref={containerRef}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{ position: "relative", perspective: "1200px" }}
      >
        <button
          onClick={() => onOpen(s.id)}
          style={{
            width: "100%",
            background: "var(--c-paper)",
            borderRadius: "var(--r-md)",
            padding: 20,
            boxShadow: "var(--shadow-card)",
            textAlign: "center",
            animation: "flipIn .4s ease",
          }}
          key={s.id}
        >
          <div style={{ maxWidth: 220, margin: "0 auto" }}>
            <Avatar student={s} size="full" />
          </div>
          <div className="h1" style={{ fontSize: 22, color: "var(--c-deep)", marginTop: 14 }}>{s.name}</div>
          <div className="handwrite" style={{ fontSize: 12, color: "var(--c-sub)", marginTop: 16 }}>
            ← 左右滑动 · 点击卡片查看 →
          </div>
        </button>
      </div>

      <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 16, marginTop: 20 }}>
        <button
          onClick={() => setIdx(Math.max(0, idx - 1))}
          disabled={idx === 0}
          style={{ ...navBtn, opacity: idx === 0 ? 0.3 : 1 }}
        >←</button>
        <div style={{ fontSize: 14, color: "var(--c-sub)", minWidth: 60, textAlign: "center" }}>
          <span className="handwrite" style={{ fontSize: 20, color: "var(--c-deep)" }}>{idx + 1}</span>
          <span style={{ color: "var(--c-sub)" }}> / {students.length}</span>
        </div>
        <button
          onClick={() => setIdx(Math.min(students.length - 1, idx + 1))}
          disabled={idx === students.length - 1}
          style={{ ...navBtn, opacity: idx === students.length - 1 ? 0.3 : 1 }}
        >→</button>
      </div>

      {/* 进度条 */}
      <div style={{ height: 3, background: "var(--c-line)", borderRadius: 2, margin: "14px 20px", overflow: "hidden" }}>
        <div style={{
          height: "100%",
          width: `${((idx + 1) / students.length) * 100}%`,
          background: "var(--c-primary)",
          transition: "width .3s ease",
        }} />
      </div>

      <style>{`
        @keyframes flipIn {
          from { opacity: 0; transform: rotateY(15deg); }
          to   { opacity: 1; transform: rotateY(0); }
        }
      `}</style>
    </div>
  );
};

const navBtn = {
  width: 44, height: 44, borderRadius: "50%",
  background: "var(--c-paper)",
  border: "1px solid var(--c-line)",
  fontSize: 20,
  color: "var(--c-deep)",
  display: "flex", alignItems: "center", justifyContent: "center",
};

Object.assign(window, { HomePage });
