// Stories page — with parallax opening hero

function StoryReviewCard({ review, openReview }) {
  const isForeign = review.lang && review.lang !== "KO";
  const stars = "★".repeat(review.rating) + "☆".repeat(5 - review.rating);
  return (
    <button className="review-card" onClick={() => openReview(review)}>
      <div className="review-head">
        <span className="review-stars">{stars}</span>
        <span style={{fontSize:16}}>{review.flag}</span>
        <span>·</span>
        <span>{review.country}</span>
        <span>·</span>
        <span className="mono">{review.date}</span>
        <span>·</span>
        <span style={{color:"var(--fg-default)",fontWeight:500}}>{review.author}</span>
        {isForeign && <span className="badge badge-lang" style={{marginLeft:"auto"}}>{review.lang}</span>}
      </div>
      <h4 className="review-title">{review.title}</h4>
      <div className={"review-body" + (isForeign ? " review-body-en" : "")}>{review.body}</div>
      {isForeign && review.bodyKo && (
        <div className="review-translation">
          <div className="review-translation-label">한국어 번역</div>
          {review.titleKo && <div style={{fontWeight:600,marginBottom:4}}>{review.titleKo}</div>}
          <div>{review.bodyKo}</div>
        </div>
      )}
      {review.reply && (
        <div className="review-reply">
          <div className="review-reply-label">💬 개발자 답변</div>
          <div>{review.reply}</div>
        </div>
      )}
    </button>
  );
}

function StorySection({ story, openReview, setActiveId, registerRef }) {
  const ref = React.useRef(null);
  const [expanded, setExpanded] = React.useState(false);
  const extras = story.extras || [];
  const extraCount = story.extra || extras.length;

  React.useEffect(() => {
    if (!ref.current) return;
    registerRef(story.id, ref.current);
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting && e.intersectionRatio > 0.25) setActiveId(story.id); });
    }, { threshold: [0.25, 0.5] });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [story.id]);

  return (
    <section ref={ref} className="story-section" data-category-theme={story.theme} id={`story-${story.id}`}>
      <div className="story-chapter-mark">{story.chapter}</div>
      <h2 className="story-title">{story.title}</h2>
      <div className="callout">
        <div className="callout-icon">✎</div>
        <div>{story.callout}</div>
      </div>
      <Narrative style={{marginLeft:0, maxWidth:"64ch"}}>
        {story.narrative.map((p, i) => <p key={i}>{p}</p>)}
      </Narrative>
      <div style={{marginTop: 32}}>
        {story.featured.map((r, i) => (
          <StoryReviewCard key={`f-${i}`} review={r} openReview={openReview} />
        ))}
        {expanded && extras.map((r, i) => (
          <StoryReviewCard key={`x-${i}`} review={r} openReview={openReview} />
        ))}
        {extraCount > 0 && (
          <button
            className="story-show-more"
            onClick={() => setExpanded(v => !v)}
            aria-expanded={expanded}
          >
            {expanded ? `접기 ▴` : `더보기 ▾ 다른 리뷰 ${extraCount}개`}
          </button>
        )}
      </div>
    </section>
  );
}

/* Parallax hero for Stories — scroll-driven */
function StoriesHeroParallax({ data }) {
  const ref = React.useRef(null);
  const [p, setP] = React.useState(0); // 0 (start) → 1 (scrolled past)
  const scrollY = useScrollY();
  const [base, setBase] = React.useState(null);

  React.useEffect(() => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    setBase(r.top + window.scrollY);
  }, []);

  const vh = typeof window === "undefined" ? 900 : window.innerHeight;
  React.useEffect(() => {
    if (base == null) return;
    const raw = (scrollY - base + vh * 0.2) / (vh * 0.9);
    setP(Math.max(0, Math.min(1, raw)));
  }, [scrollY, base, vh]);

  // deterministic stars behind hero
  const stars = React.useMemo(() => {
    const arr = [];
    let seed = 13;
    const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
    for (let i = 0; i < 30; i++) {
      arr.push({ x: rnd()*100, y: rnd()*100, r: 1 + rnd()*2, d: rnd()*5 });
    }
    return arr;
  }, []);

  const quoteLines = [
    "2016년 2월 10일, 첫 빌드가 Apple 서버에 올라갔다.",
    "2019년 9월 25일, 마지막 업데이트가 있었다.",
    "그 사이에 <em>2,200명</em>이 리뷰를 썼고, <em>261만 번</em>의 다운로드가 있었다.",
  ];

  // individual line appearance thresholds
  const lineActive = (i) => p > (0.15 + i * 0.18);

  return (
    <section ref={ref} className="stories-hero">
      <div className="stories-hero-bg">
        <div className="stories-hero-bg-stars">
          {stars.map((s, i) => (
            <span key={i} style={{
              left: `${s.x}%`,
              top: `${s.y}%`,
              width: `${s.r}px`,
              height: `${s.r}px`,
              animationDelay: `${s.d}s`,
            }} />
          ))}
        </div>
        <div className="stories-float stories-float-a" style={{ transform: `translate3d(0, ${p*-60}px, 0)` }} />
        <div className="stories-float stories-float-b" style={{ transform: `translate3d(0, ${p*80}px, 0)` }} />
        <div className="stories-float stories-float-c" style={{ transform: `translate3d(0, ${p*-40}px, 0)` }} />
      </div>

      <div className="stories-hero-mark">첫 페이지 · The Archive of Voices</div>
      <h1 style={{ transform: `translate3d(0, ${p*-30}px, 0)`, opacity: 1 - p*0.35 }}>
        투데잇이라는 이름으로<br/>보낸 <em>10년</em>
      </h1>

      <div className="stories-hero-quote">
        {quoteLines.map((line, i) => (
          <span
            key={i}
            className={lineActive(i) ? "is-in" : ""}
            style={{ transitionDelay: `${i * 60}ms` }}
            dangerouslySetInnerHTML={{ __html: line }}
          />
        ))}
      </div>

      <div className="stories-hero-figures" style={{ transform: `translate3d(0, ${p*-10}px, 0)` }}>
        <div className="stories-hero-fig">
          <div className="stories-hero-fig-num"><CountUp end={2200} format="exact" /></div>
          <div className="stories-hero-fig-lbl">목소리</div>
        </div>
        <div className="stories-hero-fig">
          <div className="stories-hero-fig-num"><CountUp end={164} format="exact" /></div>
          <div className="stories-hero-fig-lbl">국가</div>
        </div>
        <div className="stories-hero-fig">
          <div className="stories-hero-fig-num">13</div>
          <div className="stories-hero-fig-lbl">카테고리</div>
        </div>
        <div className="stories-hero-fig">
          <div className="stories-hero-fig-num">7<span style={{fontSize:18}}>년</span>5<span style={{fontSize:18}}>개월</span></div>
          <div className="stories-hero-fig-lbl">기록된 기간</div>
        </div>
      </div>
    </section>
  );
}

function StoriesPage({ openReview }) {
  const data = window.ARCHIVE_DATA;
  const [activeId, setActiveId] = React.useState(data.stories[0].id);
  const [progress, setProgress] = React.useState(0);
  const refs = React.useRef({});

  React.useEffect(() => {
    const onScroll = () => {
      const doc = document.documentElement;
      const scrolled = (window.scrollY) / (doc.scrollHeight - doc.clientHeight);
      setProgress(Math.min(1, Math.max(0, scrolled)));
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const registerRef = (id, el) => { refs.current[id] = el; };

  const scrollTo = (id) => {
    const el = refs.current[id];
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 80;
    window.scrollTo({ top, behavior: "smooth" });
  };

  return (
    <div className="stories-layout">
      <div className="stories-progress">
        <div className="stories-progress-bar" style={{height: `${progress * 100}%`}}></div>
      </div>

      <div className="stories-main">
        <StoriesHeroParallax data={data} />

        {data.stories.map((s) => (
          <StorySection key={s.id} story={s} openReview={openReview} setActiveId={setActiveId} registerRef={registerRef} />
        ))}

        <section className="stories-epilogue">
          <h2>마지막 말</h2>
          <Narrative>
            <p>{data.epilogue}</p>
          </Narrative>
        </section>
      </div>

      <aside className="stories-toc">
        <div className="toc-title">목차</div>
        <ul className="toc-list">
          {data.stories.map((s) => (
            <li key={s.id}>
              <button className={"toc-item" + (activeId === s.id ? " active" : "")} onClick={() => scrollTo(s.id)}>
                <span className="toc-bullet"></span>
                <span>{s.id}. {s.title}</span>
              </button>
            </li>
          ))}
        </ul>
      </aside>
    </div>
  );
}

Object.assign(window, { StoriesPage });
