// StudentDetail.jsx —— 同学主页：大图 + 家长寄语 + 左右切换
const StudentDetail = ({ student, students, onClose, onNav }) => {
  const idx = students.findIndex(s => s.id === student.id);
  const prev = idx > 0 ? students[idx - 1] : null;
  const next = idx < students.length - 1 ? students[idx + 1] : null;

  // 触摸滑动切换
  const tsX = React.useRef(0);
  const tsY = React.useRef(0);
  const onTouchStart = (e) => {
    tsX.current = e.touches[0].clientX;
    tsY.current = e.touches[0].clientY;
  };
  const onTouchEnd = (e) => {
    const dx = e.changedTouches[0].clientX - tsX.current;
    const dy = e.changedTouches[0].clientY - tsY.current;
    if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 50) {
      if (dx > 0 && prev) onNav(prev.id);
      else if (dx < 0 && next) onNav(next.id);
    }
  };

  return (
    <div
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      className="fade-in"
      style={{
        minHeight: "100vh", minHeight: "100svh",
        background: "var(--c-bg)",
        paddingBottom: 100,
      }}
      key={student.id}
    >
      {/* 顶部条 */}
      <div style={{
        position: "sticky", top: 0, zIndex: 10,
        padding: "12px 16px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        background: "color-mix(in srgb, var(--c-bg) 85%, transparent)",
        backdropFilter: "blur(8px)",
      }}>
        <button onClick={onClose} style={topBtn}>← 返回</button>
        <div style={{ fontSize: 12, color: "var(--c-sub)" }}>
          {idx + 1} / {students.length}
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <button onClick={() => prev && onNav(prev.id)} disabled={!prev} style={{ ...topBtn, opacity: prev ? 1 : 0.3 }}>←</button>
          <button onClick={() => next && onNav(next.id)} disabled={!next} style={{ ...topBtn, opacity: next ? 1 : 0.3 }}>→</button>
        </div>
      </div>

      {/* 照片区 —— 点击放大 */}
      <PhotoHero student={student} />

      {/* 姓名/昵称 */}
      <div style={{ textAlign: "center", padding: "22px 24px 8px" }}>
        <div className="h1" style={{ fontSize: 34, color: "var(--c-deep)", lineHeight: 1.1 }}>{student.name}</div>
      </div>

      {/* 爸妈寄语卡 */}
      <LetterCard msg={student.msg} color={student.color} />

      {/* 同学小导航（缩略） */}
      <MiniNav students={students} currentId={student.id} onNav={onNav} />
    </div>
  );
};

const topBtn = {
  background: "var(--c-paper)",
  border: "1px solid var(--c-line)",
  borderRadius: 999,
  padding: "6px 14px",
  fontSize: 13,
  color: "var(--c-deep)",
  minWidth: 36, height: 32,
  display: "inline-flex", alignItems: "center", justifyContent: "center",
};

// 生成占位图的柔和渐变（无真实照片时使用）
const photoBackground = (student, photoId) => {
  const seed = (photoId || "").split("").reduce((a, c) => a + c.charCodeAt(0), student.id * 37);
  const h1 = seed % 360;
  const h2 = (h1 + 40) % 360;
  return `linear-gradient(135deg, hsl(${h1} 60% 78%) 0%, hsl(${h2} 55% 62%) 100%)`;
};

const PhotoSlot = ({ student, photo, style, showCaption = false, big = false }) => (
  <div style={{
    aspectRatio: "3 / 4",
    borderRadius: 6,
    background: photoBackground(student, photo.id),
    position: "relative",
    overflow: "hidden",
    ...style,
  }}>
    {/* 柔光 */}
    <div style={{
      position: "absolute", top: "-15%", left: "-10%",
      width: "70%", height: "70%",
      background: "radial-gradient(circle, rgba(255,255,255,0.5), transparent 60%)",
    }} />
    {/* 昵称首字 */}
    <div style={{
      position: "absolute", inset: 0,
      display: "flex", alignItems: "center", justifyContent: "center",
      color: "rgba(255,255,255,0.85)",
      fontFamily: "var(--font-display)",
      fontSize: big ? 72 : 34,
      textShadow: "0 2px 12px rgba(0,0,0,0.15)",
    }}>{student.name.slice(0, 1)}</div>
    {/* 相机图标小小的角落 */}
    <div style={{
      position: "absolute", bottom: 8, right: 8,
      opacity: 0.45,
    }}>
      <svg viewBox="0 0 24 24" width={big ? 18 : 12} height={big ? 18 : 12} fill="none" stroke="white" strokeWidth="1.5">
        <rect x="3" y="7" width="18" height="13" rx="2"/>
        <circle cx="12" cy="13.5" r="3.5"/>
        <path d="M8 7l1.5-2.5h5L16 7"/>
      </svg>
    </div>
    {/* 真实照片（有 src 时覆盖占位） */}
    {photo.src && (
      <img
        src={photo.src}
        alt={photo.caption || ""}
        onError={(e) => { e.currentTarget.style.display = "none"; }}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
      />
    )}
    {showCaption && photo.caption && (
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0,
        padding: "24px 12px 10px",
        background: "linear-gradient(transparent, rgba(0,0,0,0.55))",
        color: "white", fontSize: 12, fontWeight: 500,
        textAlign: "center",
        zIndex: 2,
      }}>{photo.caption}</div>
    )}
  </div>
);

const PhotoHero = ({ student }) => {
  // 兜底：老数据没有 photos 字段
  const photos = (student.photos && student.photos.length > 0)
    ? student.photos
    : [{ id: `p${student.id}-default`, caption: "毕业照 · 2026" }];

  const [active, setActive] = React.useState(0);
  const [zoomIdx, setZoomIdx] = React.useState(null); // null | number
  const current = photos[active];

  // 主照片左右滑切换
  const tsX = React.useRef(0);
  const onTS = (e) => { tsX.current = e.touches[0].clientX; e.stopPropagation(); };
  const onTE = (e) => {
    const dx = e.changedTouches[0].clientX - tsX.current;
    if (Math.abs(dx) > 40) {
      e.stopPropagation();
      if (dx > 0) setActive((active - 1 + photos.length) % photos.length);
      else        setActive((active + 1) % photos.length);
    }
  };

  return (
    <>
      {/* 主照片 —— 像贴在相册上的一张大照片 */}
      <div style={{ padding: "20px 24px 0", display: "flex", justifyContent: "center" }}>
        <div
          onTouchStart={onTS}
          onTouchEnd={onTE}
          onClick={() => setZoomIdx(active)}
          style={{
            width: "min(280px, 70vw)",
            background: "white",
            padding: "14px 14px 44px",
            boxShadow: "var(--shadow-card)",
            transform: "rotate(-1.5deg)",
            cursor: "zoom-in",
            position: "relative",
          }}
        >
          <PhotoSlot student={student} photo={current} />
          <div style={{
            position: "absolute", bottom: 10, left: 0, right: 0,
            textAlign: "center",
            fontSize: 14, color: "var(--c-sub)",
            fontFamily: "var(--font-hand)",
          }}>
            {current.caption}
          </div>
          {/* 胶带 */}
          <div className="tape" style={{ top: -10, left: "50%", transform: "translateX(-50%) rotate(-3deg)" }} />
          {/* 右上角小计数 */}
          <div style={{
            position: "absolute", top: 20, right: 22,
            background: "rgba(29,53,87,0.75)",
            color: "white",
            fontSize: 11,
            padding: "2px 8px",
            borderRadius: 999,
            fontWeight: 500,
          }}>{active + 1} / {photos.length}</div>
        </div>
      </div>

      {/* 缩略图条 */}
      {photos.length > 1 && (
        <div style={{
          display: "flex",
          gap: 8,
          justifyContent: "center",
          padding: "18px 16px 0",
          flexWrap: "wrap",
        }}>
          {photos.map((p, i) => (
            <button
              key={p.id}
              onClick={() => setActive(i)}
              style={{
                padding: 0,
                width: 52,
                borderRadius: 6,
                overflow: "hidden",
                border: i === active ? "2.5px solid var(--c-primary)" : "2.5px solid transparent",
                boxShadow: i === active ? "0 4px 10px rgba(230,57,70,0.25)" : "0 2px 4px rgba(29,53,87,0.1)",
                transition: "all .2s",
                transform: i === active ? "scale(1.06)" : "scale(1)",
              }}
            >
              <PhotoSlot student={student} photo={p} style={{ borderRadius: 3 }} />
            </button>
          ))}
        </div>
      )}

      {/* 全屏 Lightbox（左右滑切换） */}
      {zoomIdx !== null && (
        <Lightbox
          student={student}
          photos={photos}
          index={zoomIdx}
          setIndex={setZoomIdx}
          onClose={() => setZoomIdx(null)}
        />
      )}
    </>
  );
};

const Lightbox = ({ student, photos, index, setIndex, onClose }) => {
  const tsX = React.useRef(0);
  const onTS = (e) => { tsX.current = e.touches[0].clientX; };
  const onTE = (e) => {
    const dx = e.changedTouches[0].clientX - tsX.current;
    if (Math.abs(dx) > 50) {
      if (dx > 0) setIndex((index - 1 + photos.length) % photos.length);
      else        setIndex((index + 1) % photos.length);
    }
  };
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowLeft")  setIndex((index - 1 + photos.length) % photos.length);
      else if (e.key === "ArrowRight") setIndex((index + 1) % photos.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [index]);

  const cur = photos[index];
  return (
    <div
      onClick={onClose}
      onTouchStart={onTS}
      onTouchEnd={onTE}
      style={{
        position: "fixed", inset: 0,
        background: "rgba(29,53,87,0.92)",
        zIndex: 100,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        padding: 20,
        animation: "fadeIn .2s ease",
        cursor: "zoom-out",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{ width: "min(420px, 88vw)", animation: "zoomIn .3s cubic-bezier(.2,.9,.3,1.2)" }}
        key={index}
      >
        <PhotoSlot student={student} photo={cur} big />
      </div>
      <div style={{ color: "rgba(255,255,255,0.9)", fontSize: 15, marginTop: 20, fontFamily: "var(--font-hand)" }}>
        {cur.caption}
      </div>
      <div style={{ color: "rgba(255,255,255,0.55)", fontSize: 12, marginTop: 10 }}>
        {index + 1} / {photos.length} · 左右滑动切换
      </div>

      {/* PC 箭头 */}
      <button
        onClick={(e) => { e.stopPropagation(); setIndex((index - 1 + photos.length) % photos.length); }}
        style={arrowBtn("left")}
      >←</button>
      <button
        onClick={(e) => { e.stopPropagation(); setIndex((index + 1) % photos.length); }}
        style={arrowBtn("right")}
      >→</button>

      <style>{`@keyframes zoomIn { from { transform: scale(0.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }`}</style>
    </div>
  );
};

const arrowBtn = (side) => ({
  position: "absolute",
  top: "50%", transform: "translateY(-50%)",
  [side]: 16,
  width: 44, height: 44,
  borderRadius: "50%",
  background: "rgba(255,255,255,0.15)",
  color: "white",
  fontSize: 22,
  backdropFilter: "blur(8px)",
  display: "flex", alignItems: "center", justifyContent: "center",
});

const LetterCard = ({ msg, color }) => (
  <div style={{
    margin: "28px 20px 0",
    background: "var(--c-paper)",
    borderRadius: "var(--r-lg)",
    padding: "28px 22px 26px",
    boxShadow: "var(--shadow-soft)",
    position: "relative",
    border: "1px solid var(--c-line)",
  }}>
    {/* 角标 */}
    <div style={{
      position: "absolute", top: -14, left: 22,
      background: color || "var(--c-accent)",
      padding: "4px 14px",
      borderRadius: 999,
      fontSize: 12,
      fontWeight: 600,
      color: "var(--c-deep)",
      fontFamily: "var(--font-display)",
    }}>
      💌 家长寄语
    </div>

    {/* 引号 */}
    <div style={{
      position: "absolute", top: 16, right: 20,
      fontFamily: "serif",
      fontSize: 52,
      color: "var(--c-primary)",
      opacity: 0.2,
      lineHeight: 1,
    }}>"</div>

    <div className="handwrite" style={{
      fontSize: 17,
      lineHeight: 1.9,
      color: "var(--c-deep)",
      whiteSpace: "pre-wrap",
      textWrap: "pretty",
    }}>
      {msg}
    </div>

    {/* 装饰横线 */}
    <div style={{
      marginTop: 16,
      height: 1,
      background: `linear-gradient(90deg, transparent, ${"var(--c-line)"}, transparent)`,
    }} />
    <div className="handwrite" style={{ fontSize: 12, color: "var(--c-sub)", textAlign: "right", marginTop: 8 }}>
      — 写于 2026 年毕业季
    </div>
  </div>
);

const MiniNav = ({ students, currentId, onNav }) => {
  const scRef = React.useRef(null);
  React.useEffect(() => {
    const el = scRef.current?.querySelector(`[data-id="${currentId}"]`);
    if (el && scRef.current) {
      const c = scRef.current;
      const offset = el.offsetLeft - c.clientWidth / 2 + el.clientWidth / 2;
      c.scrollTo({ left: offset, behavior: "smooth" });
    }
  }, [currentId]);

  return (
    <div style={{ marginTop: 32, padding: "20px 0 0" }}>
      <div className="handwrite" style={{ fontSize: 13, color: "var(--c-sub)", textAlign: "center", marginBottom: 10 }}>
        翻到其他同学 →
      </div>
      <div
        ref={scRef}
        style={{
          display: "flex", gap: 10,
          overflowX: "auto",
          padding: "6px 20px 20px",
          scrollbarWidth: "none",
        }}
      >
        {students.map(s => (
          <button
            key={s.id}
            data-id={s.id}
            onClick={() => onNav(s.id)}
            style={{
              flexShrink: 0,
              width: 56,
              padding: 0,
              textAlign: "center",
              opacity: s.id === currentId ? 1 : 0.55,
              transform: s.id === currentId ? "scale(1.1)" : "scale(1)",
              transition: "all .2s ease",
            }}
          >
            <div style={{
              width: 56, height: 56,
              borderRadius: "50%",
              overflow: "hidden",
              border: s.id === currentId ? "3px solid var(--c-primary)" : "2px solid transparent",
            }}>
              <Avatar student={s} size="full" />
            </div>
            <div style={{ fontSize: 10, color: "var(--c-deep)", marginTop: 4, whiteSpace: "nowrap" }}>
              {s.name.slice(-2)}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { StudentDetail });
