/* global React */
// ============================================================
// Section 4 — 故事 Story
// 重写（Sprint 2.L 收尾，2026-05-10）：
//   - 副标题简化一行（用户图 #38）
//   - hero 用 web/assets/story-2007|2014|2024 真实展示图（不再用 face 缩略）
//   - STORY 节点对象有 zh + en 两套，按 lang 切换
//   - INTERLUDES 同样 zh/en
//   - i18n 复用 story.* keys
// ============================================================

function StorySection() {
  const { t, lang } = useI18n();
  const [activeYear, setActiveYear] = React.useState(STORY[0].year);

  const refs = React.useRef({});
  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && e.intersectionRatio > 0.5) {
          setActiveYear(e.target.dataset.year);
        }
      });
    }, { threshold: [0, 0.3, 0.6] });
    Object.values(refs.current).forEach((el) => el && obs.observe(el));
    return () => obs.disconnect();
  }, []);

  // hero 用真实展示图（用户提供的故事 2007/2014/2024）
  const heroCards = [
    { src: 'assets/story-2007.jpg', year: '2007' },  // jpg fallback
    { src: 'assets/story-2014.jpg', year: '2014' },
    { src: 'assets/story-2024.png', year: '2024' },
  ];
  // 实际 2007 是 png — 数据校正
  heroCards[0].src = 'assets/story-2007.png';

  return (
    <div>
      {/* Hero — 副标题压成一行 */}
      <div style={{ textAlign: "center", padding: "48px 24px 60px", position: "relative" }}>
        <div style={{
          fontSize: 12, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase",
          color: "var(--text-soft)", marginBottom: 18,
        }}>
          {t("story.eyebrow")}
        </div>
        <h1 style={{
          fontSize: 56, lineHeight: 1.1, margin: 0, fontWeight: 700,
          letterSpacing: "-0.025em",
        }}>
          {t("story.title")}
        </h1>
        <div style={{
          marginTop: 18, color: "var(--text-soft)", fontSize: 16, lineHeight: 1.5,
          maxWidth: 920, margin: "18px auto 0",
          padding: "0 16px",
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
        }}>
          {t("story.subtitle")}
        </div>

        {/* Hero 3 个真实展示图 */}
        <div style={{
          marginTop: 40,
          display: "flex", justifyContent: "center", gap: 28, flexWrap: "wrap",
        }}>
          {heroCards.map((p, i) => {
            const tilt = [-5, 0, 5][i];
            return (
              <div key={p.year} style={{ transform: `rotate(${tilt}deg)`, transition: "transform 260ms var(--ease)" }}>
                <PolaroidFrame width={170} tilt={0} caption={p.year} hoverLift={false}>
                  <img src={p.src} alt={p.year} draggable={false}
                    style={{ width: 146, height: 146, objectFit: "contain", display: "block", margin: "0 auto", background: "#FAF7F2" }} />
                </PolaroidFrame>
              </div>
            );
          })}
        </div>
      </div>

      {/* Why-it-caught-on / culture interludes */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))",
        gap: 20, margin: "0 auto 48px", maxWidth: 980,
      }}>
        <Interlude entry={STORY_INTERLUDES.whyHot}  lang={lang} accent="var(--primary-soft)" badge={lang === 'zh' ? '火' : '★'} />
        <Interlude entry={STORY_INTERLUDES.culture} lang={lang} accent="var(--accent-soft)" badge={lang === 'zh' ? '文' : '#'} />
        <Interlude entry={STORY_INTERLUDES.endless} lang={lang} accent="var(--bg-soft)"     badge={lang === 'zh' ? '续' : '∞'} />
      </div>

      {/* Timeline */}
      <div style={{ position: "relative", maxWidth: 800, margin: "0 auto", padding: "20px 24px 60px" }}>
        <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 24, textAlign: "center", color: "var(--text)" }}>
          {t("story.timeline")}
        </h2>

        <div style={{
          position: "absolute", left: "calc(50% - 1px)", top: 60, bottom: 80, width: 2,
          background: "repeating-linear-gradient(to bottom, var(--border-strong) 0 6px, transparent 6px 12px)",
          opacity: 0.7,
        }} />

        {STORY.map((s, i) => (
          <TimelineRow key={s.year} s={s} i={i} lang={lang}
            active={activeYear === s.year}
            registerRef={(el) => (refs.current[s.year] = el)} />
        ))}
      </div>

      {/* Credits */}
      <div style={{
        maxWidth: 720, margin: "0 auto",
        padding: "32px 24px 24px",
        textAlign: "center",
        color: "var(--text-soft)",
        fontSize: 13, lineHeight: 1.7,
        borderTop: "1px solid var(--border)",
      }}>
        <div style={{ fontWeight: 600, color: "var(--text)", marginBottom: 8, fontSize: 14 }}>{t("story.credits")}</div>
        {t("story.credits.body")}
      </div>
    </div>
  );
}

function TimelineRow({ s, i, lang, active, registerRef }) {
  const [seen, setSeen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting && e.intersectionRatio > 0.25) setSeen(true); });
    }, { threshold: [0.25] });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  const setRefs = (el) => { ref.current = el; registerRef(el); };
  const left = i % 2 === 0;
  const node = s[lang] || s.zh;
  return (
    <div data-year={s.year} ref={setRefs}
      style={{
        display: "grid", gridTemplateColumns: "1fr 56px 1fr",
        alignItems: "start", gap: 16, marginBottom: 60,
        opacity: seen ? 1 : 0,
        transform: seen ? "translateY(0)" : "translateY(28px)",
        transition: "opacity 700ms var(--ease), transform 700ms var(--ease)",
      }}
    >
      {left ? (
        <React.Fragment>
          <div style={{ textAlign: "right" }}><YearChip year={s.year} active={active} /></div>
          <Node active={active} faceIdx={i} />
          <EventCard title={node.title} body={node.body} active={active} />
        </React.Fragment>
      ) : (
        <React.Fragment>
          <EventCard title={node.title} body={node.body} active={active} alignRight />
          <Node active={active} faceIdx={i} />
          <div style={{ textAlign: "left" }}><YearChip year={s.year} active={active} /></div>
        </React.Fragment>
      )}
    </div>
  );
}

function YearChip({ year, active }) {
  return (
    <div style={{
      display: "inline-block", padding: "6px 14px", borderRadius: 999,
      background: active ? "var(--primary)" : "var(--card)",
      border: `1px solid ${active ? "var(--primary-deep)" : "var(--border-strong)"}`,
      fontWeight: 700, color: active ? "#231C0E" : "var(--text-soft)",
      fontSize: 14, letterSpacing: "0.04em",
      transition: "all 240ms var(--ease)",
      transform: active ? "scale(1.04)" : "scale(1)",
    }}>{year}</div>
  );
}

function Node({ active, faceIdx }) {
  // 用真 face 圆头像作节点
  const faces = window.FACES || [];
  const f = faces.length ? faces[faceIdx % faces.length] : null;
  return (
    <div style={{ display: "flex", justifyContent: "center", paddingTop: 4 }}>
      <div style={{
        width: active ? 56 : 40, height: active ? 56 : 40,
        borderRadius: "50%", background: "var(--card)",
        border: `2px solid ${active ? "var(--primary)" : "var(--border-strong)"}`,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        boxShadow: active ? "0 6px 18px rgba(245,197,106,0.32)" : "var(--shadow-sm)",
        transition: "all 280ms var(--ease)",
        overflow: "hidden",
      }}>
        {f ? (
          <img src={'faces/' + f.file} alt={f.id} draggable={false}
            style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        ) : (
          <PandaGlyph size={active ? 36 : 24} />
        )}
      </div>
    </div>
  );
}

function EventCard({ title, body, active, alignRight }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        background: "var(--card)",
        border: `1px solid ${active ? "var(--primary)" : "var(--border)"}`,
        borderRadius: 14, padding: "16px 18px",
        boxShadow: hover ? "0 12px 28px rgba(40,34,28,0.12)" : (active ? "0 8px 24px rgba(40,34,28,0.10)" : "var(--shadow-sm)"),
        transform: hover ? "translateY(-3px)" : (active ? "translateY(-2px)" : "none"),
        transition: "all 260ms var(--ease)",
        textAlign: alignRight ? "right" : "left",
        cursor: "default",
      }}
    >
      <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 6 }}>{title}</div>
      <div style={{ fontSize: 13, color: "var(--text-soft)", lineHeight: 1.65 }}>{body}</div>
    </div>
  );
}

function Interlude({ entry, lang, accent, badge }) {
  const data = entry[lang] || entry.zh;
  const ref = React.useRef(null);
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });
  const parts = data.body.split(/(\*\*[^*]+\*\*)/g);
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const dx = (e.clientX - r.left) / r.width - 0.5;
    const dy = (e.clientY - r.top) / r.height - 0.5;
    setTilt({ x: dy * -3, y: dx * 3 });
  };
  return (
    <div ref={ref} onMouseMove={onMove} onMouseLeave={() => setTilt({ x: 0, y: 0 })}
      style={{
        background: "var(--card)", border: "1px solid var(--border)", borderRadius: 18,
        padding: "26px 24px 22px", position: "relative",
        transform: `perspective(800px) rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`,
        transition: "transform 240ms var(--ease), box-shadow 240ms var(--ease), border-color 240ms var(--ease)",
        boxShadow: "var(--shadow-sm)",
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.boxShadow = "0 14px 36px rgba(40,34,28,0.10)";
        e.currentTarget.style.borderColor = "var(--border-strong)";
      }}
    >
      <div style={{
        position: "absolute", top: -14, right: 22,
        width: 44, height: 44, borderRadius: "50%",
        background: accent, border: "1px solid var(--border)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: 22, fontWeight: 700, color: "var(--text)",
        boxShadow: "var(--shadow-sm)",
        transform: `translate(${tilt.y * 4}px, ${tilt.x * -4}px)`,
        transition: "transform 240ms var(--ease)",
      }}>
        {badge}
      </div>
      <div style={{ fontWeight: 700, fontSize: 17, marginBottom: 10, paddingRight: 40 }}>{data.title}</div>
      <div style={{ fontSize: 14, color: "var(--text-soft)", lineHeight: 1.75 }}>
        {parts.map((p, i) => p.startsWith("**")
          ? <strong key={i} style={{ color: "var(--text)", fontWeight: 600 }}>{p.slice(2, -2)}</strong>
          : <React.Fragment key={i}>{p}</React.Fragment>)}
      </div>
    </div>
  );
}

window.StorySection = StorySection;
