const { useRef, useState, useEffect } = React;

// Scroll so the player section's H2 title lands at the top (eyebrow scrolls
// out, title + subcopy + dark card all in view).
function scrollToPlayer() {
  const el = document.querySelector("#player .section__title");
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 24;
  window.scrollTo({ top, behavior: "smooth" });
}

// ─── Hero visuals — data-driven from persona.heroChat / persona.heroMontage ───

const renderMultiline = (text) => text.split("\n").map((line, i) => (
  <React.Fragment key={i}>{i > 0 && <br />}{line}</React.Fragment>
));

// 1분 소개 애니메이션 — 독립 실행형 HTML 을 iframe 으로 임베드한다.
// 그 애니메이션은 우리 전역(Stage/Phone/clamp …)과 이름이 충돌하므로 같은 스코프에
// 합칠 수 없어, scope·CSS 가 완전히 격리되는 iframe 으로 띄운다. (src: persona.heroVideo)
const HeroVideoVisual = ({ src, poster }) => {
  const frameRef = useRef(null);
  const goFullscreen = () => {
    const el = frameRef.current;
    if (!el) return;
    const req = el.requestFullscreen || el.webkitRequestFullscreen || el.msRequestFullscreen;
    if (req) { try { req.call(el); } catch (_) {} }
  };
  // 포스터는 페르소나별로 다르므로 인라인 배경으로 지정 (로드 전까지 노출)
  const style = poster ? { backgroundImage: `url("${poster}")` } : undefined;
  return (
    <div className="hero-video" style={style}>
      <iframe
        ref={frameRef}
        className="hero-video__frame"
        src={src}
        title="모아링 소개 애니메이션"
        loading="lazy"
        allow="autoplay; fullscreen"
        allowFullScreen
      />
      {/* 전체화면 — iframe 을 네이티브 풀스크린으로. 내부 Stage 가 화면에 맞춰 자동 확대 */}
      <button
        type="button"
        data-track="hero_video_fullscreen"
        className="hero-video__expand"
        onClick={goFullscreen}
        aria-label="영상 전체화면으로 보기"
      >
        <Icon name="maximize" size={16} />
        전체화면
      </button>
    </div>
  );
};

// Chat-style bubble stack (personas 1 & 3)
const HeroChatVisual = ({ chat }) => (
  <div className="hc-stack">
    {chat.bubbles.map((b, i) => {
      const side = b.from === "teacher" ? "out" : "in";

      if (b.type === "link") {
        return (
          <div key={i} className={"hc-bub hc-bub--" + side + " hc-bub--link"}>
            <div className="hc-link__icon">💬</div>
            <div>
              <div className="hc-link__title">{b.title}</div>
              <div className="hc-link__sub">{b.sub}</div>
            </div>
          </div>
        );
      }
      if (b.type === "typing") {
        return (
          <div key={i} className={"hc-bub hc-bub--" + side + " hc-bub--typing"}>
            <span></span><span></span><span></span>
          </div>
        );
      }
      if (b.type === "note") {
        return (
          <div key={i} className="hc-note">({b.text})</div>
        );
      }

      return (
        <div key={i} className={"hc-row hc-row--" + side}>
          {side === "in" && b.who && <div className="hc-who">{b.who}</div>}
          <div className="hc-line">
            <div className={"hc-bub hc-bub--" + side}>
              {renderMultiline(b.text)}
            </div>
            {b.time && <span className="hc-time">{b.time}</span>}
          </div>
        </div>
      );
    })}
    <div className="hc-caption">{chat.caption}</div>
  </div>
);

// Work-montage style (persona 2) — Excel-style sheet showing teacher manually
// typing each student row, with the active cell highlighted + cursor.
const HeroMontageVisual = ({ montage }) => (
  <div className="hm-stack">
    {/* Counter chip */}
    <div className="hm-counter">
      <span className="hm-counter__label">{montage.counter.label}</span>
      {montage.counter.items.map((s, i) => (
        <span key={i} className="hm-counter__pill">{s}</span>
      ))}
    </div>

    {/* Spreadsheet */}
    <div className="hm-sheet">
      <div className="hm-sheet__row hm-sheet__row--head">
        <div className="hm-sheet__cell hm-sheet__cell--num"></div>
        {montage.sheet.columns.map((c, i) => (
          <div key={i} className="hm-sheet__cell">{c}</div>
        ))}
      </div>
      {montage.sheet.rows.map((row, ri) => {
        const hasActive = row.activeCol != null;
        return (
          <div key={ri} className={"hm-sheet__row" + (hasActive ? " hm-sheet__row--active" : "")}>
            <div className="hm-sheet__cell hm-sheet__cell--num">{row.num}</div>
            {row.cells.map((cell, ci) => {
              const isCursor = ci === row.activeCol;
              const isFuture = hasActive && ci > row.activeCol;
              const cls = "hm-sheet__cell"
                + (isCursor ? " hm-sheet__cell--cursor" : "")
                + (isFuture ? " hm-sheet__cell--future" : "");
              return (
                <div key={ci} className={cls}>
                  {cell}{isCursor && <span className="hm-cursor">|</span>}
                </div>
              );
            })}
          </div>
        );
      })}
    </div>

    <div className="hm-narration">{montage.note}</div>
    <div className="hc-caption">{montage.caption}</div>
  </div>
);

// ── Section A: Hero ──
const HeroSection = ({ persona, openCheckout }) => {
  const ref = useRef(null);
  useSectionDwell(ref, "hero");

  return (
    <section className="hero" ref={ref}>
      <div className="container">
        <div className="hero__grid">
          <div>
            <div className="hero__badge reveal reveal-1">
              <span className="hero__badge-dot" />
              {persona.hero.badge}
            </div>
            <h1
              className="hero__headline reveal reveal-2"
              dangerouslySetInnerHTML={{ __html: persona.hero.headline }}
            />
            <p className="hero__subcopy reveal reveal-3">{persona.hero.subcopy}</p>
            <div className="hero__cta-row reveal reveal-4">
              <button
                data-track="hero_start_free"
                className="btn btn--primary btn--lg"
                onClick={() => openCheckout("hero")}
              >
                무료로 시작하기
                <Icon name="arrow-right" size={18} />
              </button>
              <a
                data-track="hero_see_how_it_works"
                className="btn btn--ghost btn--lg"
                href="#player"
                onClick={(e) => {
                  e.preventDefault();
                  track("Hero See How Clicked", { source: "hero", default_solution: persona.defaultSolution });
                  scrollToPlayer();
                }}
              >
                <Icon name="play" size={16} />
                작동 방식 보기
              </a>
            </div>
          </div>

          {/* Hero visual — persona-specific scenario (NOT branded UI) */}
          {/* heroVideo 가 있으면 카톡/몽타주 대신 1분 소개 애니메이션을 iframe 으로 임베드 */}
          <div
            className={"hero__visual reveal reveal-3" + (persona.heroVideo ? " hero__visual--video" : "")}
            aria-hidden={persona.heroVideo ? undefined : "true"}
          >
            {persona.heroVideo ? (
              <HeroVideoVisual src={persona.heroVideo} poster={persona.heroVideoPoster} />
            ) : (
              <>
                {persona.heroChat && <HeroChatVisual chat={persona.heroChat} />}
                {persona.heroMontage && <HeroMontageVisual montage={persona.heroMontage} />}
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

// ── Section B: Empathy ──
const EmpathySection = ({ persona }) => {
  const ref = useRef(null);
  useSectionDwell(ref, "empathy");

  // cases 는 string 또는 { quote, speaker } 객체 둘 다 지원 (구버전 호환).
  const cases = (persona.empathy.cases || [])
    .filter(Boolean)
    .map((c) => (typeof c === "string" ? { quote: c, speaker: null } : c));
  if (cases.length === 0) return null;

  return (
    <section className="section section--deep" ref={ref}>
      <div className="container">
        <SectionHead
          eyebrow="EMPATHY · 현장 인터뷰"
          title={persona.empathy.sectionTitle}
        />
        <div className="empathy__grid">
          {cases.map(({ quote, speaker }, i) => (
            <div className="empathy-card" key={i}>
              <div className="empathy-card__mark">“</div>
              <p className="empathy-card__quote">{quote}</p>
              {speaker && (
                <div className="empathy-card__speaker">
                  <span className="empathy-card__speaker-dash">—</span> {speaker}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// 솔루션 작동 시연 애니메이션 — solution_anim/ 의 독립 실행형 앱을 iframe 으로 임베드.
// (그 앱은 자체 Stage/Phone/clamp 등 전역이 우리와 충돌하므로 hero 영상과 동일하게 iframe 격리.)
// 솔루션 전환은 빈번하므로 iframe 을 리로드하지 않고 postMessage 로 씬만 바꾼다.
// 랜딩 솔루션 key → 애니메이션 씬 key 매핑:
const SOL_SCENE = {
  signup_link: "signup",
  class_setup: "classsetup",
  attendance: "attendance",
  notice_homework: "notice",
  consult: "consult",
  payment: "payment",
};

const SolutionAnimFrame = ({ solutionKey }) => {
  const frameRef = useRef(null);
  const loadedRef = useRef(false);
  // 초기 씬은 src 쿼리(?sol=)로 전달, 이후 전환은 postMessage. src 는 한 번만 설정해 리로드 방지.
  const initialScene = useRef(SOL_SCENE[solutionKey] || "signup").current;

  const postScene = (key) => {
    const scene = SOL_SCENE[key];
    const win = frameRef.current && frameRef.current.contentWindow;
    if (win && scene) win.postMessage({ type: "moaring-sol", key: scene }, "*");
  };

  useEffect(() => {
    if (loadedRef.current) postScene(solutionKey);
  }, [solutionKey]);

  // 전체화면 — iframe 을 네이티브 풀스크린으로. 내부 Stage 가 화면에 맞춰 자동 확대 (hero 와 동일).
  const goFullscreen = () => {
    const el = frameRef.current;
    if (!el) return;
    const req = el.requestFullscreen || el.webkitRequestFullscreen || el.msRequestFullscreen;
    if (req) { try { req.call(el); } catch (_) {} }
  };

  return (
    <React.Fragment>
      <iframe
        ref={frameRef}
        className="anim-slot__frame"
        src={`solution_anim/index.html?embed=1&sol=${initialScene}`}
        title="솔루션 작동 시연"
        loading="lazy"
        allow="autoplay; fullscreen"
        allowFullScreen
        onLoad={() => { loadedRef.current = true; postScene(solutionKey); }}
      />
      <button
        type="button"
        data-track="solution_anim_fullscreen"
        className="anim-slot__expand"
        onClick={goFullscreen}
        aria-label="시연 영상 전체화면으로 보기"
      >
        <Icon name="maximize" size={16} />
        전체화면
      </button>
    </React.Fragment>
  );
};

// ── Section C: Solution Player (★ core) ──
// 좌측 탭이 제거됐고, 모듈 전환은 아래 CardsSection의 카드 클릭으로 일원화.
// 슬롯이 단일 컬럼으로 확장되어 모바일에서도 안의 애니메이션이 잘 보임.
const PlayerSection = ({ persona, activeKey, openCheckout }) => {
  const ref = useRef(null);
  useSectionDwell(ref, "solution_player");

  // Track per-solution view duration
  const viewStartRef = useRef(Date.now());
  const prevKeyRef = useRef(activeKey);

  const [fading, setFading] = useState(false);

  // Whenever activeKey changes, emit Solution Viewed for the previous + fade slot
  useEffect(() => {
    const prev = prevKeyRef.current;
    if (prev && prev !== activeKey) {
      const view_duration_ms = Date.now() - viewStartRef.current;
      track("Solution Viewed", { solution: prev, view_duration_ms, ended_by: "switch" });
      setFading(true);
      const t = setTimeout(() => setFading(false), 220);
      viewStartRef.current = Date.now();
      prevKeyRef.current = activeKey;
      return () => clearTimeout(t);
    }
    viewStartRef.current = Date.now();
    prevKeyRef.current = activeKey;
  }, [activeKey]);

  // flush on page hide
  useEffect(() => {
    const onFlush = () => {
      const view_duration_ms = Date.now() - viewStartRef.current;
      track("Solution Viewed", { solution: prevKeyRef.current, view_duration_ms, ended_by: "page_leave" });
      viewStartRef.current = Date.now();
    };
    window.addEventListener("__flushDwell", onFlush);
    return () => window.removeEventListener("__flushDwell", onFlush);
  }, []);

  const active = solutions.find((s) => s.key === activeKey) || solutions[0];
  const activeIdx = solutions.findIndex((s) => s.key === active.key);

  return (
    <section
      id="player"
      className="section section--dark player-wrap"
      ref={ref}
      style={{ paddingTop: 96, paddingBottom: 96 }}
    >
      <div className="container">
        <div className="player__intro">
          <div className="eyebrow" style={{ color: "var(--color-accent)" }}>SOLUTION · 작동 시연</div>
          <h2 className="section__title" style={{ color: "white" }}>
            카톡 안에서, <em style={{ fontStyle: "normal", color: "var(--color-primary)" }}>실제로</em> 이렇게 움직입니다
          </h2>
          <p className="section__sub" style={{ color: "var(--text-on-dark-muted)" }}>
            지금은 한 가지 모듈을 보고 계세요. <strong style={{ color: "white" }}>아래 카드</strong>에서 자세히 보고 싶은 기능을 누르면, 여기에 작동 영상이 다시 재생됩니다.
          </p>
        </div>

        <div className="player">
          <div className="player__stage">
            <div className="player__head">
              <div>
                <div className="player__nowtag">
                  <span className="player__nowtag-dot" />
                  지금 시연 중 · {String(activeIdx + 1).padStart(2, "0")} / {String(solutions.length).padStart(2, "0")}
                </div>
                <h3 className="player__title">{active.title}</h3>
                <p className="player__desc">{active.cardDesc}</p>
              </div>
              {active.pro && <span className="player__chip">PRO</span>}
            </div>

            <div className={"anim-slot" + (fading ? " anim-slot--fading" : "")}>
              <SolutionAnimFrame solutionKey={active.key} />
            </div>

            <div className="player__footer">
              <div className="player__progress" aria-hidden="true">
                {solutions.map((s, i) => (
                  <span key={s.key} className={i === activeIdx ? "active" : ""} />
                ))}
              </div>
              <button
                data-track="player_start_free"
                className="btn btn--primary"
                onClick={() => openCheckout("section_c")}
              >
                이 기능 무료로 사용해보기
                <Icon name="arrow-right" size={16} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ── Section D: Solution Cards ──
// PlayerSection의 탭이 제거되어, 카드의 "작동 시연 보기" 버튼이 모듈 전환의 유일한 진입점.
// (모듈별 "무료로 시작하기" 보조 CTA는 의미가 약해 의도적으로 제거 — Hero/Player/FinalCTA 의 글로벌 CTA 만 유지)
const CardsSection = ({ switchToSolution, activeKey }) => {
  const ref = useRef(null);
  useSectionDwell(ref, "solution_cards");

  return (
    <section className="section" ref={ref}>
      <div className="container">
        <SectionHead
          eyebrow="MODULES · 6개 모듈"
          title="필요한 것만, 카톡 안에서"
          sub="궁금한 모듈을 누르면 위쪽 무대에서 작동 영상이 재생됩니다. 각 모듈은 독립적으로 켜고 끌 수 있고, 전부 켜도 학부모님이 새로 깔 앱은 0개."
        />
        <div className="cards-grid">
          {solutions.map((s) => {
            const isActive = s.key === activeKey;
            return (
              <div className={"sol-card" + (isActive ? " sol-card--active" : "")} key={s.key}>
                {isActive && (
                  <div className="sol-card__nowtag">
                    <span className="sol-card__nowtag-dot" />
                    위에서 시연 중
                  </div>
                )}
                <div className="sol-card__icon"><Icon name={s.iconName} size={22} /></div>
                <h3 className="sol-card__title">
                  {s.title}
                  {s.pro && <span className="sol-card__pro">PRO</span>}
                </h3>
                <p className="sol-card__desc">{s.cardDesc}</p>
                <button
                  data-track={"card_preview_" + s.key}
                  className="sol-card__cta-primary"
                  onClick={() => {
                    switchToSolution(s.key, "card");
                    setTimeout(scrollToPlayer, 50);
                  }}
                  disabled={isActive}
                >
                  <Icon name="play" size={14} />
                  {isActive ? "위에서 재생 중" : "작동 시연 보기"}
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

// ── Section E: Final CTA ──
// 좌측 칼럼은 카피만 — 별도 CTA 없음. 모든 전환은 우측 패널의 "무료로 시작하기" 한 곳으로 일원화.
// (요금제 선택 단계는 제거됨 — 버튼을 누르면 바로 이메일 사전등록 폼이 열린다.)
const FinalCtaSection = ({ persona, openCheckout }) => {
  const ref = useRef(null);
  useSectionDwell(ref, "final_cta");

  const fc = persona.finalCta;

  return (
    <section className="final" ref={ref}>
      <div className="container">
        <div className="final__inner">
          <div>
            <div className="eyebrow" style={{ color: "var(--color-accent)" }}>FINAL · 시작하기</div>
            <h2 className="final__headline" dangerouslySetInnerHTML={{ __html: fc.headline }} />
            <p className="final__closing">{fc.closing}</p>
          </div>

          <div className="final__panel">
            <div className="final__gift">{window.welcomeGift}</div>
            <h4 className="final__panel-title">시작 직전 체크</h4>
            <ul className="final__check-list">
              {fc.checks.map((c, i) => (
                <li key={i}><Icon name="check" size={18} /> {c}</li>
              ))}
            </ul>
            <button
              data-track="final_start_free"
              className="btn btn--primary btn--block"
              onClick={() => openCheckout("final_cta")}
            >
              무료로 시작하기
              <Icon name="arrow-right" size={18} />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { HeroSection, EmpathySection, PlayerSection, CardsSection, FinalCtaSection });
