/* sections-hero.jsx — 풀폭 캐러셀 Hero (5장 자동 회전) */

const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

const SLIDES = [
  {
    id: "main",
    eyebrow: "INTRO · 울산 입시 명문 · 20년+",
    title: <>잊지 않게 가르치고,<br/>매일 부모님께<br/><span className="dh-text-grad-primary">보고합니다.</span></>,
    sub: "1·3·7·30일 자동 복습 · 3회 연속 정답 시 ‘정복’ · 매일 18시 학부모 알림.",
    cta1: { label: "상담 예약하기", href: "consultation.php" },
    cta2: { label: "학원 실적 보기", href: "results.php" },
    imagePlaceholder: "학원 풍경 · 책상 위 책 · 형광펜",
    imageSlotId: "hero-slide-main",
    imageSrc: "landing/photos/sweetlouise-books-5991410_1920.jpg",
    accent: "var(--primary)",
    tag: "01 / 05",
  },
  {
    id: "results",
    eyebrow: "RESULTS · 2025 학년도",
    title: (() => {
      const c = (typeof window !== 'undefined' && window.DAHIM_DATA && window.DAHIM_DATA.counts) || {};
      const topRank = c.top_rank_count || 16;
      const grade1  = c.grade1_count   || 37;
      return <>전교 1등 <span className="dh-text-grad-accent" data-count-key="top_rank_count">{topRank}명</span>,<br/>1등급 릴레이 <span className="dh-text-grad-accent" data-count-key="grade1_count">{grade1}명</span></>;
    })(),
    sub: "대현고 1·2학년 전교 1등 · 약사고 전교 1등 · 대현고 2학년 1학기 전교 10등 內 4명 동시 배출.",
    cta1: { label: "성과 보러가기", href: "results.php" },
    cta2: (() => {
      const c = (typeof window !== 'undefined' && window.DAHIM_DATA && window.DAHIM_DATA.counts) || {};
      const adm = c.admissions_count || 25;
      return { label: `합격 명단 ${adm}건`, href: "results.php" };
    })(),
    imagePlaceholder: "전교 1등 시상 / 학생들 책상",
    imageSlotId: "hero-slide-results",
    imageSrc: "landing/photos/student_highschool.jpg",
    accent: "var(--accent)",
    tag: "02 / 05",
  },
  {
    id: "diagnose",
    eyebrow: "DIAGNOSE · 입학 시 정밀 진단",
    title: <>같은 교실,<br/><span className="dh-text-grad-primary">다른 출발점</span></>,
    sub: "48분 정밀 진단으로 어휘·독해·문법·문학·비문학·메타인지의 강약을 분리해 ‘개별 첫 회차’를 설계합니다.",
    cta1: { label: "정밀 진단 살펴보기", href: "ai_system.php" },
    cta2: { label: "AI 시스템 보기", href: "ai_system.php" },
    imagePlaceholder: "학생이 문제집 푸는 손 · 책상 위",
    imageSlotId: "hero-slide-diagnose",
    imageSrc: "landing/photos/student_elementary.jpg",
    accent: "var(--primary)",
    tag: "03 / 05",
  },
  {
    id: "bank",
    eyebrow: (() => { const c = (typeof window !== 'undefined' && window.DAHIM_DATA && window.DAHIM_DATA.counts) || {}; const t = (c.ebs_questions || 33624) + (c.neasin_questions || 27985); const v = c.videos || 3112; return 'QUESTION BANK · ' + Math.round(t/10000) + '만 문제 + ' + v.toLocaleString() + '강'; })(),
    title: (() => { const c = (typeof window !== 'undefined' && window.DAHIM_DATA && window.DAHIM_DATA.counts) || {}; const t = (c.ebs_questions || 33624) + (c.neasin_questions || 27985); const v = c.videos || 3112; return <>문제은행 <span className="dh-text-grad-accent" data-count-key="q_total">{t.toLocaleString()}</span>제,<br/>동영상 강의 <span className="dh-text-grad-accent" data-count-key="videos">{v.toLocaleString()}</span>강</>; })(),
    sub: "동영상 학습 · 요점 정리 · 문제 풀이까지 한 시스템에. 출판사·학년·학교 단위로 정밀 매칭됩니다.",
    cta1: { label: "시스템 보러가기", href: "curriculum.php" },
    cta2: { label: "커리큘럼 보기", href: "curriculum.php" },
    imagePlaceholder: "도서관 책장 · 책 무더기",
    imageSlotId: "hero-slide-bank",
    imageSrc: "landing/photos/chalkboard_hand.jpg",
    accent: "var(--accent)",
    tag: "04 / 05",
  },
  {
    id: "admission",
    eyebrow: "ADMISSION · 수시·정시·학종",
    title: <>수시·정시·학종,<br/><span className="dh-text-grad-primary">한 사람이</span> 책임집니다.</>,
    sub: "원장 직강 20년+. 생기부 분석부터 목표 대학·최저등급·면접까지 1:1로. AI가 출제하고, 원장이 검수합니다.",
    cta1: { label: "원장 직강 소개", href: "greetings.php" },
    cta2: { label: "입시 컨설팅 상담", href: "consultation.php" },
    imagePlaceholder: "원장 / 칠판 / 강의실",
    imageSlotId: "hero-slide-admission",
    imageSrc: "landing/photos/classroom_purple.jpg",
    accent: "var(--primary)",
    tag: "05 / 05",
  },
];

const AUTO_INTERVAL = 6500;

const HeroCarousel = () => {
  const [idx, setIdx] = useStateH(0);
  const [paused, setPaused] = useStateH(false);
  const total = SLIDES.length;

  useEffectH(() => {
    if (paused) return;
    const t = setTimeout(() => setIdx((i) => (i + 1) % total), AUTO_INTERVAL);
    return () => clearTimeout(t);
  }, [idx, paused, total]);

  const go = (n) => setIdx((n + total) % total);

  return (
    <section
      style={{
        position: "relative",
        padding: "32px 0 60px",
        overflow: "hidden",
      }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {/* bg glow */}
      <div aria-hidden style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "radial-gradient(60% 40% at 75% 10%, rgba(37,99,235,0.06), transparent 70%), radial-gradient(40% 30% at 90% 70%, rgba(234,88,12,0.06), transparent 70%)",
      }}/>

      <div className="wrap" style={{ position: "relative" }}>
        {/* Carousel frame */}
        <div 
          className="dh-glass-card"
          style={{
            position: "relative",
            borderRadius: "var(--r-xl)",
            padding: 12,
            overflow: "hidden",
          }}
        >
          {/* Slides — absolute stacked, fade transition */}
          <div style={{ position: "relative", minHeight: 560 }}>
            {SLIDES.map((s, i) => (
              <Slide key={s.id} slide={s} active={i === idx}/>
            ))}
          </div>

          {/* Controls overlay (bottom) — arrows + autoplay 상태만 표시 */}
          <div style={{
            position: "absolute", left: 0, right: 0, bottom: 0,
            padding: "0 28px 22px",
            display: "flex", alignItems: "center", justifyContent: "flex-end",
            pointerEvents: "none",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, pointerEvents: "auto" }}>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--text-4)", letterSpacing: "0.14em", marginRight: 8, display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ width: 6, height: 6, borderRadius: 6, background: paused ? "var(--text-4)" : "var(--green)" }} className={paused ? "" : "pulse-dot"}/>
                {paused ? "PAUSED" : "AUTOPLAY"}
              </span>
              <CarouselButton onClick={() => go(idx - 1)} aria-label="이전 슬라이드">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
              </CarouselButton>
              <CarouselButton onClick={() => go(idx + 1)} aria-label="다음 슬라이드">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
              </CarouselButton>
            </div>
          </div>

          {/* Progress bar (top) — 가는 붉은색이 옆으로 채워지는 식 */}
          <div aria-hidden style={{
            position: "absolute", top: 0, left: 0, right: 0,
            height: 2, background: "rgba(220,38,38,0.08)",
            borderTopLeftRadius: "var(--r-xl)", borderTopRightRadius: "var(--r-xl)",
            overflow: "hidden",
          }}>
            <div
              key={idx + (paused ? "-p" : "-a")}
              style={{
                height: "100%",
                background: "var(--red)",
                width: "100%",
                animation: paused ? "none" : `progress ${AUTO_INTERVAL}ms linear forwards`,
                transformOrigin: "left",
              }}
            />
          </div>
        </div>

        {/* mini trust bar below */}
        <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "flex-start", rowGap: 2, columnGap: 12, color: "var(--text-3)", fontSize: 12.5 }}>
          <TrustItem>원장 직강 100%</TrustItem>
          <Sep/>
          <TrustItem>20년+ 경력</TrustItem>
          <Sep/>
          <TrustItem>리드인(독서) + 입시·내신</TrustItem>
          <Sep/>
          <TrustItem>매일 18시 학부모 알림</TrustItem>
          <Sep/>
          <TrustItem>출판사·학년·학교 정밀 매칭</TrustItem>
        </div>
      </div>

      <style>{`
        @keyframes progress {
          from { transform: scaleX(0); }
          to { transform: scaleX(1); }
        }
        @keyframes slideFadeIn {
          from { opacity: 0; transform: translateY(8px); }
          to { opacity: 1; transform: none; }
        }
      `}</style>
    </section>
  );
};

const TrustItem = ({ children }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
    <Check size={15} stroke="var(--green)"/> {children}
  </span>
);
const Sep = () => <span style={{ width: 1, height: 12, background: "var(--border)" }}/>;

const CarouselButton = ({ children, ...p }) => (
  <button {...p} style={{
    width: 38, height: 38, borderRadius: 999,
    background: "var(--surface)", border: "1px solid var(--border)",
    color: "var(--text-2)",
    display: "inline-flex", alignItems: "center", justifyContent: "center",
    cursor: "pointer",
    transition: "transform .15s ease, border-color .15s ease",
  }} onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--text)"}
     onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border)"}
  >{children}</button>
);

// ── 슬라이드 ───────────────────────────────────────────────
const Slide = ({ slide, active }) => (
  <div
    aria-hidden={!active}
    style={{
      position: active ? "relative" : "absolute",
      inset: 0,
      opacity: active ? 1 : 0,
      visibility: active ? "visible" : "hidden",
      transition: "opacity .55s ease",
      pointerEvents: active ? "auto" : "none",
      minHeight: 560,
    }}
  >
    <div style={{
      display: "grid", gridTemplateColumns: "1fr 1.1fr", gap: 0,
      minHeight: 560,
    }}>
      {/* LEFT — text */}
      <div style={{
        padding: "44px 36px 80px",
        display: "flex", flexDirection: "column", justifyContent: "center",
        position: "relative",
        minWidth: 0,
      }}>
        <div style={{ animation: active ? "slideFadeIn .55s ease both .1s" : "none" }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "5px 12px", borderRadius: 999,
            background: `color-mix(in oklab, ${slide.accent} 10%, white)`,
            color: slide.accent,
            fontSize: 11, fontWeight: 700, letterSpacing: "0.08em",
            maxWidth: "100%",
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 5, background: slide.accent, flexShrink: 0 }}/>
            <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{slide.eyebrow}</span>
          </div>

          <h1 style={{
            fontSize: "clamp(28px, 3.4vw, 52px)",
            lineHeight: 1.12,
            letterSpacing: "-0.028em",
            fontWeight: 800,
            margin: "24px 0 0",
            textWrap: "balance",
          }}>
            {slide.title}
          </h1>

          <p style={{
            marginTop: 20,
            fontSize: 14.5, lineHeight: 1.6,
            color: "var(--text-3)", maxWidth: "44ch",
          }}>{slide.sub}</p>

          <div style={{ display: "flex", gap: 12, marginTop: 28, flexWrap: "wrap" }}>
            <a 
              href={slide.cta1.href} 
              className="btn btn-primary" 
              style={{
                background: slide.accent === "var(--accent)" ? "linear-gradient(135deg, #ea580c 0%, #ff782e 50%, #c2410c 100%)" : "linear-gradient(135deg, #2563eb 0%, #3b82f6 50%, #1d4ed8 100%)",
                boxShadow: slide.accent === "var(--accent)" ? "0 6px 20px rgba(234,88,12,0.35)" : "0 6px 20px rgba(37,99,235,0.35)",
                border: "none",
              }}
            >
              {slide.cta1.label} <ArrowRight size={15}/>
            </a>
            <a 
              href={slide.cta2.href} 
              className="btn btn-ghost"
              style={{
                backdropFilter: "blur(8px)",
                background: "rgba(255, 255, 255, 0.4)",
              }}
            >
              {slide.cta2.label}
            </a>
          </div>
        </div>

      </div>

      {/* RIGHT — image slot */}
      <div style={{ position: "relative", padding: 12, minHeight: 380 }}>
        <div style={{
          position: "absolute", inset: 12,
          background: slide.imageBg || `linear-gradient(135deg, color-mix(in oklab, ${slide.accent} 8%, var(--surface-soft)) 0%, var(--surface-soft) 100%)`,
          borderRadius: "var(--r-lg)",
          overflow: "hidden",
        }}>
          {/* image slot — src 우선, 비어 있으면 placeholder */}
          <image-slot
            id={slide.imageSlotId}
            shape="rounded"
            src={slide.imageSrc}
            fit={slide.imageFit || "cover"}
            placeholder={slide.imagePlaceholder}
            style={{
              width: "100%", height: "100%",
              "--slot-radius": "var(--r-lg)",
            }}
          />
        </div>

        {/* subtle frame chrome */}
        <div 
          className="dh-glass-card"
          style={{
            position: "absolute", left: 24, top: 24,
            padding: "5px 12px", borderRadius: 8,
            fontSize: 10, fontWeight: 700, color: "var(--text-2)",
            letterSpacing: "0.14em",
            fontFamily: "var(--mono)",
          }}
        >
          {slide.imageSlotId.replace("hero-slide-", "").toUpperCase()}
        </div>
      </div>
    </div>
  </div>
);

Object.assign(window, { HeroCarousel });
