// 시안 A — Classic / Editorial
// 보편적인 교회 홈페이지 구조. 정돈된 카드 그리드, 따뜻한 종이톤, 산뜻한 푸른 포인트.
const { useState, useEffect, useRef, useMemo } = React;

// ─── 안전장치: data.js 로드 실패 시 크래시 방지 ───
if (!window.CHURCH) {
  window.CHURCH = {
    nameKo: '맑은빛 세광교회', nameEn: 'Heallight Church',
    tagline: '주를 알고, 주를 알리며, 주와 함께하는 교회',
    taglineEn: 'To know HIM, to make HIM known, to live with HIM.',
    themeYear: 2026, themeKo: '성령으로 부흥하라', themeEn: 'Revival in the Spirit',
    address: { full: '서울시 서대문구 신촌로26길 11', mapAddress: '서울특별시 서대문구 신촌로26길 11', lat: 37.5567, lng: 126.9385 },
    thisWeek: { date: '', season: '', sermonTitle: '', sermonTitleEn: '', scripture: '', preacher: '박병규 목사', scriptureText: '', notices: [] },
    services: [
      { name: '주일 온세대예배 1부', time: '주일 9:30am', place: '그레이스홀 (B1)', dot: 'primary' },
      { name: '주일 온세대예배 2부', time: '주일 11:00am', place: '그레이스홀 (B1)', dot: 'primary' },
      { name: '수요낮예배', time: '수요일 10:30am', place: '그레이스홀 (B1)', dot: 'primary' },
      { name: '온마음 아침예배', time: '월-금 5:30am', place: '그레이스홀 (B1)', dot: 'primary' },
    ],
    communities: [
      { name: '맑은빛 영유아부', desc: '주일 11am · 유리방(B1)', age: '0-6세' },
      { name: '세광 어린이부', desc: '주일 11am · 비전홀(4F)', age: '초등' },
      { name: '틴틴 청소년부', desc: '주일 11am · 남신도실(5F)', age: '중·고등' },
      { name: '푸른빛 청년부', desc: '주일 11am · 남신도실(5F)', age: '20-30대' },
      { name: '온세대 장년 공동체', desc: '주일 1·2부 예배', age: '전 세대' },
    ],
    pastor: { name: '박병규', title: '담임목사', titleEn: 'Rev. B K Park, Senior Pastor',
      education: ['영남신학대학교 신학과 (B.A.)', '한신대학교 신학전문대학원 실천신학 (M.Div.)'],
      ministry: '맑은빛세광교회 담임목사 시무',
      message: '맑은빛세광교회 홈페이지를 찾아주신 여러분을 예수 그리스도의 이름으로 환영합니다.' },
    history: [], prayerPoints: [], weeklyEssay: null,
    account: { bank: '신한', number: '100-034-146193', holder: '한국기독교장로회 세광교회' },
  };
}
if (!window.getCopy) {
  window.getCopy = function(key) {
    try { var v = localStorage.getItem('hlc-copy-' + key); if (v != null) return v; } catch(e) {}
    var d = window.SITE_COPY_DEFAULTS;
    return (d && d[key] != null) ? d[key] : '';
  };
}
const { useScrollSpy, NAV_ITEMS, scrollToId, Icon, LogoLockup, CrossPattern, PhotoSlot,
  SectionTitle, YouTubeCard, YouTubeArchive, ArchiveList, CrossBadge,
  IllustratedMap, KakaoEmbedMap, copyText, useCopyButton } = window;

// ─────────── 동선 카드 (이대역 / 신촌역 탭 전환) ───────────
function RouteStepsCard() {
  const c = window.CHURCH;
  const gc = window.getCopy;
  const [tab, setTab] = useState("edae");
  const parseSteps = (key, fallback) => {
    try { const v = gc && gc(key); if (v) return JSON.parse(v); } catch(e) {}
    return fallback;
  };
  const stepsEdae = parseSteps("visit.routeEdae", c.routeStepsFromEdae);
  const stepsSinchon = parseSteps("visit.routeSinchon", c.routeStepsFromSinchon);
  const tabs = [
  { id: "edae", label: "이대역에서", subtitle: "6번 출구 · 도보 3분", steps: stepsEdae, color: "var(--primary)" },
  { id: "sinchon", label: "신촌역에서", subtitle: "5번 출구 · 도보 8분", steps: stepsSinchon, color: "var(--mint-deep)" }];

  const cur = tabs.find((t) => t.id === tab) || tabs[0];
  return (
    <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 14, padding: 28, fontFamily: "var(--font-sans)" }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <div className="eyebrow" style={{ color: cur.color }}>Step by Step</div>
        <h3 style={{ fontSize: 18, fontWeight: 600, margin: 0 }}>상세 동선 안내</h3>
      </div>
      {/* 탭 */}
      <div style={{ display: "inline-flex", padding: 4, background: "var(--paper-2)", borderRadius: 999, marginBottom: 22, gap: 4 }}>
        {tabs.map((t) =>
        <button key={t.id} onClick={() => setTab(t.id)} style={{
          border: 0,
          background: t.id === tab ? "var(--card)" : "transparent",
          color: t.id === tab ? t.color : "var(--ink-3)",
          padding: "8px 16px", borderRadius: 999,
          fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700,
          boxShadow: t.id === tab ? "0 2px 6px -2px rgba(20,30,60,0.12)" : "none",
          cursor: "pointer",
          display: "inline-flex", flexDirection: "column", alignItems: "flex-start", gap: 1
        }}>
            <span>{t.label}</span>
            <span style={{ fontSize: 10, fontWeight: 500, color: t.id === tab ? "var(--ink-3)" : "var(--ink-3)", letterSpacing: "0.04em" }}>{t.subtitle}</span>
          </button>
        )}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {cur.steps.map((s) =>
        <div key={s.n} style={{ display: "flex", gap: 16 }}>
            <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: cur.color, color: "white",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontWeight: 700, fontSize: 14, flexShrink: 0
          }}>{s.n}</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>{s.title}</div>
              <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.6 }}>{s.body}</div>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ─────────── 카카오지도 스타일 약도 ───────────
// 신촌로 수평축 위에 2호선 + 양쪽 끝의 신촌역·이대역.
// 신촌로26길이 중앙에서 남쪽으로 내려가 좌측으로 꺾이며 그 모퉁이에 우리 교회.
function KakaoStyleMapV2() {
  return (
    <div style={{ position: "absolute", inset: 0, fontFamily: "var(--font-sans)", background: "#fbf8f1" }}>
      <svg viewBox="0 0 800 500" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" style={{ display: "block" }}>
        <defs>
          <filter id="mapShadow" x="-50%" y="-50%" width="200%" height="200%">
            <feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#1a2238" floodOpacity="0.14" />
          </filter>
          <filter id="bldShadow" x="-30%" y="-30%" width="160%" height="160%">
            <feDropShadow dx="1" dy="3" stdDeviation="2.5" floodColor="#1a2238" floodOpacity="0.18" />
          </filter>
          <linearGradient id="mapBg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#fbf8f1" />
            <stop offset="100%" stopColor="#f4efe1" />
          </linearGradient>
          <linearGradient id="bldFace" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#fff7e6" />
            <stop offset="100%" stopColor="#ece2c8" />
          </linearGradient>
          <linearGradient id="bldChurch" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#eef3fb" />
            <stop offset="100%" stopColor="#c4d2e6" />
          </linearGradient>
        </defs>

        <rect width="800" height="500" fill="url(#mapBg)" rx="12" />

        {/* 노고산 — 남측 녹지 */}
        <path d="M 200 500 C 300 420, 420 400, 500 500 Z" fill="#dde7d3" opacity="0.85" />
        <text x="350" y="475" fill="#7a9070" fontSize="11" fontWeight="700" letterSpacing="0.06em">노고산 Nogosan</text>

        {/* 신촌로 — 도로 줄 중간(가운데)에 라벨 */}
        <path d="M 0 160 L 800 160" stroke="#dfd6bc" strokeWidth="48" />
        <path d="M 0 160 L 800 160" stroke="#ffffff" strokeWidth="42" />
        <path d="M 0 160 L 800 160" stroke="#d8d0b6" strokeWidth="1.5" strokeDasharray="12 12" />
        <text x="400" y="164" fill="#9c8c5e" fontSize="11" fontWeight="700" letterSpacing="0.04em" textAnchor="middle">신촌로 Sinchon-ro</text>

        {/* 신촌로 26길 — 약간 우측으로 (x=460) */}
        <path d="M 460 160 L 460 380 L 290 380" stroke="#ffffff" strokeWidth="26" strokeLinecap="round" strokeLinejoin="round" fill="none" />
        <path d="M 460 160 L 460 380 L 290 380" stroke="#f3e7c8" strokeWidth="1.6" fill="none" />
        <text x="475" y="265" fill="#9c8c5e" fontSize="10" fontWeight="800" transform="rotate(90 475 265)" letterSpacing="0.06em">신촌로 26길</text>

        <path d="M 460 310 L 540 310" stroke="#ffffff" strokeWidth="18" strokeLinecap="round" />

        {/* 2호선 라인 */}
        <path d="M 0 110 L 800 110" stroke="#22C55E" strokeWidth="6" opacity="0.32" />
        <path d="M 0 110 L 800 110" stroke="#22C55E" strokeWidth="2" strokeDasharray="6 4" />

        {/* ── 건물 배치 ──
                       西쪽: 우리마포복지관 + 대흥동 주민센터 = 한 건물 (L자, 코너 비워둠)
                       東쪽: 신촌포스빌(위) · 맑은빛 세광교회(아래) ← 주민센터와 맞은편 */}
        <CommunityComplex x={290} y={210} width={160} height={170} />
        <MapBuilding x={490} y={200} width={130} height={62} stories={3} label="신촌포스빌" sublabel="아파트" tone="blue" />
        <ChurchBuilding x={490} y={285} width={130} height={90} />

        {/* NH농협 배지 */}
        <g transform="translate(520, 155)" filter="url(#mapShadow)">
          <rect x="-22" y="-10" width="44" height="20" rx="4" fill="#0066B3" />
          <text x="0" y="4" fill="#fff" fontSize="10" fontWeight="700" textAnchor="middle">NH농협</text>
        </g>

        {/* 이대역 → 교회 유도 점선 제거 (사용자 요청) */}

        {/* 맞은편 화살표 */}
        <g>
          <path d="M452 348 L488 348" stroke="#d97706" strokeWidth="2" fill="none" strokeDasharray="2 4" strokeLinecap="round" />
          <path d="M452 344 L443 348 L452 352 Z" fill="#d97706" />
          <path d="M488 344 L497 348 L488 352 Z" fill="#d97706" />
          <text x="470" y="343" fill="#d97706" fontSize="9" fontWeight="800" textAnchor="middle">맞은편</text>
        </g>

        {/* 신촌역 — 원을 2호선 아래로 내려 논석 가리지 않게 배치 */}
        <g transform="translate(110, 95)">
          <rect x="-44" y="-44" width="88" height="22" rx="4" fill="#3d5d8c" filter="url(#mapShadow)" />
          <text x="0" y="-28" textAnchor="middle" fill="#fff" fontSize="11" fontWeight="800">신촌역 2호선</text>
          <g filter="url(#mapShadow)">
            <circle r="18" fill="#15803D" />
            <circle r="14" fill="#FFFFFF" />
            <circle r="11" fill="#22C55E" />
            <text y="4" textAnchor="middle" fill="#fff" fontSize="11" fontWeight="900">신촌</text>
          </g>
          <g transform="translate(0, 36)" filter="url(#mapShadow)">
            <rect x="-26" y="-8" width="52" height="18" rx="9" fill="#22C55E" stroke="#166534" strokeWidth="1.2" />
            <text x="0" y="5" textAnchor="middle" fill="#fff" fontSize="10" fontWeight="800">5번 출구</text>
          </g>
        </g>

        {/* 이대역 */}
        <g transform="translate(680, 95)">
          <rect x="-44" y="-44" width="88" height="22" rx="4" fill="#3d5d8c" filter="url(#mapShadow)" />
          <text x="0" y="-28" textAnchor="middle" fill="#fff" fontSize="11" fontWeight="800">이대역 2호선</text>
          <g filter="url(#mapShadow)">
            <circle r="18" fill="#15803D" />
            <circle r="14" fill="#FFFFFF" />
            <circle r="11" fill="#22C55E" />
            <text y="4" textAnchor="middle" fill="#fff" fontSize="11" fontWeight="900">이대</text>
          </g>
          <g transform="translate(0, 36)" filter="url(#mapShadow)">
            <rect x="-26" y="-8" width="52" height="18" rx="9" fill="#22C55E" stroke="#166534" strokeWidth="1.2" />
            <text x="0" y="5" textAnchor="middle" fill="#fff" fontSize="10" fontWeight="800">6번 출구</text>
          </g>
        </g>

        {/* 콜아웃 — 교회 건물 아래쪽 위치 */}
        <g transform="translate(555, 405)" filter="url(#mapShadow)">
          <path d="M-6 -19 L6 -19 L0 -28 Z" fill="#3d5d8c" />
          <rect x="-72" y="-19" width="144" height="40" rx="6" fill="#3d5d8c" />
          <text x="0" y="-1" textAnchor="middle" fill="#fff" fontSize="14" fontWeight="800" letterSpacing="-0.01em">세광교회</text>
          <text x="0" y="14" textAnchor="middle" fill="rgba(255,255,255,0.78)" fontSize="10" fontWeight="500">신촌로26길 11</text>
        </g>

        {/* 옛 맞은편 화살표 제거 (위에서 새로 배치됨) */}

        {/* 나침반 */}
        <g transform="translate(48, 460)">
          <circle r="20" fill="#fff" stroke="#d8d0b6" strokeWidth="1.5" filter="url(#mapShadow)" />
          <path d="M0 -12 L4 0 L0 12 L-4 0 Z" fill="#3d5d8c" />
          <path d="M0 -12 L4 0 L-4 0 Z" fill="#c84c4c" />
          <text x="0" y="-14" textAnchor="middle" fill="#c84c4c" fontSize="8" fontWeight="800">N</text>
        </g>

        {/* 스케일 바 */}
        <g transform="translate(720, 470)">
          <rect x="0" y="-2" width="50" height="4" fill="#5b5847" />
          <rect x="0" y="-2" width="25" height="4" fill="#fff" stroke="#5b5847" strokeWidth="0.6" />
          <text x="0" y="-7" fill="#5b5847" fontSize="9" fontWeight="600">0</text>
          <text x="50" y="-7" textAnchor="end" fill="#5b5847" fontSize="9" fontWeight="600">100m</text>
        </g>
      </svg>

      <div style={{
        position: "absolute", top: 14, right: 14,
        display: "inline-flex", alignItems: "center", gap: 6,
        background: "rgba(255,255,255,0.94)", backdropFilter: "blur(6px)",
        border: "1px solid rgba(120,110,90,0.2)",
        borderRadius: 999, padding: "5px 11px",
        fontSize: 11, fontWeight: 700, color: "#5b5847", letterSpacing: "0.04em"
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: "#3d5d8c" }} />
        04105 마포구 신촌로26길 11
      </div>

      <div style={{
        position: "absolute", bottom: 18, left: 96,
        display: "inline-flex", alignItems: "center", gap: 10,
        padding: "10px 16px", background: "var(--ink)", color: "var(--paper)",
        borderRadius: 999, boxShadow: "0 8px 18px -8px rgba(20,30,60,0.4)",
        fontSize: 12, fontWeight: 700
      }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: "#d97706" }} />
        이대역 6번 출구에서 약 250m · 도보 3분
      </div>
    </div>);

}

function KakaoStyleMap() {return <KakaoStyleMapV2 />;}

// (구) function KakaoStyleMap unused below — alias replaced
function _UnusedOldKakaoStyleMap() {
  return (
    <div style={{ position: "absolute", inset: 0, fontFamily: "var(--font-sans)", background: "#fbf8f1" }}>
      <svg viewBox="0 0 900 540" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" style={{ display: "block" }}>
        <defs>
          <filter id="mapShadow" x="-50%" y="-50%" width="200%" height="200%">
            <feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#1a2238" floodOpacity="0.16" />
          </filter>
          <filter id="bldShadow" x="-30%" y="-30%" width="160%" height="160%">
            <feDropShadow dx="0" dy="3" stdDeviation="2.5" floodColor="#1a2238" floodOpacity="0.22" />
          </filter>
          <pattern id="mapDots" width="22" height="22" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="0.9" fill="rgba(108,138,184,0.10)" />
          </pattern>
          <linearGradient id="mapBg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#fbf8f1" />
            <stop offset="100%" stopColor="#f3efe6" />
          </linearGradient>
          {/* 일반 건물 사이드 그라데이션 */}
          <linearGradient id="bldFace" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#fff7e6" />
            <stop offset="100%" stopColor="#f0e6c8" />
          </linearGradient>
          <linearGradient id="bldChurch" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#f0f4fb" />
            <stop offset="100%" stopColor="#c9d6e8" />
          </linearGradient>
        </defs>

        {/* 배경 */}
        <rect width="900" height="540" fill="url(#mapBg)" />
        <rect width="900" height="540" fill="url(#mapDots)" />

        {/* 옅은 녹지 (이화여대 캠퍼스 — 우측 상단) */}
        <path d="M770 25 L880 25 L880 170 L800 170 Z" fill="#e2ead4" stroke="#c6d2b1" strokeWidth="1" />
        <text x="828" y="100" fill="#5b6648" fontSize="12" fontWeight="700" textAnchor="middle">이화여대</text>

        {/* ─── 신촌로 (메인 동서축, 상단) ─── */}
        <path d="M-10 95 L910 95" stroke="#dfd6bc" strokeWidth="56" fill="none" />
        <path d="M-10 95 L910 95" stroke="#ffffff" strokeWidth="50" fill="none" />
        {/* 점선 차선 */}
        <path d="M-10 95 L910 95" stroke="#dfd6bc" strokeWidth="1.5" fill="none" strokeDasharray="12 12" />
        <text x="450" y="92" fill="#9c8c5e" fontSize="12" fontWeight="700" letterSpacing="0.1em" textAnchor="middle">신촌로 Sinchon-ro</text>

        {/* ─── 신촌로26길 (남북, 중앙 → 아래) ─── */}
        <path d="M460 124 L470 510" stroke="#dfd6bc" strokeWidth="28" fill="none" />
        <path d="M460 124 L470 510" stroke="#ffffff" strokeWidth="22" fill="none" />
        <text x="497" y="220" fill="#9c8c5e" fontSize="10" fontWeight="700" transform="rotate(88 497 220)">신촌로 26길</text>

        {/* 보조 도로 */}
        <path d="M-10 250 L450 250" stroke="#dfd6bc" strokeWidth="14" fill="none" />
        <path d="M-10 250 L450 250" stroke="#ffffff" strokeWidth="10" fill="none" />
        <path d="M480 350 L910 350" stroke="#dfd6bc" strokeWidth="14" fill="none" />
        <path d="M480 350 L910 350" stroke="#ffffff" strokeWidth="10" fill="none" />
        <path d="M250 100 L260 540" stroke="#dfd6bc" strokeWidth="14" fill="none" />
        <path d="M250 100 L260 540" stroke="#ffffff" strokeWidth="10" fill="none" />

        {/* ─── 지하철 노선 (신촌로 아래) ─── */}
        {/* 2호선 — 신촌로 따라 동서 (녹색) */}
        <path d="M-10 70 Q 200 68, 460 67 Q 660 66, 910 70"
        stroke="#3ec300" strokeWidth="7" fill="none" strokeLinecap="round" />
        {/* 경의·중앙선 (옅은 청록, 신촌역 아래쪽) */}
        <path d="M-10 165 L260 165" stroke="#71b9a6" strokeWidth="5" fill="none" opacity="0.85" />

        {/* ─── 경로 점선 (이대역에서 출발) ─── */}
        <g>
          <path d="M780 110 L780 95 L470 95 L470 410"
          stroke="#d97a3a" strokeWidth="4" fill="none" strokeDasharray="3 7" strokeLinecap="round" />
          {/* 신촌역 경로 (옅게) */}
          <path d="M130 110 L130 95 L460 95 L460 410"
          stroke="#d97a3a" strokeWidth="3" fill="none" strokeDasharray="3 7" strokeLinecap="round" opacity="0.45" />
        </g>

        {/* ─── 지하철역 마커 (상단) ─── */}
        {/* 이대역 (Line 2) */}
        <g transform="translate(780, 67)" filter="url(#mapShadow)">
          <circle r="17" fill="#fff" stroke="#3ec300" strokeWidth="4.5" />
          <text y="5" textAnchor="middle" fill="#3ec300" fontSize="14" fontWeight="800">2</text>
        </g>
        <g transform="translate(780, 67)">
          <rect x="-50" y="-46" width="100" height="22" rx="4" fill="#3d5d8c" />
          <text x="0" y="-30" textAnchor="middle" fill="#fff" fontSize="12" fontWeight="800">이대역</text>
          <rect x="-44" y="118" width="88" height="20" rx="4" fill="#fff" stroke="#d97a3a" strokeWidth="1.5" />
          <text x="0" y="132" textAnchor="middle" fill="#d97a3a" fontSize="11" fontWeight="800">6번 출구 ↑</text>
        </g>

        {/* 신촌역 (Line 2) */}
        <g transform="translate(130, 67)" filter="url(#mapShadow)">
          <circle r="17" fill="#fff" stroke="#3ec300" strokeWidth="4.5" />
          <text y="5" textAnchor="middle" fill="#3ec300" fontSize="14" fontWeight="800">2</text>
        </g>
        <g transform="translate(130, 67)">
          <rect x="-50" y="-46" width="100" height="22" rx="4" fill="#3d5d8c" />
          <text x="0" y="-30" textAnchor="middle" fill="#fff" fontSize="12" fontWeight="800">신촌역</text>
          <rect x="-44" y="118" width="88" height="20" rx="4" fill="#fff" stroke="#d97a3a" strokeWidth="1.5" />
          <text x="0" y="132" textAnchor="middle" fill="#d97a3a" fontSize="11" fontWeight="800">5번 출구 ↑</text>
        </g>

        {/* 신촌기차역 (경의·중앙선) */}
        <g transform="translate(70, 165)">
          <circle r="13" fill="#fff" stroke="#71b9a6" strokeWidth="3.5" />
          <text y="4" textAnchor="middle" fill="#71b9a6" fontSize="11" fontWeight="800">K</text>
        </g>
        <g transform="translate(70, 165)">
          <rect x="-58" y="22" width="116" height="20" rx="4" fill="#fff" stroke="#d8d0b6" />
          <text x="0" y="36" textAnchor="middle" fill="#5b6648" fontSize="11" fontWeight="700">신촌기차역</text>
        </g>

        {/* ─── 건물 일러스트 ─── */}
        {/* 마포복지관 — 신촌로26길 동쪽, 상단 */}
        <MapBuilding x={580} y={290} width={70} height={68} stories={3} kind="general" label="마포복지관" />

        {/* 대흥동 주민센터 — 신촌로26길 동쪽, 세광교회 맞은편 */}
        <MapBuilding x={580} y={400} width={84} height={80} stories={3} kind="general" label="대흥동 주민센터" pinHighlight={true} />

        {/* 맑은빛 세광교회 (메인 강조) — 대흥동 주민센터 맞은편 (서쪽) */}
        <ChurchBuilding x={310} y={395} width={120} height={130} />

        {/* "맞은편" 안내 화살표 */}
        <g>
          <path d="M442 440 L538 440" stroke="#d97a3a" strokeWidth="2" fill="none" strokeDasharray="2 4" strokeLinecap="round" />
          <path d="M538 436 L548 440 L538 444 Z" fill="#d97a3a" />
          <path d="M442 436 L432 440 L442 444 Z" fill="#d97a3a" />
          <rect x="478" y="430" width="24" height="20" rx="4" fill="#fff" stroke="#d97a3a" />
          <text x="490" y="444" textAnchor="middle" fill="#d97a3a" fontSize="10" fontWeight="800">맞은편</text>
        </g>

        {/* 핀 + 콜아웃 (교회 위) */}
        <g transform="translate(370, 350)" filter="url(#mapShadow)">
          <rect x="-92" y="-25" width="184" height="44" rx="7" fill="#3d5d8c" />
          <path d="M-8 19 L8 19 L0 30 Z" fill="#3d5d8c" />
          <text x="0" y="-6" textAnchor="middle" fill="#ffffff" fontSize="15" fontWeight="800" letterSpacing="-0.01em">맑은빛 세광교회</text>
          <text x="0" y="11" textAnchor="middle" fill="rgba(255,255,255,0.78)" fontSize="10" fontWeight="500">신촌로26길 11 · 5층 건물</text>
        </g>

        {/* ─── 나침반 ─── */}
        <g transform="translate(48, 480)">
          <circle r="22" fill="#ffffff" stroke="#d8d0b6" strokeWidth="1.5" filter="url(#mapShadow)" />
          <path d="M0 -14 L4 0 L0 14 L-4 0 Z" fill="#3d5d8c" />
          <path d="M0 -14 L4 0 L-4 0 Z" fill="#c84c4c" />
          <text x="0" y="-16" textAnchor="middle" fill="#c84c4c" fontSize="9" fontWeight="800">N</text>
        </g>

        {/* ─── 스케일 바 ─── */}
        <g transform="translate(820, 500)">
          <rect x="0" y="-2" width="50" height="4" fill="#5b5847" />
          <rect x="0" y="-2" width="25" height="4" fill="#ffffff" stroke="#5b5847" strokeWidth="0.6" />
          <text x="0" y="-7" fill="#5b5847" fontSize="9" fontWeight="600">0</text>
          <text x="50" y="-7" textAnchor="end" fill="#5b5847" fontSize="9" fontWeight="600">100m</text>
        </g>
      </svg>

      {/* 우상단 주소 칩 */}
      <div style={{
        position: "absolute", top: 14, right: 14,
        display: "inline-flex", alignItems: "center", gap: 6,
        background: "rgba(255,255,255,0.94)",
        backdropFilter: "blur(6px)",
        border: "1px solid rgba(120,110,90,0.2)",
        borderRadius: 999, padding: "5px 11px",
        fontSize: 11, fontWeight: 700, color: "#5b5847", letterSpacing: "0.04em"
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: "#3d5d8c" }} />
        04105 마포구 신촌로26길 11
      </div>

      {/* 좌하단 동선 거리 배지 */}
      <div style={{
        position: "absolute", bottom: 18, left: 96,
        display: "inline-flex", alignItems: "center", gap: 10,
        padding: "10px 16px",
        background: "var(--ink)", color: "var(--paper)",
        borderRadius: 999,
        boxShadow: "0 8px 18px -8px rgba(20,30,60,0.4)",
        fontSize: 12, fontWeight: 700
      }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: "#d97a3a" }} />
        이대역 6번 출구에서 보행 동선 · 약 250m · 도보 3분
      </div>
    </div>);

}

// 일반 건물 일러스트 (마포복지관·대흥동 주민센터 등)
// tone: "beige" (default) | "gray" | "blue"
function MapBuilding({ x, y, width, height, stories = 3, label, sublabel, tone = "beige", pinHighlight = false }) {
  const winRows = stories;
  const winCols = 3;
  const winW = width * 0.18;
  const winH = (height - 14) / winRows * 0.42;
  const winSpaceY = (height - 14) / winRows;
  const palette = {
    beige: { bg: "#f4ecd5", side: "#c2b485", roof: "#a89770", text: "#3c3424", sub: "#7a6f4f", win: "#7a8aa3" },
    gray: { bg: "#edeae3", side: "#cdc7b8", roof: "#a8a395", text: "#4a4842", sub: "#807a6b", win: "#8a8a92" },
    blue: { bg: "#e4ecf6", side: "#b8c4d6", roof: "#8a9aae", text: "#3a4258", sub: "#6e788a", win: "#7a8aa3" }
  };
  const p = palette[tone] || palette.beige;
  return (
    <g transform={`translate(${x}, ${y})`} filter="url(#bldShadow)">
      <rect x="-2" y="-3" width={width + 4} height={height + 5} rx="4" fill={p.side} opacity="0.5" />
      <rect x="0" y="0" width={width} height={height} rx="3" fill={p.bg} stroke={p.side} strokeWidth="1.2" />
      <rect x="-2" y="-4" width={width + 4} height="5" rx="1.5" fill={p.roof} />
      {Array.from({ length: winRows }).map((_, r) =>
      Array.from({ length: winCols }).map((__, c) =>
      <rect key={`${r}-${c}`}
      x={(width - winCols * winW - (winCols - 1) * 6) / 2 + c * (winW + 6)}
      y={9 + r * winSpaceY}
      width={winW} height={winH}
      fill={p.win} opacity={0.45} />
      )
      )}
      <text x={width / 2} y={height / 2 + 4} textAnchor="middle" fill={p.text} fontSize={width > 90 ? 11 : 10} fontWeight="700">{label}</text>
      {sublabel && <text x={width / 2} y={height / 2 + 18} textAnchor="middle" fill={p.sub} fontSize="9">{sublabel}</text>}
    </g>);

}

// 우리마포복지관 + 대흥동 주민센터 결합 건물 (L자, 좌상 코너 비워둠)
function CommunityComplex({ x, y, width, height }) {
  const cornerW = width * 0.50;
  const cornerH = height * 0.42;
  const path = `M ${cornerW} 2 L ${width - 2} 2 L ${width - 2} ${height - 2} L 2 ${height - 2} L 2 ${cornerH} L ${cornerW} ${cornerH} Z`;
  const bg = "#edeae3";
  const stroke = "#cdc7b8";
  const text = "#4a4842";
  const winFill = "#8a8a92";
  return (
    <g transform={`translate(${x}, ${y})`} filter="url(#bldShadow)">
      <path d={path} fill={bg} stroke={stroke} strokeWidth="1.2" />
      <line x1={2} y1={height * 0.58} x2={width - 2} y2={height * 0.58}
      stroke={stroke} strokeWidth="1" strokeDasharray="4 3" opacity="0.7" />
      {[0, 1, 2].map((c) =>
      <rect key={`u-${c}`}
      x={cornerW + 8 + c * ((width - cornerW - 24) / 3)}
      y={cornerH + 8}
      width={(width - cornerW - 24) / 3 - 4}
      height={(height * 0.58 - cornerH - 16) * 0.5}
      fill={winFill} opacity="0.4" rx="0.5" />
      )}
      {[0, 1, 2, 3].map((c) =>
      <rect key={`d-${c}`}
      x={8 + c * ((width - 16) / 4)}
      y={height * 0.62 + 6}
      width={(width - 16) / 4 - 4}
      height={(height - height * 0.62 - 14) * 0.5}
      fill={winFill} opacity="0.4" rx="0.5" />
      )}
      <text x={cornerW + (width - cornerW) / 2} y={cornerH + height * 0.13} textAnchor="middle"
      fill={text} fontSize="11" fontWeight="700">우리마포복지관</text>
      <text x={cornerW + (width - cornerW) / 2} y={cornerH + height * 0.22} textAnchor="middle"
      fill="#807a6b" fontSize="9">공영 주차장</text>
      <text x={width / 2} y={height * 0.80} textAnchor="middle"
      fill={text} fontSize="11" fontWeight="700">대흥동 주민센터</text>
    </g>);

}

// 교회 건물 — 실제 건물 모티프 (노란 본체 + 우측 다크 타워에 흰 십자가)
// 첨부 사진을 토대로 한 평면 일러스트. 그림자/태양광/실내조명 효과는 제외.
function ChurchBuilding({ x, y, width, height }) {
  // 폭을 살짝 좁힘 — 전체에서 양쪽 여백 7%씩
  const inset = width * 0.07;
  const usableW = width - inset * 2;
  const towerW = usableW * 0.30;
  const bodyW = usableW - towerW;
  const baseH = height * 0.16;
  // 색 — 노란 본체를 더 연한 톤(전체 톤앤매너 맞춤, 베이지에 가까운 옅은 노랑)
  const bodyFill = "#fbe8a8"; // 옅은 노랑 (베이지 톤)
  const bodyHi = "#fef0c4"; // 상단 하이라이트
  const towerFill = "#4d4d52"; // 다크 그레이 (덜 강한 검정)
  const towerSide = "#3a3a3e";
  const bodyStroke = "#cdb56a";
  const brick = "#9c5440"; // 적벽돌 톤도 살짝 부드럽게
  const brickDark = "#7a3a2a";
  const window = "#4a5e7a"; // 창문 톤 살짝 옅게
  return (
    <g transform={`translate(${x + inset}, ${y})`}>
      {/* 글로우 */}
      <ellipse cx={usableW / 2} cy={height / 2} rx={usableW * 0.85} ry={height * 0.7} fill="#3d5d8c" opacity="0.07" />

      <g filter="url(#bldShadow)">
        {/* 노란 본체 — 그라데이션 톤 */}
        <rect x="0" y="0" width={bodyW} height={height} rx="2" fill={bodyFill} stroke={bodyStroke} strokeWidth="1.2" />
        {/* 상단 하이라이트 (옅게) */}
        <rect x="0" y="0" width={bodyW} height={height * 0.25} rx="2" fill={bodyHi} opacity="0.55" />
        {/* 본체 창문 슬릿 4개 */}
        {[0.22, 0.38, 0.54, 0.70].map((yPct, i) =>
        <rect key={i}
        x={bodyW * 0.18} y={height * yPct}
        width={bodyW * 0.55} height={height * 0.06}
        fill={window} opacity="0.55" rx="1" />
        )}

        {/* 다크 타워 (우측) */}
        <rect x={bodyW - 1} y={-height * 0.05} width={towerW + 1} height={height + height * 0.05} rx="2"
        fill={towerFill} stroke={towerSide} strokeWidth="1.2" />
        {/* 타워 정면 큰 흰 십자가 */}
        <rect x={bodyW + towerW / 2 - 3} y={height * 0.20} width={6} height={height * 0.50}
        fill="#ffffff" rx="0.5" />
        <rect x={bodyW + towerW / 2 - towerW * 0.32} y={height * 0.38} width={towerW * 0.64} height={6}
        fill="#ffffff" rx="0.5" />

        {/* 1층 벽돌 베이스 */}
        <rect x="0" y={height - baseH} width={bodyW} height={baseH} fill={brick} stroke={brickDark} strokeWidth="0.6" />
        <line x1="0" y1={height - baseH * 0.66} x2={bodyW} y2={height - baseH * 0.66}
        stroke={brickDark} strokeWidth="0.4" opacity="0.5" />
        <line x1="0" y1={height - baseH * 0.33} x2={bodyW} y2={height - baseH * 0.33}
        stroke={brickDark} strokeWidth="0.4" opacity="0.5" />

        {/* 1층 입구 (어두운 유리문) */}
        <rect x={bodyW * 0.42} y={height - baseH * 0.9} width={bodyW * 0.22} height={baseH * 0.85}
        fill={towerFill} stroke={brickDark} strokeWidth="0.6" />
        <line x1={bodyW * 0.53} y1={height - baseH * 0.9} x2={bodyW * 0.53} y2={height - baseH * 0.05}
        stroke="#ffffff" strokeWidth="0.5" opacity="0.6" />
      </g>
    </g>);

}

function ClassicNav() {
  const active = useScrollSpy(NAV_ITEMS.map((i) => i.id));
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 30);
    fn();window.addEventListener("scroll", fn);
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 100,
      background: scrolled ? "color-mix(in oklab, var(--paper) 92%, transparent)" : "transparent",
      backdropFilter: scrolled ? "blur(10px)" : "none",
      borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
      transition: "all .25s ease"
    }}>
      <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 32px" }}>
        <a href="#home" onClick={(e) => {e.preventDefault();scrollToId("home");}} style={{ display: "flex", alignItems: "center", gap: 12, textDecoration: "none" }}>
          {(window.getCopy && window.getCopy("nav.logoImg")) ? <img src={window.getCopy("nav.logoImg")} alt="맑은빛 세광교회" style={{ height: 60, width: "auto", display: "block" }} /> : <LogoLockup variant="blue" height={170} />}
        </a>
        <nav className="desk-nav" style={{ display: "flex", gap: 4, alignItems: "center" }}>
          {NAV_ITEMS.map((item) =>
          <button key={item.id}
          onClick={() => scrollToId(item.id)}
          style={{
            border: item.accent ? "1px solid var(--mint-deep)" : 0,
            background: item.accent ? "var(--mint-soft)" : "transparent",
            padding: item.accent ? "7px 14px" : "8px 14px",
            marginLeft: item.accent ? 8 : 0,
            borderRadius: item.accent ? 999 : 0,
            fontFamily: "var(--font-sans)",
            fontSize: 14, fontWeight: item.accent ? 700 : 500,
            color: item.accent ? "var(--mint-deep)" : active === item.id ? "var(--ink)" : "var(--ink-3)",
            position: "relative",
            display: "inline-flex", alignItems: "center", gap: 6
          }}>
              {item.accent && <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: 999, background: "var(--mint-deep)" }} />}
              {item.label}
              {active === item.id && !item.accent &&
            <span style={{ position: "absolute", left: "50%", bottom: -2, transform: "translateX(-50%)", width: 16, height: 2, background: "var(--primary)", borderRadius: 2 }} />
            }
            </button>
          )}
          <a href="#" onClick={(e) => {e.preventDefault();scrollToId("media");}} className="btn primary" style={{ marginLeft: 12, padding: "9px 16px", fontSize: 13 }}>
            <Icon.youtube size={16} /> 온라인 예배
          </a>
        </nav>
        <button className="mob-toggle" onClick={() => setOpen(!open)} style={{ display: "none", border: 0, background: "transparent", color: "var(--ink)" }}>
          {open ? <Icon.close /> : <Icon.menu />}
        </button>
      </div>
      {open &&
      <div className="mob-panel" style={{ borderTop: "1px solid var(--line)", padding: "12px 20px", background: "var(--card)" }}>
          {NAV_ITEMS.map((item) =>
        <button key={item.id} onClick={() => {scrollToId(item.id);setOpen(false);}} style={{ display: "block", width: "100%", textAlign: "left", padding: "12px 6px", border: 0, background: "transparent", fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--ink)" }}>
              {item.label}
            </button>
        )}
        </div>
      }
      <style>{`
        @media (max-width: 880px) {
          .desk-nav { display: none !important; }
          .mob-toggle { display: inline-flex !important; }
        }
      `}</style>
    </header>);

}

// ─── 히어로 LIVE 카드 아래 보조 카드 (Tweaks → heroExtra) ───
function HeroExtraCard({ kind, tw }) {
  if (kind === "none") return null;

  const cardBase = {
    background: "var(--card)",
    border: "1px solid var(--line)",
    borderRadius: 10,
    boxShadow: "0 20px 40px -20px rgba(20,30,60,0.18)",
    overflow: "hidden",
  };

  if (kind === "sermon") {
    return (
      <div className="hero-extra-card sermon" style={{ ...cardBase, padding: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--primary)" }} />
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.16em", color: "var(--primary)", textTransform: "uppercase" }}>이번 주 설교</span>
          <span style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>{tw.date.replace(/\.$/, "")}</span>
        </div>
        <div style={{
          fontFamily: "var(--font-display)",
          fontSize: 18, fontWeight: 500, lineHeight: 1.35,
          color: "var(--ink)",
          letterSpacing: "-0.01em",
        }}>
          ‘{tw.sermonTitle}’
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 6, fontStyle: "italic", fontFamily: "var(--font-display)", paddingLeft: "0.7em" }}>
          {tw.sermonTitleEn}
        </div>
        <div style={{
          marginTop: 10, paddingTop: 10,
          borderTop: "1px dashed var(--line-2)",
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontSize: 11, color: "var(--ink-3)",
        }}>
          <span>{tw.scripture}</span>
          <span style={{ color: "var(--ink-2)", fontWeight: 600 }}>{tw.preacher}</span>
        </div>
      </div>
    );
  }

  if (kind === "verse") {
    return (
      <div className="hero-extra-card verse" style={{
        ...cardBase,
        padding: 18,
        background: "linear-gradient(135deg, var(--paper-2) 0%, var(--card) 100%)",
        borderColor: "var(--mint-soft)",
      }}>
        <div style={{
          fontFamily: "var(--font-display)", fontSize: 36, fontWeight: 400,
          color: "var(--mint-deep)", lineHeight: 0.6, marginBottom: 6,
        }}>“</div>
        <div style={{
          fontFamily: "var(--font-display)",
          fontSize: 14.5, lineHeight: 1.65, fontWeight: 500,
          color: "var(--ink)",
          letterSpacing: "-0.01em",
        }}>
          오직 성령이 너희에게 임하시면, 너희가 권능을 받고…
        </div>
        <div style={{
          marginTop: 12, fontSize: 11, color: "var(--ink-3)",
          fontFamily: "var(--font-sans)",
          letterSpacing: "0.04em",
        }}>
          — 사도행전 1:8
        </div>
      </div>
    );
  }

  if (kind === "schedule") {
    const items = [
      { day: "주일", time: "9:30 · 11:00", label: "온세대예배" },
      { day: "수요", time: "10:30am",      label: "수요낮예배" },
      { day: "매일", time: "5:30am",       label: "온마음 아침예배" },
    ];
    return (
      <div className="hero-extra-card schedule" style={{ ...cardBase, padding: "14px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.16em", color: "var(--mint-deep)", textTransform: "uppercase" }}>이번 주 예배</span>
          <span style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>그레이스홀 B1</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {items.map((it, i) =>
            <div key={i} style={{
              display: "grid", gridTemplateColumns: "32px 1fr auto",
              alignItems: "baseline", gap: 8,
              paddingBottom: i < items.length - 1 ? 8 : 0,
              borderBottom: i < items.length - 1 ? "1px dashed var(--line-2)" : "none",
            }}>
              <div style={{
                fontSize: 10, fontWeight: 700, color: "var(--primary)",
                letterSpacing: "0.05em",
              }}>{it.day}</div>
              <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.3 }}>{it.label}</div>
              <div style={{
                fontFamily: "var(--font-sans)",
                fontSize: 11, color: "var(--ink-3)", fontWeight: 600, fontVariantNumeric: "tabular-nums",
                whiteSpace: "nowrap",
              }}>{it.time}</div>
            </div>
          )}
        </div>
      </div>
    );
  }

  return null;
}

function ClassicHero({ heroExtra = "sermon", isLive = null }) {
  const c = window.CHURCH;
  const tw = c.thisWeek;

  // 주간 예배 스케줄 — 시작 시간 기준 (끝 시간 없음, YouTube API가 종료 감지)
  const HERO_SERVICES = [
    { day: 0, start: 11*60,    name: "주일 2부 예배", time: "11:00am" },
    { day: 1, start: 5*60+30,  name: "아침예배",      time: "05:30am" },
    { day: 2, start: 5*60+30,  name: "아침예배",      time: "05:30am" },
    { day: 3, start: 5*60+30,  name: "아침예배",      time: "05:30am" },
    { day: 3, start: 10*60+30, name: "수요예배",       time: "10:30am" },
    { day: 4, start: 5*60+30,  name: "아침예배",      time: "05:30am" },
    { day: 5, start: 5*60+30,  name: "아침예배",      time: "05:30am" },
  ];
  // 현재 시간 기준으로 예배 이름 판별 (YouTube API가 live라고 할 때 이름 표시용)
  const getCurrentServiceName = () => {
    const now = new Date();
    const day = now.getDay();
    const hm = now.getHours() * 60 + now.getMinutes();
    const candidates = HERO_SERVICES
      .filter(s => s.day === day && hm >= s.start && hm < s.start + 3*60)
      .sort((a, b) => b.start - a.start);
    return candidates[0] || null;
  };
  // 다음 예배 계산
  const getNextService = () => {
    const now = new Date();
    const today = now.getDay();
    const nowHM = now.getHours() * 60 + now.getMinutes();
    for (let d = 0; d <= 7; d++) {
      const targetDay = (today + d) % 7;
      const dayServices = HERO_SERVICES
        .filter(s => s.day === targetDay)
        .sort((a, b) => a.start - b.start);
      for (const svc of dayServices) {
        if (d === 0 && nowHM >= svc.start) continue;
        return svc;
      }
    }
    return HERO_SERVICES[0];
  };
  const [nextService, setNextService] = React.useState(getNextService);
  React.useEffect(() => {
    const t = setInterval(() => setNextService(getNextService()), 60000);
    return () => clearInterval(t);
  }, []);
  const liveServiceInfo = isLive ? getCurrentServiceName() : null;

  return (
    <section id="home" style={{ position: "relative", paddingTop: 24, paddingBottom: 80, overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, pointerEvents: "none", color: "var(--primary)" }}>
        <CrossPattern color="var(--primary)" opacity={0.04} />
      </div>
      <div className="container" style={{ position: "relative", display: "grid", gridTemplateColumns: "minmax(0,1.1fr) minmax(0,0.9fr)", gap: 64, alignItems: "stretch" }}>
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>
            {window.getCopy ? window.getCopy("hero.eyebrow") : "SE 2026 · Revival in the Spirit"}
          </div>
          <h1 style={{
            fontSize: "clamp(40px, 6vw, 76px)",
            lineHeight: 1.05, margin: 0, fontWeight: 500,
            letterSpacing: "-0.02em"
          }}>
            {window.getCopy ? window.getCopy("hero.theme.line1") : "성령으로"}<br />
            <span style={{ color: "var(--primary)" }}>{window.getCopy ? window.getCopy("hero.theme.line2") : "부흥하라."}</span>
          </h1>
                    <p style={{ marginTop: 24, fontSize: 17, color: "var(--ink-2)", maxWidth: 460, whiteSpace: "pre-line" }}>
            {window.getCopy ? window.getCopy("hero.intro") : "1962년 마포에서 시작된 한국기독교장로회 맑은빛 세광교회는,\n\"주를 알고, 주를 알리며, 주와 함께하는 교회\"라는 사명을 따라\n오늘도 한 자리에서 예배합니다."}
          </p>
          <div style={{ display: "flex", gap: 12, marginTop: 32, flexWrap: "wrap" }}>
            <button onClick={() => scrollToId("visit")} className="btn primary">
              주일 예배 함께하기 <Icon.arrow size={14} />
            </button>
            <button onClick={() => scrollToId("media")} className="btn ghost">
              <Icon.youtube size={16} /> 온라인 예배 보기
            </button>
          </div>

          <div style={{ marginTop: 56, display: "flex", gap: 32, flexWrap: "wrap", fontFamily: "var(--font-sans)" }}>
            <div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.16em", textTransform: "uppercase" }}>창립</div>
              <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>{c.founded}</div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.16em", textTransform: "uppercase" }}>주일예배</div>
              <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>9:30 · 11:00</div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.16em", textTransform: "uppercase" }}>위치</div>
              <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>서울시 마포구 신촌로</div>
            </div>
          </div>
        </div>

        <div style={{ position: "relative" }}>
          {/* 메인 사진 — 교회 외관 실제 사진 (JPEG 압축본, srcset 반응형) */}
          <picture>
            <source media="(min-width: 1280px)" srcSet="assets/church-exterior-1800.jpg" />
            <source media="(min-width: 720px)" srcSet="assets/church-exterior-1400.jpg" />
            <img
              src="assets/church-exterior-900.jpg"
              srcSet="assets/church-exterior-900.jpg 900w, assets/church-exterior-1400.jpg 1400w, assets/church-exterior-1800.jpg 1800w"
              sizes="(min-width: 1280px) 520px, (min-width: 720px) 40vw, 100vw"
              alt="맑은빛 세광교회 외관"
              loading="lazy"
              decoding="async"
              style={{
                width: "100%", aspectRatio: "3/4",
                objectFit: "cover", borderRadius: 12,
                boxShadow: "0 30px 60px -30px rgba(20,30,60,0.4)",
                display: "block"
              }} />
          </picture>
          
          {/* 떠있는 카드 스택 — LIVE 카드 + 보조 카드 (heroExtra) */}
          <div className="classic-card-stack" style={{
            position: "absolute", left: -212, top: heroExtra === "none" ? "62%" : "38%",
            width: 240,
            display: "flex", flexDirection: "column", gap: 14,
            zIndex: 2,
            fontFamily: "var(--font-sans)",
          }}>
            <div className="classic-live-card" style={{
              background: "var(--card)",
              border: isLive ? "1px solid rgba(204,43,43,0.25)" : "1px solid var(--line)",
              padding: 16, borderRadius: 10,
              boxShadow: "0 20px 40px -20px rgba(20,30,60,0.18)",
              transition: "border-color 0.4s",
            }}>
              {isLive ? (
                <React.Fragment>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                    <span className="hero-live-pulse" style={{ width: 8, height: 8, borderRadius: 999, background: "#cc2b2b", flexShrink: 0, display: "inline-block" }} />
                    <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", color: "#cc2b2b" }}>LIVE</span>
                    <span style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>유튜브</span>
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4, color: "var(--ink)" }}>
                    {liveServiceInfo ? liveServiceInfo.name : "예배 진행 중"}
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
                    그레이스홀 · {liveServiceInfo ? liveServiceInfo.time : ""}
                  </div>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--ink-3)", flexShrink: 0, display: "inline-block" }} />
                    <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", color: "var(--ink-3)" }}>다음 예배</span>
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4, color: "var(--ink)" }}>
                    {nextService ? nextService.name : "주일 2부 예배"}
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
                    그레이스홀 · {nextService ? nextService.time : "11:00am"}
                  </div>
                </React.Fragment>
              )}
            </div>

            <HeroExtraCard kind={heroExtra} tw={tw} />
          </div>
        </div>
      </div>
      <style>{`
        @keyframes hero-live-blink {
          0%, 100% { opacity: 1; box-shadow: 0 0 0 0 rgba(204,43,43,0.55); }
          50% { opacity: 0.35; box-shadow: 0 0 0 5px rgba(204,43,43,0); }
        }
        .hero-live-pulse { animation: hero-live-blink 1.3s ease-in-out infinite; }
        @media (max-width: 880px) {
          #home > .container { grid-template-columns: 1fr !important; gap: 40px !important; }
          /* 카드 스택: 데스크탑 좌측 오버랩 → 모바일 사진 아래로 풀로 빠짐 */
          .classic-card-stack {
            position: static !important;
            left: auto !important;
            top: auto !important;
            width: 100% !important;
            margin-top: 16px;
          }
        }
      `}</style>
    </section>);

}

function ClassicMission() {
  const c = window.CHURCH;
  return (
    <section className="mission-section" style={{ background: "var(--paper-2)", padding: "80px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
      <div className="container" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "center" }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Our Mission</div>
                    <h2 style={{ fontSize: "clamp(28px, 3.4vw, 40px)", fontWeight: 500, lineHeight: 1.25, margin: 0, whiteSpace: "pre-line" }}>
            {window.getCopy ? window.getCopy("mission.headline") : "주를 알고,\n주를 알리며,\n주와 함께하는 교회"}
          </h2>
                    <p style={{ marginTop: 18, fontFamily: "var(--font-sans)", color: "var(--ink-3)", fontStyle: "italic" }}>
            {window.getCopy ? window.getCopy("mission.en") : "To know HIM, to make HIM known, to live with HIM."}
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          {(function(){
            const gc = window.getCopy;
            return [
              { t: gc?gc("mission.card1.t"):"주를 알고",   en: gc?gc("mission.card1.en"):"Know",       body: gc?gc("mission.card1.body"):"말씀과 예배로 하나님을 알아가는 일에 집중합니다." },
              { t: gc?gc("mission.card2.t"):"주를 알리며", en: gc?gc("mission.card2.en"):"Make Known",  body: gc?gc("mission.card2.body"):"일상의 자리에서 복음을 살아내고 전합니다." },
              { t: gc?gc("mission.card3.t"):"주와 함께",   en: gc?gc("mission.card3.en"):"Live With",   body: gc?gc("mission.card3.body"):"성령의 임재 안에 매일을 살아갑니다." },
              { t: gc?gc("mission.card4.t"):"공동체",      en: gc?gc("mission.card4.en"):"Together",    body: gc?gc("mission.card4.body"):"온 세대가 한자리에서 예배하는 교회입니다." },
            ];
          })().map((x, i) =>
          <div key={i} style={{ background: "var(--card)", border: "1px solid var(--line)", padding: 22, borderRadius: 8 }}>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "var(--mint-deep)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 10 }}>{x.en}</div>
              <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>{x.t}</div>
              <div style={{ fontSize: 13, color: "var(--ink-3)", lineHeight: 1.6 }}>{x.body}</div>
            </div>
          )}
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          section[style*="paper-2"] > .container { grid-template-columns: 1fr !important; gap: 40px !important; }
          /* 연혁 그리드: 모바일 2열 고정 */
          .history-grid { grid-template-columns: 1fr 1fr !important; }
          .history-grid > div { padding: 14px 14px !important; }
          /* FUTURE AND BEYOND: 모바일에서 2열 전체 span */
          .future-beyond-cell { grid-column: 1 / -1 !important; padding: 14px 14px !important; }
          /* ===== 전체 섹션 모바일 패딩 축소 (A안: 40px 균일) ===== */
          #home { padding-bottom: 40px !important; }
          .mission-section { padding: 40px 0 !important; }
          #about { padding-top: 40px !important; padding-bottom: 40px !important; }
          #worship { padding-top: 40px !important; padding-bottom: 40px !important; }
          #thisweek { padding: 40px 0 !important; }
          #media { padding: 40px 0 !important; }
          #bulletin-viewer { padding: 40px 0 !important; }
          #prayer { padding: 40px 0 !important; }
          #visit { padding: 40px 0 !important; }
          #gallery { padding: 40px 0 !important; }
          #gallery div[style*="28px"] { padding-left: 0 !important; }
          /* 예배 카드 + 세대별 공동체: 모바일 2열 고정 */
          .worship-grid { grid-template-columns: 1fr 1fr !important; gap: 10px !important; }
          .community-grid { grid-template-columns: 1fr 1fr !important; gap: 10px !important; }
        }
      `}</style>
    </section>);

}

function ClassicAbout() {
  const c = window.CHURCH;
  const [historyData, setHistoryData] = React.useState(() => (window.CHURCH && window.CHURCH.history) || []);
  React.useEffect(() => {
    const onUpdated = () => {
      if (window.CHURCH && window.CHURCH.history) setHistoryData([...window.CHURCH.history]);
    };
    window.addEventListener('hlc-history-updated', onUpdated);
    return () => window.removeEventListener('hlc-history-updated', onUpdated);
  }, []);
  const HISTORY_COLS = 6;
  const _futureCol = historyData.length % HISTORY_COLS === 0 ? 1 : historyData.length % HISTORY_COLS + 1;
  return (
    <section id="about" style={{ padding: "100px 0" }}>
      <div className="container">
        <SectionTitle eyebrow="About · 교회 소개" title="" en={window.getCopy ? window.getCopy("about.en") : "Faithfully serving this neighborhood since 1962"} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 56, alignItems: "stretch" }}>
          <div className="classic-about-leftcol" style={{ display: "flex", flexDirection: "column", maxWidth: 280 }}>
            {/* 담임목사 정보 — 사진 위 */}
            <div style={{ marginBottom: 0 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>담임목사</div>
              <h3 style={{ fontSize: 22, fontWeight: 500, margin: "0 0 0" }}>
                {c.pastor.name} <span style={{ color: "var(--ink-3)", fontSize: 15 }}>{c.pastor.title}</span>
              </h3>

            </div>
            {/* 담임목사 사진 — 배경 투명 PNG, 사이즈 축소, 담임목사 시무 아래 작은 간격 */}
            <div style={{
              marginTop: 0,
              width: "100%",
              maxWidth: 170,
              aspectRatio: "245/311",
            }}>
              <img
                src={(window.getCopy && window.getCopy("about.pastorImg")) || "assets/pastor-park.png"}
                alt="박병규 담임목사"
                loading="lazy"
                decoding="async"
                style={{
                  display: "block",
                  width: "100%", height: "100%",
                  objectFit: "contain", objectPosition: "center top",
                }}
              />
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-start" }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>{window.getCopy ? window.getCopy("about.rightEyebrow") : "맑은빛세광교회는"}</div>
            <h3 style={{ fontSize: 26, fontWeight: 500, margin: "0 0 22px", lineHeight: 1.35, fontFamily: "var(--font-display)" }}>
              {window.getCopy ? (<>
                <span className="about-hl-pc">{window.getCopy("about.headline").split("\n").reduce((a,l,i)=>[...a,i?<br key={i}/>:null,l],[])}</span>
                <span className="about-hl-mobile">{(window.getCopy("about.headlineMobile")||window.getCopy("about.headline")).split("\n").reduce((a,l,i)=>[...a,i?<br key={i}/>:null,l],[])}</span>
              </>) : <React.Fragment><span className="about-hl-pc">세상의 어둠을 복음의 빛으로 밝히고,<br />세상의 아픔을 치유의 빛으로 맑힙니다.</span><span className="about-hl-mobile">세상의 어둠을 복음의 빛으로<br />밝히고,<br />세상의 아픔을 치유의 빛으로<br />맑힙니다.</span></React.Fragment>}
            </h3>
            <div style={{ fontSize: 16, lineHeight: 1.85, color: "var(--ink-2)" }}>
              <p style={{ margin: "0 0 14px" }}>
                {window.getCopy ? window.getCopy("about.body1") : <React.Fragment>맑은빛 세광교회는 <strong style={{ color: "var(--ink)", fontWeight: 600 }}>세상을 밝히는 복음의 빛</strong>, 세상을 치유하여 맑히는 <strong style={{ color: "var(--ink)", fontWeight: 600 }}>성령의 빛</strong>을 가득 품은 교회입니다. 예수 그리스도를 구주로 고백하며, 복음적 메시지로 은혜로운 예배를 중심에 두는 <strong style={{ color: "var(--primary)", fontWeight: 600 }}>복음적 교회</strong>입니다.</React.Fragment>}
              </p>
              <p style={{ margin: "0 0 14px" }}>
                {window.getCopy ? window.getCopy("about.body2") : <React.Fragment>지역 구청과 협업하여 독거 어르신들을 위한 효도밥상을 운영하며 이웃을 섬기는 <strong style={{ color: "var(--primary)", fontWeight: 600 }}>선교적 교회</strong>입니다.</React.Fragment>}
              </p>
              <p style={{ margin: "0 0 14px" }}>
                {window.getCopy ? window.getCopy("about.body3") : <React.Fragment>어른부터 아이들까지 모두 함께 모여 예배하는 <strong style={{ color: "var(--primary)", fontWeight: 600 }}>온세대 예배 공동체</strong>를 추구합니다. 동네 이웃과 협력하고, 지역 아동을 위한 공부방으로 개방하고, 온세대가 다음 시대를 향해 함께 나아가는 신나는 교회입니다.</React.Fragment>}
              </p>
              <p style={{ margin: "18px 0 0", fontFamily: "var(--font-display)", fontSize: 17, color: "var(--mint-deep)", fontStyle: "italic" }}>
                {window.getCopy ? window.getCopy("about.tagline") : "당신 곁에, 신촌 맑은빛세광교회입니다."}
              </p>
              <div style={{ marginTop: 22, fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--ink-3)" }}>
                {window.getCopy ? window.getCopy("about.signature") : "— 신촌 맑은빛세광교회에서 박병규 목사 드림"}
              </div>
            </div>
          </div>
        </div>

        {/* 연혁 */}
        <div style={{ marginTop: 100 }}>
          <SectionTitle eyebrow="History · 교회 연혁" title="우리가 걸어온 길" align="left" />
          <div className="history-grid" style={{
            display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
            gap: 0, borderTop: "1px solid var(--line)"
          }}>
            {historyData.map((h, i) =>
            <div key={i} style={{
              borderRight: "1px solid var(--line)",
              borderBottom: "1px solid var(--line)",
              padding: "24px 22px",
              background: i % 2 === 0 ? "var(--paper)" : "var(--paper-2)"
            }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.14em", fontWeight: 600 }}>{h.year}</div>
                <div style={{ fontSize: 16, fontWeight: 600, marginTop: 10, color: "var(--primary)" }}>{h.label}</div>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 8, lineHeight: 1.6 }}>{h.text}</div>
              </div>
            )}
            {/* FUTURE AND BEYOND — 3열~끝까지, 모바일은 1칸 */}
            <div className="future-beyond-cell" style={{ '--future-col': _futureCol, padding: "24px 22px" }}>
              {/* 연도 라벨 높이 맞춤용 투명 스페이서 */}
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "transparent", letterSpacing: "0.14em", fontWeight: 600 }}>0000</div>
              {/* 텍스트 — 지역선교보다 약간 작게 */}
              <div className="future-beyond-text" style={{ fontSize: 13, fontWeight: 600, marginTop: 10, color: "var(--primary)", whiteSpace: "nowrap", letterSpacing: "0.04em" }}>
                FUTURE AND BEYOND
              </div>
              {/* 애니메이션 점선 — 행 끝까지 가득 (미래로 이어지는 의미) */}
              <div className="future-beyond-dots" style={{
                position: "relative", height: 40, marginTop: 12,
                maskImage: "linear-gradient(to right, rgba(0,0,0,1) 0%, rgba(0,0,0,0.75) 40%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0) 100%)",
                WebkitMaskImage: "linear-gradient(to right, rgba(0,0,0,1) 0%, rgba(0,0,0,0.75) 40%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0) 100%)"
              }}>
                {/* 글로우 레이어 */}
                <div style={{position:"absolute",inset:0,filter:"blur(3.5px)",opacity:0.35}}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="40" style={{display:"block",overflow:"hidden"}}>
                    <line x1="0" y1="20" x2="2000" y2="20" stroke="#5387ca" strokeWidth="11" strokeLinecap="round" strokeDasharray="1 19">
                      <animate attributeName="stroke-dashoffset" values="0; -20" dur="1.5s" repeatCount="indefinite" calcMode="linear"/>
                    </line>
                  </svg>
                </div>
                {/* 선명한 중심 레이어 */}
                <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="40" style={{display:"block",overflow:"hidden",position:"relative"}}>
                  <line x1="0" y1="20" x2="2000" y2="20" stroke="#5387ca" strokeWidth="6" strokeLinecap="round" strokeDasharray="1 19">
                    <animate attributeName="stroke-dashoffset" values="0; -20" dur="1.5s" repeatCount="indefinite" calcMode="linear"/>
                  </line>
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        /* 데스크탑: FUTURE AND BEYOND 셀이 3열~끝까지 차지 */
        @media (min-width: 881px) {
          .future-beyond-cell { grid-column: var(--future-col, 4) / -1 !important; }
        }
        .about-hl-mobile { display: none; }
        @media (max-width: 880px) {
          #about > .container > div:nth-of-type(1) { grid-template-columns: 1fr !important; gap: 32px !important; }
          /* 담임목사 컬럼: 모바일에서 좌우 자동 마진으로 중앙 정렬 */
          .classic-about-leftcol { margin-left: auto !important; margin-right: auto !important; }
          /* headline 모바일 전환 */
          .about-hl-pc { display: none !important; }
          .about-hl-mobile { display: block !important; }
          /* 연혁 그리드: 행 단위 배경 교대 (2열 기준 4n 패턴) */
          .history-grid > div:nth-child(4n+1),
          .history-grid > div:nth-child(4n+2) { background: var(--paper) !important; }
          .history-grid > div:nth-child(4n+3),
          .history-grid > div:nth-child(4n+4) { background: var(--paper-2) !important; }
          /* FUTURE AND BEYOND: span 해제 → 한 칸에 맞게 */
          .future-beyond-cell { grid-column: auto !important; }
          /* 텍스트 축소 + 줄바꿈 허용 */
          .future-beyond-text { font-size: 12px !important; letter-spacing: 0.06em !important; white-space: normal !important; line-height: 1.3 !important; }
          /* 점선 여백 축소 */
          .future-beyond-dots { margin-top: 6px !important; height: 28px !important; }
        }
      `}</style>
    </section>);

}

function ClassicWorship() {
  const c = window.CHURCH;
  return (
    <section id="worship" style={{ padding: "100px 0", background: "var(--paper-2)" }}>
      <div className="container">
        <SectionTitle eyebrow="Worship · 예배" title={<React.Fragment>이번 주에도 함께<br className="br-mobile"/> 예배합니다</React.Fragment>} en="Weekly Worship Services" />
        <div className="worship-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
          {(function(){
              const gc = window.getCopy;
              let svcs = c.services;
              try { if(gc && gc("worship.services")) svcs = JSON.parse(gc("worship.services")); } catch(e){}
              return svcs;
            })().map((s, i) =>
          <div key={i} style={{
            background: "var(--card)",
            border: "1px solid var(--line)",
            borderLeft: `3px solid ${s.dot === "mint" ? "var(--mint)" : "var(--primary)"}`,
            padding: "20px 22px", borderRadius: 6
          }}>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: s.dot === "mint" ? "var(--mint-deep)" : "var(--primary)", letterSpacing: "0.14em", fontWeight: 600, textTransform: "uppercase", marginBottom: 8 }}>
                {s.dot === "mint" ? "교회학교·청년" : "온세대 예배"}
              </div>
              <div style={{ fontSize: 17, fontWeight: 600 }}>{s.name}</div>
              <div style={{ marginTop: 14, fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 8 }}>
                <Icon.clock size={14} /> {s.time}
              </div>
              <div style={{ marginTop: 4, fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 8 }}>
                <Icon.pin size={14} /> {s.place}
              </div>
            </div>
          )}
        </div>

        {/* 부서 / 공동체 */}
        <div style={{ marginTop: 60 }}>
          <h3 style={{ fontSize: 22, fontWeight: 500, margin: "0 0 20px" }}>{window.getCopy ? window.getCopy("worship.community.title") : "세대별 공동체"}</h3>
          <div className="community-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
            {(function(){
                const gc = window.getCopy;
                let coms = c.communities;
                try { if(gc && gc("worship.communities")) coms = JSON.parse(gc("worship.communities")); } catch(e){}
                return coms;
              })().map((co, i) =>
            <div key={i} style={{ background: "var(--card)", border: "1px solid var(--line)", padding: 18, borderRadius: 6, display: "flex", alignItems: "flex-start", gap: 14 }}>
                <div style={{ width: 6, height: 40, background: i < 4 ? "var(--mint)" : "var(--primary)", borderRadius: 3, flexShrink: 0 }} />
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600 }}>{co.name}</div>
                  <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{co.desc}</div>
                  <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "var(--mint-deep)", marginTop: 6, fontWeight: 600 }}>{co.age}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

function ClassicThisWeek({ isLive = null, weeklyVer = 0 }) {
  const c = window.CHURCH;
  const [localVer, setLocalVer] = React.useState(0);
  React.useEffect(() => {
    const handler = () => setLocalVer(v => v + 1);
    window.addEventListener('hlc-weekly-updated', handler);
    return () => window.removeEventListener('hlc-weekly-updated', handler);
  }, []);
  // window.CHURCH.thisWeek.scriptureText 폴링 — app.jsx가 채워주면 즉시 반영
  const [scriptureText, setScriptureText] = React.useState(c.thisWeek.scriptureText || '');
  const [scriptureExpanded, setScriptureExpanded] = React.useState(false);
  React.useEffect(() => {
    if (c.thisWeek.scriptureText) { setScriptureText(c.thisWeek.scriptureText); return; }
    let attempts = 0;
    const timer = setInterval(() => {
      attempts++;
      const st = c.thisWeek.scriptureText;
      if (st) { setScriptureText(st); clearInterval(timer); return; }
      if (attempts >= 24) clearInterval(timer); // 12초 후 중단
    }, 500);
    return () => clearInterval(timer);
  }, []);
  const tw = { ...c.thisWeek, scriptureText };
  return (
    <section id="thisweek" style={{ padding: "100px 0" }}>
      <div className="container">
        <SectionTitle eyebrow="This Week · 이번 주" title="이번 주 예배와 소식" en={tw.date + " · " + tw.season} />
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 40 }}>
          {/* 설교 카드 */}
          <article style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 10, padding: 36, position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", top: 24, right: 24, opacity: 0.08, color: "var(--primary)" }}>
              <LogoMark color="var(--primary)" size={120} />
            </div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>이번 주 설교</div>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--ink-3)", marginBottom: 18 }}>
              {tw.scripture} · {tw.preacher}
            </div>
            <h3 className="sermon-title" style={{ fontSize: 38, fontWeight: 500, margin: 0, lineHeight: 1.15 }}>‘{tw.sermonTitle}’</h3>
            <div className="sermon-title-en" style={{ fontFamily: "var(--font-sans)", fontStyle: "italic", color: "var(--ink-3)", marginTop: 8, paddingLeft: "0.55em" }}>{tw.sermonTitleEn}</div>
            {(tw.scriptureText || tw.scripture) && (
            <div style={{ marginTop: 36, padding: 20, background: "var(--paper-2)", borderRadius: 8, fontSize: 14.5, lineHeight: 1.85, position: "relative" }}>
              <div style={{
                position: "absolute", top: -10, left: 16,
                background: "var(--mint-deep)", color: "white",
                fontSize: 10, fontWeight: 700, letterSpacing: "0.08em",
                padding: "3px 10px", borderRadius: 999,
                fontFamily: "var(--font-sans)"
              }}>새번역</div>
              {tw.scriptureText
                ? <div className="scripture-wrap">
                    <div
                      className="scripture-body"
                      style={{ whiteSpace: "pre-wrap", paddingTop: 4 }}
                      data-expanded={scriptureExpanded ? "1" : "0"}
                      dangerouslySetInnerHTML={{ __html: tw.scriptureText }}
                    />
                    <div className={"scripture-fade" + (scriptureExpanded ? " hidden" : "")} />
                    <button
                      className="scripture-toggle"
                      onClick={() => setScriptureExpanded(v => !v)}
                    >
                      {scriptureExpanded ? "접기 ▲" : "펼치기 ▼"}
                    </button>
                  </div>
                : <div style={{ fontSize: 13, color: "var(--ink-3)", fontStyle: "italic", paddingTop: 4 }}>{tw.scripture} 본문은 관리자 → 주보 업로드 후 자동 적용됩니다.</div>
              }
            </div>
            )}
            <div style={{ marginTop: 24, display: "flex", gap: 12 }}>
              <BulletinViewButton />
            </div>
          </article>

          {/* 옆 칼럼 */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16, height: "100%" }}>
            <YouTubeCard title="주일 2부 예배 다시보기" subtitle={tw.date} live={false} mode="sunday" playable={true}
              liveStatus={null} sermonTitle={tw.sermonTitle} scripture={tw.scripture} />
            <div className="notices-card" style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 10, padding: 22, flex: 1 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>주요 소식</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                {tw.notices.map((n, i) =>
                <div key={i} style={{ display: "flex", gap: 12, paddingBottom: 4, borderBottom: i < tw.notices.length - 1 ? "1px solid var(--line)" : "none" }}>
                    <span className="pill" style={{ flexShrink: 0, alignSelf: "flex-start" }}>
                      <span className="dot" />{n.tag}
                    </span>
                    <div>
                      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 14 }}>{n.title}</div>
                      <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5 }}>{n.body}</div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          #thisweek > .container > div { grid-template-columns: 1fr !important; }
          .sermon-title { font-size: 24px !important; line-height: 1.25 !important; }
          .sermon-title-en { font-size: 13px !important; }
          .notices-card { padding: 14px 14px 10px !important; }
          .notices-card .eyebrow { margin-bottom: 8px !important; }
          /* 본문말씀 펼치기/접기 + 애니메이션 */
          .scripture-body {
            transition: max-height 0.4s ease !important;
            overflow: hidden !important;
          }
          .scripture-body[data-expanded="0"] {
            max-height: 135px !important;
            white-space: normal !important;
          }
          .scripture-body[data-expanded="1"] {
            max-height: 2000px !important;
          }
          /* 접힌 상태 하단 그라데이션 페이드 */
          .scripture-wrap { position: relative; }
          .scripture-fade {
            position: absolute;
            bottom: 0; left: 0; right: 0;
            height: 40px;
            background: linear-gradient(transparent, var(--paper-2));
            pointer-events: none;
            transition: opacity 0.3s ease;
          }
          .scripture-fade.hidden { opacity: 0; }
          .scripture-toggle {
            display: block;
            margin-top: 8px;
            background: none;
            border: none;
            color: var(--mint-deep);
            font-size: 12px;
            font-weight: 700;
            font-family: var(--font-sans);
            cursor: pointer;
            padding: 2px 0;
            letter-spacing: 0.04em;
            transition: color 0.2s;
          }
          .scripture-toggle:active { opacity: 0.7; }
        }
        @media (min-width: 881px) {
          .scripture-toggle { display: none !important; }
          .scripture-fade { display: none !important; }
          .scripture-body[data-expanded="0"] { max-height: none !important; white-space: pre-wrap !important; }
        }
        }
      `}</style>
    </section>);

}

function ClassicMedia({ isLive = null }) {
  const c = window.CHURCH;
  const tw = (window.CHURCH && window.CHURCH.thisWeek) || {};
  // isLive가 null이면(API 미응답/에러) 시간 기반으로 보완 — liveStatus가 null이 되지 않도록
  const _now = new Date(), _day = _now.getDay(), _tot = _now.getHours()*60+_now.getMinutes();
  const _tLive = (_day>=1&&_day<=5&&_tot>=315&&_tot<420)||(_day===3&&_tot>=615&&_tot<720)||(_day===0&&_tot>=650&&_tot<750);
  const liveStatus = isLive !== null ? isLive : _tLive;
  return (
    <section id="media" style={{ padding: "100px 0", background: "linear-gradient(180deg, var(--paper-2) 0%, var(--paper) 100%)" }}>
      <div className="container">
        <SectionTitle eyebrow="Online · 온라인 예배" title={<React.Fragment>유튜브에서 함께<br className="br-mobile"/> 예배합니다</React.Fragment>} en={"@" + c.youtube + " · YouTube"} />
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "start" }}>
          <YouTubeCard
            title={isLive ? "주일 2부 예배 · LIVE 진행 중" : "최근 예배 다시보기"}
            subtitle=""
            live={liveStatus === true}
            mode="latest"
            playable={true}
            liveStatus={liveStatus}
          />
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="archive-card" style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 10, padding: 22 }}>
              <h4 style={{ fontSize: 17, fontWeight: 600, margin: "0 0 10px" }}>지난 예배 다시보기</h4>
              <ArchiveList />
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          #media > .container > div { grid-template-columns: 1fr !important; }
          .archive-card { padding: 14px 14px 10px !important; }
        }
      `}</style>
    </section>);

}

// ─────────────────────────────────────────────────────────
// 홈페이지용 PDF.js 뷰어 (community-content.jsx의 BulletinViewerModal 재사용 가능하지만
// 독립적으로 inline 정의하여 별도 스크립트 의존성 없애기)
// ─────────────────────────────────────────────────────────
async function _classicLoadPdfJs() {
  if (window.pdfjsLib) return window.pdfjsLib;
  return new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js";
    s.onload = () => {
      // cross-origin Worker 차단 우회: blob URL로 importScripts 사용
      const _wSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";
      window.pdfjsLib.GlobalWorkerOptions.workerSrc = URL.createObjectURL(
        new Blob([`importScripts("${_wSrc}")`], { type: "text/javascript" })
      );
      resolve(window.pdfjsLib);
    };
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

function ClassicBulletinModal({ title, pdfUrl, downloadUrl, onClose }) {
  const [pages, setPages]         = React.useState([]);
  const [pg, setPg]               = React.useState(1);
  const [loading, setLoading]     = React.useState(true);
  const [useIframe, setUseIframe] = React.useState(false);
  const [scale, setScale]         = React.useState(1.0);
  const [horizMode, setHorizMode] = React.useState(() => window.matchMedia("(pointer: coarse)").matches);
  const scaleRef  = React.useRef(1.0);
  const areaRef   = React.useRef(null);
  const horizRef  = React.useRef(null);
  const pinchRef  = React.useRef({ dist: 0, baseScale: 1 });
  const touchRef  = React.useRef(null);
  React.useEffect(() => { scaleRef.current = scale; }, [scale]);

  // ── PDF 로딩 ──────────────────────────────────────────────────
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      if (pdfUrl.includes("firebasestorage")) {
        if (!cancelled) { setUseIframe(true); setLoading(false); }
        return;
      }
      // Drive view URL은 CORS 차단 → Google Drive API v3 직접 다운로드 사용
      const _driveFid = (() => {
        const m = pdfUrl.match(/\/d\/([^/]+)\//);
        return m ? m[1] : null;
      })();
      const loadUrl = (pdfUrl.includes("drive.google.com") && _driveFid)
        ? `https://www.googleapis.com/drive/v3/files/${_driveFid}?alt=media&key=AIzaSyDfuBNn6MvdBAH_X19DxTi5Rvnt8K_tC4M`
        : pdfUrl;

      try {
        const pdfjs = await _classicLoadPdfJs();
        const pdf = await pdfjs.getDocument({ url: loadUrl, withCredentials: false }).promise;
        if (cancelled) return;
        const imgs = [];
        for (let i = 1; i <= pdf.numPages; i++) {
          const page = await pdf.getPage(i);
          const vp = page.getViewport({ scale: 1.2 });
          const canvas = document.createElement("canvas");
          canvas.width = vp.width; canvas.height = vp.height;
          await page.render({ canvasContext: canvas.getContext("2d"), viewport: vp }).promise;
          imgs.push(canvas.toDataURL("image/jpeg", 0.88));
          if (!cancelled) {
            setPages([...imgs]);
            if (i === 1) setLoading(false); // 1페이지 완료 즉시 표시
          }
        }
        if (!cancelled) setPages(imgs);
      } catch(e) {
        if (!cancelled) { setUseIframe(true); setLoading(false); }
      }
    }
    load();
    return () => { cancelled = true; };
  }, [pdfUrl]);

  // ── 키보드 단축키 ─────────────────────────────────────────────
  React.useEffect(() => {
    const h = (e) => {
      if (e.key === "Escape") onClose();
      if ((e.key === "ArrowRight" || e.key === "ArrowDown") && pages.length > 1) goPage(p => Math.min(pages.length, p+1));
      if ((e.key === "ArrowLeft"  || e.key === "ArrowUp")   && pages.length > 1) goPage(p => Math.max(1, p-1));
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose, pages.length]);

  // ── 페이지 이동 (가로 모드 스크롤 동기화 포함) ───────────────
  const goPage = (updater) => {
    setPg(prev => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      if (horizRef.current) {
        horizRef.current.scrollTo({ left: (next - 1) * horizRef.current.offsetWidth, behavior: "smooth" });
      }
      return next;
    });
  };

  // ── 가로 스크롤 → 인디케이터 동기화 ─────────────────────────
  React.useEffect(() => {
    const el = horizRef.current;
    if (!el) return;
    let t;
    const onScroll = () => {
      clearTimeout(t);
      t = setTimeout(() => {
        const idx = Math.round(el.scrollLeft / Math.max(el.offsetWidth, 1));
        setPg(idx + 1);
      }, 80);
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => { el.removeEventListener("scroll", onScroll); clearTimeout(t); };
  }, [horizMode, pages.length]);

  // ── 마우스 휠 줌 (세로 / PC) ─────────────────────────────────
  React.useEffect(() => {
    const el = areaRef.current;
    if (!el || loading || useIframe || horizMode) return;
    const h = (e) => {
      e.preventDefault();
      setScale(s => Math.min(Math.max(s - e.deltaY * 0.003, 0.25), 4.0));
    };
    el.addEventListener("wheel", h, { passive: false });
    return () => el.removeEventListener("wheel", h);
  }, [loading, useIframe, horizMode]);

  // ── 터치 핀치줌 + 패닝 (세로 모드 전용) ────────────────────
  React.useEffect(() => {
    const el = areaRef.current;
    if (!el || loading || useIframe || horizMode) return;
    const onTS = (e) => {
      if (e.touches.length === 2) {
        const dx = e.touches[0].clientX - e.touches[1].clientX;
        const dy = e.touches[0].clientY - e.touches[1].clientY;
        pinchRef.current = { dist: Math.hypot(dx, dy), baseScale: scaleRef.current };
      } else if (e.touches.length === 1) {
        touchRef.current = { y: e.touches[0].clientY, x: e.touches[0].clientX,
          scrollTop: el.scrollTop, scrollLeft: el.scrollLeft };
      }
    };
    const onTM = (e) => {
      if (e.touches.length === 2) {
        e.preventDefault();
        const dx = e.touches[0].clientX - e.touches[1].clientX;
        const dy = e.touches[0].clientY - e.touches[1].clientY;
        const ratio = Math.hypot(dx, dy) / (pinchRef.current.dist || 1);
        setScale(Math.min(Math.max(pinchRef.current.baseScale * ratio, 0.25), 4.0));
      } else if (e.touches.length === 1 && touchRef.current) {
        el.scrollTop  = touchRef.current.scrollTop  + (touchRef.current.y - e.touches[0].clientY);
        el.scrollLeft = touchRef.current.scrollLeft + (touchRef.current.x - e.touches[0].clientX);
      }
    };
    el.addEventListener("touchstart", onTS, { passive: true });
    el.addEventListener("touchmove",  onTM, { passive: false });
    return () => {
      el.removeEventListener("touchstart", onTS);
      el.removeEventListener("touchmove",  onTM);
    };
  }, [loading, useIframe, horizMode]);

  const iframeUrl = pdfUrl.includes("firebasestorage") ? pdfUrl
    : pdfUrl.includes("drive.google.com")
      ? (() => { const m = pdfUrl.match(/\/d\/([^/]+)\//); return m ? `https://drive.google.com/file/d/${m[1]}/preview` : `https://docs.google.com/viewer?url=${encodeURIComponent(pdfUrl)}&embedded=true`; })()
    : `https://docs.google.com/viewer?url=${encodeURIComponent(pdfUrl)}&embedded=true`;

  const useHorizMode = horizMode && !useIframe && !loading && pages.length > 0;

  const modalEl = (
    <div style={{ position:"fixed", inset:0, background:"rgba(10,15,35,0.97)", zIndex:99999,
      display:"flex", flexDirection:"column" }} onClick={onClose}>

      {/* ── 상단 헤더 ── */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between",
        padding:"8px 14px", background:"rgba(0,0,0,0.35)", flexShrink:0, minHeight:48 }}
        onClick={e=>e.stopPropagation()}>
        <span style={{ color:"#fff", fontWeight:600, fontSize:15, overflow:"hidden",
          textOverflow:"ellipsis", whiteSpace:"nowrap", maxWidth:"calc(100% - 260px)" }}>{title}</span>
        <div style={{ display:"flex", gap:10, alignItems:"center" }}>
          {!useIframe && !loading && pages.length > 0 && (
            <>
              <button onClick={()=>setHorizMode(m=>!m)}
                title={horizMode ? "세로 보기" : "가로 보기"}
                style={{ padding:"4px 9px", borderRadius:6, border:"1.5px solid rgba(255,255,255,0.28)",
                  background: horizMode ? "rgba(255,255,255,0.18)" : "transparent",
                  color:"#fff", fontSize:11, fontWeight:600, cursor:"pointer",
                  display:"flex", alignItems:"center", gap:4, whiteSpace:"nowrap" }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
                  {horizMode
                    ? <><line x1="12" y1="3" x2="12" y2="21"/><polyline points="9,6 12,3 15,6"/><polyline points="9,18 12,21 15,18"/></>
                    : <><line x1="3" y1="12" x2="21" y2="12"/><polyline points="6,9 3,12 6,15"/><polyline points="18,9 21,12 18,15"/></>
                  }
                </svg>
                {horizMode ? "세로" : "가로"}
              </button>
              <span style={{ color:"rgba(255,255,255,0.5)", fontSize:12, whiteSpace:"nowrap" }}>
                {pg} / {pages.length}{!horizMode ? ` · ${Math.round(scale*100)}%` : ""}
              </span>
            </>
          )}
          {downloadUrl && (
            <button onClick={async()=>{
              try{
                const fidM=(downloadUrl||pdfUrl).match(/\/d\/([^/]+)\//);
                const fid=fidM?fidM[1]:null;
                const fetchUrl=fid
                  ?`https://www.googleapis.com/drive/v3/files/${fid}?alt=media&key=AIzaSyDfuBNn6MvdBAH_X19DxTi5Rvnt8K_tC4M`
                  :downloadUrl;
                const res=await fetch(fetchUrl);
                if(!res.ok)throw new Error(res.status);
                const blob=await res.blob();
                const bUrl=URL.createObjectURL(blob);
                const a=document.createElement("a");
                a.href=bUrl; a.download=(title||"주보")+".pdf";
                document.body.appendChild(a); a.click(); document.body.removeChild(a);
                setTimeout(()=>URL.revokeObjectURL(bUrl),2000);
              }catch(e){ const fidM=(downloadUrl||pdfUrl).match(/\/d\/([^/]+)\//);const fid=fidM?fidM[1]:null; window.open(fid?`https://drive.google.com/uc?export=download&id=${fid}`:downloadUrl,"_blank"); }
            }}
              style={{ padding:"7px 14px", borderRadius:8, border:"1.5px solid rgba(255,255,255,0.28)",
                background:"#7D9BBC", color:"#fff", fontSize:12, fontWeight:700,
                cursor:"pointer", display:"flex", alignItems:"center", gap:6, whiteSpace:"nowrap" }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7 10 12 15 17 10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
              저장
            </button>
          )}
          <button onClick={onClose}
            style={{ width:36, height:36, borderRadius:999, background:"rgba(255,255,255,0.14)",
              border:"none", color:"#fff", fontSize:20, cursor:"pointer",
              display:"flex", alignItems:"center", justifyContent:"center" }}>✕</button>
        </div>
      </div>

      {/* ── 콘텐츠 ── */}
      <div style={{ flex:1, overflow:"hidden", display:"flex" }} onClick={e=>e.stopPropagation()}>

        {loading && (
          <div style={{ flex:1, display:"flex", alignItems:"center", justifyContent:"center",
            flexDirection:"column", gap:12, color:"rgba(255,255,255,0.65)" }}>
            <div style={{ fontSize:40 }}>📄</div>
            <div style={{ fontSize:14 }}>주보를 불러오는 중…</div>
          </div>
        )}

        {!loading && useIframe && (
          <iframe src={iframeUrl} style={{ flex:1, border:"none" }}
            allow="autoplay" title={title}/>
        )}

        {/* ── 모바일 가로 모드: 수평 scroll-snap 슬라이드 ── */}
        {useHorizMode && (
          <div style={{ flex:1, position:"relative" }}>
            <div ref={horizRef}
              style={{ display:"flex", flexDirection:"row", width:"100%", height:"100%",
                overflowX:"auto", overflowY:"hidden",
                scrollSnapType:"x mandatory", scrollBehavior:"smooth",
                WebkitOverflowScrolling:"touch",
                msOverflowStyle:"none", scrollbarWidth:"none" }}>
              {pages.map((src, idx) => (
                <div key={idx} style={{ flex:"0 0 100%", width:"100%", height:"100%",
                  scrollSnapAlign:"start",
                  display:"flex", alignItems:"center", justifyContent:"center", overflow:"hidden" }}>
                  <img src={src}
                    style={{ maxHeight:"100%", maxWidth:"100%", height:"auto", width:"auto",
                      objectFit:"contain", userSelect:"none", borderRadius:4,
                      boxShadow:"0 4px 24px rgba(0,0,0,0.5)" }}
                    alt={`${title} ${idx+1}페이지`} draggable={false}/>
                </div>
              ))}
            </div>
            {pages.length > 1 && (
              <>
                <button onClick={()=>goPage(p=>Math.max(1,p-1))} disabled={pg<=1}
                  style={{ position:"absolute", left:8, top:"50%", transform:"translateY(-50%)",
                    width:36, height:54, borderRadius:10, zIndex:5,
                    background:pg<=1?"rgba(255,255,255,0.04)":"rgba(255,255,255,0.18)",
                    border:"none", color:"#fff", fontSize:24, cursor:pg<=1?"default":"pointer",
                    opacity:pg<=1?0.1:0.9, display:"flex", alignItems:"center", justifyContent:"center" }}>‹</button>
                <button onClick={()=>goPage(p=>Math.min(pages.length,p+1))} disabled={pg>=pages.length}
                  style={{ position:"absolute", right:8, top:"50%", transform:"translateY(-50%)",
                    width:36, height:54, borderRadius:10, zIndex:5,
                    background:pg>=pages.length?"rgba(255,255,255,0.04)":"rgba(255,255,255,0.18)",
                    border:"none", color:"#fff", fontSize:24, cursor:pg>=pages.length?"default":"pointer",
                    opacity:pg>=pages.length?0.1:0.9, display:"flex", alignItems:"center", justifyContent:"center" }}>›</button>
              </>
            )}
            {pages.length > 1 && pages.length <= 16 && (
              <div style={{ position:"absolute", bottom:8, left:0, right:0,
                display:"flex", justifyContent:"center", gap:5, zIndex:5 }}>
                {pages.map((_,i) => (
                  <button key={i} onClick={()=>goPage(i+1)}
                    style={{ width:i+1===pg?16:6, height:6, borderRadius:999, padding:0,
                      background:i+1===pg?"rgba(255,255,255,0.9)":"rgba(255,255,255,0.3)",
                      border:"none", cursor:"pointer", transition:"width 0.25s, background 0.25s" }}/>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ── 세로 모드 / PC: 단일 페이지 + 좌우 화살표 ── */}
        {!loading && !useIframe && !useHorizMode && pages.length > 0 && (
          <>
            {pages.length > 1 && (
              <div style={{ width:52, flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center" }}>
                <button onClick={()=>setPg(p=>Math.max(1,p-1))} disabled={pg<=1}
                  style={{ width:40, height:60, borderRadius:12,
                    background:pg<=1?"rgba(255,255,255,0.04)":"rgba(255,255,255,0.16)",
                    border:"none", color:"#fff", fontSize:28, cursor:pg<=1?"default":"pointer",
                    opacity:pg<=1?0.15:0.9, display:"flex", alignItems:"center", justifyContent:"center" }}>‹</button>
              </div>
            )}
            <div ref={areaRef} style={{ flex:1, position:"relative",
              overflow: useHorizMode ? "hidden" : "auto",
              textAlign:"center",
              padding: useHorizMode ? "0" : "20px 10px 16px",
              touchAction:"none" }}>
              {pages[pg-1] && (
                useHorizMode ? (
                  <div style={{ position:"absolute", inset:0, display:"flex",
                    alignItems:"center", justifyContent:"center" }}>
                    <img src={pages[pg-1]}
                      style={{ transform:"rotate(90deg)", transformOrigin:"center center",
                        width:"calc(100vh - 56px)", height:"100vw",
                        objectFit:"contain", flexShrink:0,
                        borderRadius:10, boxShadow:"0 8px 40px rgba(0,0,0,0.6)",
                        userSelect:"none" }}
                      alt={`${title} ${pg}페이지`} draggable={false}/>
                  </div>
                ) : (
                  <>
                    <img src={pages[pg-1]}
                      style={{ width:`${Math.round(scale * 820)}px`, maxWidth:"none", minWidth:200,
                        borderRadius:10, boxShadow:"0 8px 40px rgba(0,0,0,0.6)",
                        display:"inline-block", userSelect:"none" }}
                      alt={`${title} ${pg}페이지`} draggable={false}/>
                    <div style={{ color:"rgba(255,255,255,0.2)", fontSize:11, marginTop:12, paddingBottom:8 }}>
                      마우스 휠 · 두 손가락 핀치로 확대/축소
                    </div>
                  </>
                )
              )}
            </div>
            {pages.length > 1 && (
              <div style={{ width:52, flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center" }}>
                <button onClick={()=>setPg(p=>Math.min(pages.length,p+1))} disabled={pg>=pages.length}
                  style={{ width:40, height:60, borderRadius:12,
                    background:pg>=pages.length?"rgba(255,255,255,0.04)":"rgba(255,255,255,0.16)",
                    border:"none", color:"#fff", fontSize:28, cursor:pg>=pages.length?"default":"pointer",
                    opacity:pg>=pages.length?0.15:0.9, display:"flex", alignItems:"center", justifyContent:"center" }}>›</button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
  return ReactDOM.createPortal(modalEl, document.body);
}
function ClassicBulletin() {
  const [latest, setLatest]     = React.useState(null);
  const [loading, setLoading]   = React.useState(true);
  const [modalOpen, setModalOpen] = React.useState(false);

  React.useEffect(() => {
    if (typeof firebase === "undefined" || !firebase.firestore) return;
    firebase.firestore().collection("bulletins").get()
      .then(snap => {
        const list = snap.docs.map(d => ({ id: d.id, ...d.data() }));
        list.sort((a, b) => (b.date || "").localeCompare(a.date || ""));
        setLatest(list[0] || null);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const toDownloadUrl = (url) => {
    if (!url) return "";
    const m1 = url.match(/\/file\/d\/([^/]+)/);
    if (m1) return `https://drive.google.com/uc?id=${m1[1]}&export=download`;
    const m2 = url.match(/[?&]id=([^&]+)/);
    if (m2) return `https://drive.google.com/uc?id=${m2[1]}&export=download`;
    return url;
  };

  if (!loading && !latest) return null;

  const fmtDate = (d) => {
    if (!d) return "";
    const [y,m,day] = d.split("-");
    return `${y}년 ${parseInt(m)}월 ${parseInt(day)}일 주보`;
  };

  const bulletinTitle = latest ? (latest.title || fmtDate(latest.date)) : "";
  const pdfUrl  = latest ? (latest.storageUrl || latest.driveUrl || "") : "";
  const dlUrl   = toDownloadUrl(pdfUrl);

  return (
    <section id="bulletin-viewer" style={{ padding:"80px 0", background:"var(--paper-2)" }}>
      <div className="container" style={{ maxWidth:900 }}>
        <div style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between",
          marginBottom:32, flexWrap:"wrap", gap:12 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom:8 }}>이번 주 주보</div>
            <h2 style={{ margin:0, fontSize:"clamp(22px,4vw,32px)", fontWeight:700,
              fontFamily:"var(--font-display,serif)" }}>
              {loading ? "불러오는 중…" : bulletinTitle}
            </h2>
          </div>
          {latest && (
            <div style={{ display:"flex", gap:10 }}>
              <a href={dlUrl} target="_blank" rel="noopener noreferrer"
                className="btn ghost" style={{ fontSize:14 }}>⬇ 다운로드</a>
              <a href="/community/community.html#bulletin" className="btn ghost" style={{ fontSize:14 }}>지난 주보 →</a>
            </div>
          )}
        </div>

        {loading && (
          <div style={{ height:400, display:"flex", alignItems:"center", justifyContent:"center",
            color:"var(--ink-3)", flexDirection:"column", gap:12 }}>
            <div style={{ fontSize:40 }}>📄</div>불러오는 중…
          </div>
        )}

        {latest && !loading && (
          <div
            onClick={() => setModalOpen(true)}
            style={{ borderRadius:14, overflow:"hidden",
              boxShadow:"0 4px 24px rgba(0,0,0,0.10)", border:"1px solid var(--line)",
              background:"#fff", cursor:"pointer", position:"relative",
              transition:"transform .15s, box-shadow .15s" }}
            onMouseEnter={e=>{ e.currentTarget.style.transform="translateY(-3px)"; e.currentTarget.style.boxShadow="0 8px 32px rgba(0,0,0,0.15)"; }}
            onMouseLeave={e=>{ e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow="0 4px 24px rgba(0,0,0,0.10)"; }}>
            {/* PDF 미리보기 iframe (클릭 불가, 오버레이 처리) */}
            <div style={{ position:"relative", height:600 }}>
              <iframe
                src={pdfUrl.includes("firebasestorage.googleapis.com") ? pdfUrl : `https://docs.google.com/viewer?url=${encodeURIComponent(pdfUrl)}&embedded=true`}
                style={{ width:"100%", height:"100%", border:"none", display:"block", pointerEvents:"none" }}
                title="이번 주 주보 미리보기"
              />
              {/* 클릭 유도 오버레이 */}
              <div style={{ position:"absolute", inset:0, display:"flex", alignItems:"center",
                justifyContent:"center", background:"rgba(0,0,0,0)", transition:"background .2s" }}
                className="bulletin-overlay">
                <div style={{ background:"rgba(0,0,0,0.55)", color:"#fff", padding:"12px 24px",
                  borderRadius:999, fontSize:15, fontWeight:700, display:"flex", alignItems:"center", gap:8,
                  opacity:0, transition:"opacity .2s" }} className="bulletin-overlay-btn">
                  📄 주보 펼쳐보기
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      <style>{`
        .bulletin-overlay:hover { background: rgba(0,0,0,0.1) !important; }
        .bulletin-overlay:hover .bulletin-overlay-btn { opacity: 1 !important; }
      `}</style>

      {modalOpen && pdfUrl && (
        <ClassicBulletinModal
          title={bulletinTitle}
          pdfUrl={pdfUrl}
          downloadUrl={dlUrl}
          onClose={() => setModalOpen(false)}
        />
      )}
    </section>
  );
}

function ClassicPrayer() {
  const c = window.CHURCH;
  const [essayExpanded, setEssayExpanded] = React.useState(false);
  const [essayMobileExpanded, setEssayMobileExpanded] = React.useState(false);
  const essayBody = (c.weeklyEssay && c.weeklyEssay.body) || "";
  const essayRef = React.useRef(null);
  const [essayOverflows, setEssayOverflows] = React.useState(false);
  React.useEffect(() => {
    if (essayRef.current) {
      // PC 10줄 기준: font-size 14px x line-height 1.85 x 10 = 259px
      setEssayOverflows(essayRef.current.scrollHeight > 259);
    }
  }, [essayBody]);
  return (
    <section id="prayer" style={{ padding: "100px 0" }}>
      <div className="container" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "start" }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>'주심' 중보기도 나눔</div>
          <h2 className="prayer-title" style={{ fontSize: 36, fontWeight: 500, lineHeight: 1.25, margin: 0 }}>이번 주, 함께<br className="br-mobile"/> 기도합니다.</h2>
          <p style={{ marginTop: 16, color: "var(--ink-3)" }}>주보에 실린 기도제목을 일상에서 함께 들고 갑니다.</p>
          <ul className="prayer-list" style={{ marginTop: 28, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 14 }}>
            {c.prayerPoints.map((p, i) =>
            <li key={i} style={{ display: "flex", gap: 14, paddingLeft: 0 }}>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "var(--mint-deep)", fontWeight: 700, paddingTop: 6, minWidth: 24 }}>0{i + 1}</span>
                <span style={{ fontSize: 15, color: "var(--ink-2)", lineHeight: 1.6, paddingTop: 4 }}>{p}</span>
              </li>
            )}
          </ul>
        </div>
        <aside className="essay-card" style={{ background: "var(--primary)", color: "white", padding: 40, borderRadius: 14, position: "relative", overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div style={{ position: "absolute", top: 30, right: 30, opacity: 0.18 }}>
            <Icon.quote size={64} />
          </div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", opacity: 0.7 }}>주간 기도에세이</div>
          <div style={{ position: "relative", marginTop: 16 }}>
            <p ref={essayRef} className="essay-body" data-mobile-expanded={essayMobileExpanded ? "1" : "0"} style={{
              whiteSpace: "pre-line", fontSize: 14, lineHeight: 1.85,
              color: "rgba(255,255,255,0.88)", margin: 0,
              maxHeight: essayExpanded ? "200em" : "18.5em",
            }}>{essayBody}</p>
            {/* PC 페이드 */}
            {!essayExpanded && essayOverflows && (
              <div className="essay-fade-pc" style={{
                position: "absolute", bottom: 0, left: 0, right: 0, height: 56,
                background: "linear-gradient(transparent, var(--primary))",
                pointerEvents: "none",
              }}/>
            )}
            {/* 모바일 페이드 */}
            <div className={"essay-fade-mobile" + (essayMobileExpanded ? " hidden" : "")} style={{
              position: "absolute", bottom: 0, left: 0, right: 0, height: 48,
              background: "linear-gradient(transparent, var(--primary))",
              pointerEvents: "none",
            }}/>
          </div>
          {essayOverflows && (
            <button className="essay-toggle-pc"
              onClick={() => setEssayExpanded(x => !x)}
              style={{
                marginTop: 18, alignSelf: "flex-start",
                background: "rgba(255,255,255,0.18)", color: "white",
                border: "1px solid rgba(255,255,255,0.32)", borderRadius: 999,
                padding: "8px 20px", fontSize: 12, fontWeight: 700,
                cursor: "pointer", letterSpacing: "0.02em",
              }}>
              {essayExpanded ? "접기 ↑" : "펼쳐보기 ↓"}
            </button>
          )}
          {/* 모바일 전용 펼치기/접기 버튼 */}
          <button className="essay-toggle-mobile"
            onClick={() => setEssayMobileExpanded(x => !x)}
            style={{
              marginTop: 12, alignSelf: "flex-start",
              background: "rgba(255,255,255,0.18)", color: "white",
              border: "1px solid rgba(255,255,255,0.32)", borderRadius: 999,
              padding: "6px 16px", fontSize: 12, fontWeight: 700,
              cursor: "pointer", letterSpacing: "0.02em",
            }}>
            {essayMobileExpanded ? "접기 ▲" : "펼치기 ▼"}
          </button>
        </aside>
      </div>
      <style>{`
        @media (max-width: 880px) {
          #prayer > .container { grid-template-columns: 1fr !important; gap: 40px !important; }
          .prayer-title { font-size: 24px !important; white-space: nowrap !important; }
          #prayer .br-mobile { display: none !important; }
          .prayer-list { gap: 8px !important; margin-top: 16px !important; }
          /* 기도에세이 모바일 */
          .essay-card { padding: 24px 20px 16px !important; }
          /* scripture 방식과 동일하게 max-height 트랜지션 */
          .essay-body {
            transition: max-height 0.4s ease !important;
            overflow: hidden !important;
          }
          .essay-body[data-mobile-expanded="0"] {
            max-height: 160px !important;
          }
          .essay-body[data-mobile-expanded="1"] {
            max-height: 2000px !important;
          }
          .essay-fade-mobile {
            display: block !important;
            transition: opacity 0.3s ease !important;
          }
          .essay-fade-mobile.hidden { opacity: 0 !important; pointer-events: none; }
          .essay-toggle-mobile { display: inline-flex !important; }
          .essay-toggle-pc { display: none !important; }
          .essay-fade-pc { display: none !important; }
        }
        @media (min-width: 881px) {
          .essay-toggle-mobile { display: none !important; }
          .essay-fade-mobile { display: none !important; }
          /* PC에서는 인라인 스타일 그대로 동작하도록 max-height 초기화 */
          .essay-body { transition: max-height 0.5s ease !important; overflow: hidden !important; }
        }
      `}</style>
    </section>);
}

// ── 주보 팝업 버튼 (방문자용 — 교인마당 이동 없이 바로 PDF 표시) ──
function BulletinViewButton() {
  const [open, setOpen]         = React.useState(false);
  const [bulletin, setBulletin] = React.useState(null);
  const [loading, setLoading]   = React.useState(false);
  const [fetched, setFetched]   = React.useState(false);

  const handleClick = () => {
    setOpen(true);
    if (!fetched) {
      setLoading(true);
      setFetched(true);
      try {
        firebase.firestore().collection("bulletins").get()
          .then(snap => {
            const list = snap.docs.map(d => ({ id: d.id, ...d.data() }));
            list.sort((a, b) => (b.date || "").localeCompare(a.date || ""));
            setBulletin(list[0] || null);
            setLoading(false);
          })
          .catch(() => setLoading(false));
      } catch(e) { setLoading(false); }
    }
  };

  const pdfUrl = bulletin ? (bulletin.storageUrl || bulletin.driveUrl || "") : "";
  const title  = bulletin
    ? (bulletin.title || (bulletin.date
        ? bulletin.date.replace(/(\d{4})-(\d{2})-(\d{2})/, (_, y, m, d) => y + "년 " + parseInt(m) + "월 " + parseInt(d) + "일 주보")
        : "이번 주 주보"))
    : "이번 주 주보";

  return (
    <React.Fragment>
      <button className="btn ghost" onClick={handleClick}>주보 보기</button>
      {open && loading && (
        <div style={{ position:"fixed", inset:0, zIndex:9999, background:"rgba(10,15,35,0.97)",
          display:"flex", alignItems:"center", justifyContent:"center" }}
          onClick={()=>setOpen(false)}>
          <div style={{ color:"rgba(255,255,255,0.65)", textAlign:"center" }}>
            <div style={{ fontSize:40, marginBottom:16 }}>📄</div>
            <div style={{ fontSize:14 }}>주보를 불러오는 중…</div>
          </div>
        </div>
      )}
      {open && !loading && !bulletin && (
        <div style={{ position:"fixed", inset:0, zIndex:9999, background:"rgba(10,15,35,0.97)",
          display:"flex", alignItems:"center", justifyContent:"center" }}
          onClick={()=>setOpen(false)}>
          <div style={{ color:"rgba(255,255,255,0.65)", textAlign:"center" }}>
            <div style={{ fontSize:40, marginBottom:16 }}>📄</div>
            <div style={{ fontSize:14 }}>등록된 주보가 없습니다.</div>
            <button onClick={()=>setOpen(false)} style={{ marginTop:20, padding:"8px 20px",
              borderRadius:8, background:"rgba(255,255,255,0.15)", border:"none", color:"#fff",
              cursor:"pointer", fontSize:14 }}>닫기</button>
          </div>
        </div>
      )}
      {open && !loading && bulletin && pdfUrl && (
        <ClassicBulletinModal title={title} pdfUrl={pdfUrl}
          downloadUrl={bulletin ? (bulletin.downloadUrl || (()=>{const m=pdfUrl.match(/\/d\/([^/]+)\//);return m?`https://drive.google.com/uc?id=${m[1]}&export=download`:"";})()) : ""}
          onClose={()=>setOpen(false)}/>
      )}
    </React.Fragment>
  );
}

function ClassicVisit() {
  const c = window.CHURCH;
  const gc = window.getCopy;
  const [copiedRoad, copyRoad] = useCopyButton();
  const [copiedJibun, copyJibun] = useCopyButton();
  const [copiedBank, copyBank] = useCopyButton();
  const naviApps = [
  { label: "카카오맵에서 길찾기", accent: "#fee500", dot: "카", dotText: "#3c1e1e", url: `https://map.kakao.com/?q=${encodeURIComponent(c.address)}` },
  { label: "네이버 지도에서 길찾기", accent: "#03c75a", dot: "N", url: `https://map.naver.com/p/search/${encodeURIComponent(c.address)}` },
  { label: "티맵 내비게이션 시작", accent: "#1f74e8", dot: "T", url: null,
    handleClick: () => {
      const _d = `goalname=${encodeURIComponent('맑은빛 세광교회')}&goalx=126.943073&goaly=37.556002`;
      window.location.href = /Android/i.test(navigator.userAgent)
        ? `intent://route?${_d}#Intent;scheme=tmap;package=com.skt.tmap.ku;end`
        : `tmap://route?${_d}`;
    } }];

  return (
    <section id="visit" style={{ padding: "100px 0", background: "var(--paper-2)" }}>
      <div className="container">
        <SectionTitle eyebrow="Visit · 오시는 길" title={<React.Fragment>{window.getCopy ? window.getCopy("visit.title") : "언제나 여러분을 위해"}<br className="br-mobile"/> {window.getCopy ? "" : "교회는 열려 있습니다"}</React.Fragment>} en={window.getCopy ? window.getCopy("visit.en") : "Mapo-gu, Sinchon-ro 26-gil 11"} />
        {/* 이 섹션 제목만 작게 — '이번 주, 함께 기도합니다.'와 동일 사이즈로 통일 */}
        <style>{`
          #visit > .container > header > h2 {
            font-size: 36px !important;
            font-weight: 500 !important;
            line-height: 1.25 !important;
          }
          @media (max-width: 720px) {
            #visit > .container > header > h2 { font-size: 28px !important; }
          }
        `}</style>

        {/* ─── 약도 + 우측 정보 패널 ─── */}
        <div className="visit-map-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 18, alignItems: "stretch" }}>
          <div style={{
            position: "relative", borderRadius: 14, overflow: "hidden",
            border: "1px solid var(--line)", background: "var(--paper)",
            minWidth: 0, minHeight: 360
          }}>
            <KakaoEmbedMap />
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 14, fontFamily: "var(--font-sans)", height: "100%" }}>
            {/* 주소 카드 */}
            <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 14, padding: 22, flex: 1, display: "flex", flexDirection: "column" }}>
              <div style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700, marginBottom: 10 }}>주소</div>
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>{c.addressZip} {c.address}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>한국기독교장로회 세광교회</div>
              <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
                <button
                  className="btn ghost"
                  style={{ flex: 1, padding: "9px 14px", fontSize: 12, background: copiedRoad ? "var(--mint-soft)" : "var(--paper-2)", color: copiedRoad ? "var(--mint-deep)" : undefined, border: 0, justifyContent: "center", transition: "all .15s ease" }}
                  onClick={() => copyRoad(c.address)}>
                  {copiedRoad ? "✓ 복사됨" : "도로명 복사"}</button>
                <button
                  className="btn ghost"
                  style={{ flex: 1, padding: "9px 14px", fontSize: 12, background: copiedJibun ? "var(--mint-soft)" : "var(--paper-2)", color: copiedJibun ? "var(--mint-deep)" : undefined, border: 0, justifyContent: "center", transition: "all .15s ease" }}
                  onClick={() => copyJibun("서울 마포구 대흥동 812")}>
                  {copiedJibun ? "✓ 복사됨" : "지번 복사"}</button>
              </div>
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 6, fontSize: 13 }}>
                <a href={`tel:${c.phone}`} style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--ink)", textDecoration: "none" }}><Icon.phone size={14} /> {c.phone}</a>
                <a href={`mailto:${c.email}`} style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--ink)", textDecoration: "none" }}><Icon.mail size={14} /> {c.email}</a>
              </div>
            </div>

            {/* 내비 앱 바로가기 — C안 톤 적용 */}
            <div style={{
              background: "linear-gradient(160deg, var(--mint-tint) 0%, var(--card) 100%)",
              border: "1px solid var(--mint-soft)",
              borderRadius: 14, padding: 22,
              flex: 1,
              display: "flex", flexDirection: "column"
            }}>
              <div style={{ fontSize: 11, color: "var(--mint-deep)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700, marginBottom: 10 }}>내비게이션 앱 바로가기</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 12, lineHeight: 1.6 }}>
                스마트폰에서 누르면 실시간 길안내가 시작됩니다.
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {naviApps.map((a) =>
                <a key={a.label} href={a.url || "#"}
                  target={a.url ? "_blank" : "_self"}
                  rel={a.url ? "noopener noreferrer" : undefined}
                  onClick={a.handleClick ? (e) => { e.preventDefault(); a.handleClick(); } : undefined}
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  gap: 10, padding: "12px 16px",
                  background: "var(--card)",
                  color: "var(--ink)",
                  border: "1px solid var(--line)",
                  borderLeft: `4px solid ${a.accent}`,
                  borderRadius: 10, textDecoration: "none",
                  fontSize: 13, fontWeight: 700
                }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
                      <span style={{
                      width: 22, height: 22, borderRadius: 999,
                      background: a.accent, color: a.dotText || "white",
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      fontSize: 10, fontWeight: 900
                    }}>{a.dot}</span>
                      {a.label}
                    </span>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M14 3h7v7M10 14L21 3M19 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h6" />
                    </svg>
                  </a>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* ─── 상세 동선 + 교통수단 + 건물 층별 안내 ─── */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 18, marginTop: 24, alignItems: "stretch" }} className="visit-map-grid">
          {/* 좌측: 동선 안내 + 교통수단 */}
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <RouteStepsCard />

            {/* 교통수단별 안내 (3컬럼) — 동선 안내 아래로 이동 */}
            <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, fontFamily: "var(--font-sans)", flex: 1, alignItems: "stretch" }} className="visit-transport-grid">
                {[
                { id: "subway", title: "지하철", icon: "🚇", color: "var(--primary)", items: (gc && gc("visit.subway") ? gc("visit.subway").split("\n").filter(Boolean) : c.transport.subway) },
                { id: "bus", title: "버스", icon: "🚌", color: "var(--mint-deep)", items: (gc && gc("visit.bus") ? gc("visit.bus").split("\n").filter(Boolean) : c.transport.bus) },
                { id: "car", title: "자가용·주차", icon: "🚗", color: "#c4923f", items: (gc && gc("visit.car") ? gc("visit.car").split("\n").filter(Boolean) : c.transport.car) }].
                map((t) =>
                <div key={t.id} style={{
                  background: "var(--card)", border: "1px solid var(--line)",
                  borderRadius: 12, padding: 16,
                  display: "flex", flexDirection: "column", gap: 8
                }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div style={{
                      width: 28, height: 28, borderRadius: 7, background: "var(--paper-2)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 14
                    }}>{t.icon}</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>{t.title}</div>
                    </div>
                    <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 6 }}>
                      {t.items.map((line, i) =>
                    <li key={i} style={{
                      display: "flex", gap: 6,
                      fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.55
                    }}>
                          <span style={{ color: t.color, flexShrink: 0, paddingTop: 2 }}>•</span>
                          <span>{line}</span>
                        </li>
                    )}
                    </ul>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 우측: 건물 층별 안내 */}
          <div className="floor-card" style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 14, padding: 28, fontFamily: "var(--font-sans)", height: "100%", display: "flex", flexDirection: "column" }}>
            <div className="eyebrow" style={{ color: "var(--mint-deep)", marginBottom: 8 }}>Inside · 층별 안내</div>
            <h3 style={{ fontSize: 18, fontWeight: 600, margin: "0 0 16px" }}>층별 사용 공간</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 0, borderTop: "1px solid var(--line)" }}>
              {c.building.map((b, i) =>
              <div key={i} className="floor-row" style={{
                display: "flex", alignItems: "center", gap: 16,
                padding: "14px 0", borderBottom: "1px solid var(--line)",
                opacity: b.external ? 0.55 : 1
              }}>
                  <div style={{
                  width: 42, height: 42, borderRadius: 8,
                  background: b.floor === "B1" ? "var(--primary)" : b.external ? "var(--paper-3)" : "var(--paper-2)",
                  color: b.floor === "B1" ? "white" : b.external ? "var(--ink-3)" : "var(--primary)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: b.floor.length > 2 ? 11 : 13, fontWeight: 800, letterSpacing: "0.04em",
                  flexShrink: 0
                }}>{b.floor}</div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700 }}>{b.label}</div>
                    {b.sub && <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{b.sub}</div>}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* ─── 헌금 안내 ─── */}
        <div style={{
          marginTop: 32,
          background: "linear-gradient(135deg, var(--mint-soft) 0%, var(--card) 100%)",
          color: "var(--ink)", borderRadius: 18, padding: "10px 24px",
          display: "grid", gridTemplateColumns: "1fr auto", gap: 20, alignItems: "center",
          border: "1px solid var(--line)"
        }} className="giving-grid">
          <div style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <div className="eyebrow" style={{ color: "var(--mint-deep)", marginBottom: 6 }}>Offering · 헌금 안내</div>
            <h3 className="giving-h3" style={{ fontSize: 20, margin: "0 0 6px", fontWeight: 500, lineHeight: 1.3, color: "var(--ink)" }}>
              {window.getCopy ? window.getCopy("giving.headline") : "온라인으로도 헌금을 드릴 수 있습니다."}
            </h3>
            <p style={{ fontFamily: "var(--font-sans)", color: "var(--ink-3)", fontSize: 14, margin: 0 }}>
              <span className="giving-sub-full">{window.getCopy ? window.getCopy("giving.body") : "십일조·감사·선교·구제 등 모든 헌금은 아래 계좌로 송금하실 수 있습니다."}</span>
              <span className="giving-sub-short">십일조·감사·선교·구제 등 모든 헌금</span>
            </p>
          </div>
          <div className="giving-card" style={{
            background: "white", borderRadius: 14, padding: "8px 16px",
            boxShadow: "0 8px 24px -12px rgba(20,30,60,0.15)",
            fontFamily: "var(--font-sans)",
            display: "flex", flexDirection: "column", justifyContent: "center", alignSelf: "center"
          }}>
            <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 700 }}>온라인 헌금 계좌</div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 4 }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap" }}>{(window.getCopy ? window.getCopy("giving.bank") : "신한")} {(window.getCopy ? window.getCopy("giving.account") : "100-034-146193")}</div>
              <button className="btn" style={{
                background: copiedBank ? "var(--mint-soft)" : "var(--mint-deep)",
                color: copiedBank ? "var(--mint-deep)" : "white",
                border: "none", fontSize: 12, padding: "5px 12px",
                flexShrink: 0,
                transition: "all .2s ease",
              }} onClick={() => { const acct = ((c.bankAccount||"").match(/\d[\d\-]+\d/)?.[0] || c.bankAccount || "").replace(/-/g, ""); copyBank(acct); }}>
                {copiedBank ? "✓ 복사됨" : "복사"}
              </button>
            </div>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--ink-3)", marginTop: 2, paddingLeft: 4 }}>예금주: {window.getCopy ? window.getCopy("giving.holder") : "한국기독교장로회 세광교회"}</div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .visit-route-cards { grid-template-columns: 1fr !important; }
          .visit-map-grid { grid-template-columns: 1fr !important; }
          .visit-transport-grid { grid-template-columns: 1fr !important; }
          #visit > .container > div[style*="ink"] { grid-template-columns: 1fr !important; padding: 28px !important; }
          .giving-grid { grid-template-columns: 1fr !important; padding: 20px !important; gap: 14px !important; }
          .giving-h3 { display: none !important; }
          .giving-sub-full { display: none !important; }
          .giving-card { width: fit-content; margin: 0 auto; }
          .visit-map-grid > div:last-child { padding: 16px !important; }
          .visit-map-grid > div:last-child h3 { margin: 0 0 8px !important; }
          .floor-row { padding: 7px 0 !important; }
        }
        .giving-sub-short { display: none; }
        @media (max-width: 880px) {
          .giving-sub-short { display: inline !important; }
        }
      `}</style>
    </section>);

}


// ─────────── 세광갤러리 (메인 홈페이지) ───────────
// 관리자가 게시한 앨범만 표시. galleryVisible=false이면 숨김.
// 클릭 시 라이트박스로 크게 보기 / 영상 재생 지원
// ─── 앨범 캐러셀 (홈페이지 갤러리 한 줄 슬라이더) ───
function AlbumCarousel({ albumName, albumItems, openLightbox }) {
  const PAGE = 8;
  const [offset, setOffset] = React.useState(0);
  const [animStyle, setAnimStyle] = React.useState({});
  const [isAnimating, setIsAnimating] = React.useState(false);
  const touchStartX = React.useRef(null);

  const maxOffset = Math.max(0, albumItems.length - PAGE);
  const totalPages = Math.ceil(albumItems.length / PAGE);
  const currentPage = Math.floor(offset / PAGE);
  const canPrev = offset > 0;
  const canNext = offset < maxOffset;

  // Drive 썸네일 URL 헬퍼
  const thumbUrl = (item, size) => {
    if (!size) size = 200;
    if (item.driveFileId) return 'https://drive.google.com/thumbnail?id=' + item.driveFileId + '&sz=w' + size;
    var m = (item.driveViewUrl || item.downloadURL || '').match(/[?&]id=([^&]+)/);
    if (m) return 'https://drive.google.com/thumbnail?id=' + m[1] + '&sz=w' + size;
    return item.downloadURL || null;
  };

  const goTo = function(newOffset, dir) {
    if (isAnimating) return;
    setIsAnimating(true);
    // 1. 현재 내용 슬라이드 아웃
    setAnimStyle({
      opacity: 0,
      transform: 'translateX(' + (dir === 'left' ? '-44px' : '44px') + ')',
      transition: 'opacity 0.15s ease, transform 0.16s ease',
    });
    setTimeout(function() {
      setOffset(newOffset);
      // 2. 반대쪽에서 시작 (transition 없이 snap)
      setAnimStyle({
        opacity: 0,
        transform: 'translateX(' + (dir === 'left' ? '44px' : '-44px') + ')',
        transition: 'none',
      });
      // 3. 슬라이드 인
      requestAnimationFrame(function() {
        requestAnimationFrame(function() {
          setAnimStyle({
            opacity: 1,
            transform: 'translateX(0)',
            transition: 'opacity 0.2s ease, transform 0.22s cubic-bezier(.25,.8,.25,1)',
          });
          setTimeout(function() { setIsAnimating(false); }, 230);
        });
      });
    }, 155);
  };

  var prev = function() { if (canPrev && !isAnimating) goTo(Math.max(0, offset - PAGE), 'right'); };
  var next = function() { if (canNext && !isAnimating) goTo(Math.min(maxOffset, offset + PAGE), 'left'); };

  // 모바일 터치 스와이프
  var onTouchStart = function(e) { touchStartX.current = e.touches[0].clientX; };
  var onTouchEnd = function(e) {
    if (touchStartX.current === null) return;
    var dx = e.changedTouches[0].clientX - touchStartX.current;
    touchStartX.current = null;
    if (dx < -55 && canNext) next();
    else if (dx > 55 && canPrev) prev();
  };

  var visible = albumItems.slice(offset, offset + PAGE);

  var ArrowBtn = function(_ref) {
    var direction = _ref.direction, onClick = _ref.onClick, enabled = _ref.enabled;
    return (
      <button onClick={onClick} disabled={!enabled || isAnimating}
        style={{
          position: "absolute",
          left: direction === "left" ? -22 : "auto",
          right: direction === "right" ? -22 : "auto",
          top: "50%", transform: "translateY(-50%)",
          zIndex: 2, width: 38, height: 38, borderRadius: "50%",
          background: enabled ? "var(--ink, #2a2a2a)" : "var(--line, #ddd)",
          color: "white", border: "none", cursor: enabled ? "pointer" : "default",
          display: "flex", alignItems: "center", justifyContent: "center",
          transition: "transform 0.18s cubic-bezier(.34,1.56,.64,1), opacity 0.18s ease, box-shadow 0.18s ease",
          opacity: enabled ? 1 : 0.22,
          boxShadow: enabled ? "0 3px 10px rgba(0,0,0,0.22)" : "none",
        }}
        onMouseEnter={function(e) { if(enabled){ e.currentTarget.style.transform="translateY(-50%) scale(1.18)"; e.currentTarget.style.boxShadow="0 5px 16px rgba(0,0,0,0.3)"; }}}
        onMouseLeave={function(e) { e.currentTarget.style.transform=enabled?"translateY(-50%) scale(1)":"translateY(-50%) scale(0.82)"; e.currentTarget.style.boxShadow=enabled?"0 3px 10px rgba(0,0,0,0.22)":"none"; }}
        onMouseDown={function(e) { if(enabled) e.currentTarget.style.transform="translateY(-50%) scale(0.94)"; }}
        onMouseUp={function(e) { if(enabled) e.currentTarget.style.transform="translateY(-50%) scale(1.18)"; }}>
        {direction === "left"
          ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15,18 9,12 15,6"/></svg>
          : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="9,18 15,12 9,6"/></svg>}
      </button>
    );
  };

  return (
    <div>
      {/* 앨범 헤더 */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
        <h3 style={{ fontSize: 17, fontWeight: 600, color: "var(--ink)", margin: 0 }}>{albumName}</h3>
        <span style={{ fontSize: 12, color: "var(--ink-3)" }}>
          {albumItems.filter(function(i) { return i.fileType && i.fileType.startsWith("video"); }).length > 0
            ? ('사진 ' + albumItems.filter(function(i) { return !i.fileType || !i.fileType.startsWith("video"); }).length + '·영상 ' + albumItems.filter(function(i) { return i.fileType && i.fileType.startsWith("video"); }).length)
            : albumItems.length + '장'}
        </span>
      </div>

      {/* 캐러셀 */}
      <div style={{ position: "relative", padding: "0 28px" }}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}>
        <ArrowBtn direction="left" onClick={prev} enabled={canPrev}/>

        {/* overflow hidden — 슬라이드 애니메이션용 */}
        <div style={{ overflow: "hidden", borderRadius: 10 }}>
          <div style={Object.assign({
            display: "grid",
            gridTemplateColumns: "repeat(8, 1fr)",
            gap: 6,
          }, animStyle)}>
            {visible.map(function(item) {
              var isVid = item.fileType && item.fileType.startsWith("video");
              var thumb = thumbUrl(item, 200);
              return (
                <div key={item.id} style={{ cursor: "pointer" }}
                  onClick={function() { openLightbox(item, albumItems); }}>
                  <div style={{
                    position: "relative", aspectRatio: "1",
                    borderRadius: 8, overflow: "hidden",
                    background: isVid ? "linear-gradient(135deg,#1a2238,#3d5d8c)" : "var(--paper-3)",
                    transition: "transform 0.18s ease, box-shadow 0.18s ease",
                  }}
                    onMouseEnter={function(e) { e.currentTarget.style.transform="scale(1.06)"; e.currentTarget.style.boxShadow="0 4px 14px rgba(0,0,0,0.18)"; }}
                    onMouseLeave={function(e) { e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow=""; }}>
                    {thumb && !isVid ? (
                      <img src={thumb}
                        alt={item.title || item.fileName || ""}
                        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                        onError={function(e) { e.target.style.display = "none"; }}/>
                    ) : isVid ? (
                      <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}>
                        <div style={{ position: "relative", zIndex: 1, width: 28, height: 28, borderRadius: "50%", background: "rgba(255,255,255,0.9)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                          <svg width="10" height="10" viewBox="0 0 24 24" fill="#3d5d8c"><polygon points="6,3 20,12 6,21"/></svg>
                        </div>
                      </div>
                    ) : (
                      <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", fontSize: 11 }}>사진</div>
                    )}
                  </div>
                </div>
              );
            })}
            {visible.length < PAGE && Array.from({ length: PAGE - visible.length }).map(function(_, i) {
              return <div key={'empty-' + i} style={{ aspectRatio: "1" }}/>;
            })}
          </div>
        </div>

        <ArrowBtn direction="right" onClick={next} enabled={canNext}/>
      </div>

      {/* 페이지 인디케이터 */}
      {totalPages > 1 && (
        <div style={{ display: "flex", justifyContent: "center", gap: 5, marginTop: 10 }}>
          {Array.from({ length: totalPages }).map(function(_, i) {
            return (
              <button key={i}
                onClick={function() { var newOff = i * PAGE; goTo(newOff, newOff > offset ? 'left' : 'right'); }}
                style={{
                  width: i === currentPage ? 22 : 6, height: 6, borderRadius: 3,
                  background: i === currentPage ? "var(--primary, #4B749D)" : "var(--line, #ddd)",
                  border: "none", cursor: "pointer", padding: 0,
                  transition: "all 0.3s cubic-bezier(.34,1.56,.64,1)",
                }}/>
            );
          })}
        </div>
      )}
    </div>
  );
}


function SegyangGallery() {
  const [visible, setVisible] = React.useState(null);
  const [items, setItems] = React.useState([]);
  const [lightbox, setLightbox] = React.useState(null); // { item, allItems, idx }

  React.useEffect(() => {
    if (!window.firebase) return;
    const db = firebase.firestore();

    // 1) 갤러리 섹션 노출 여부
    db.collection("siteSettings").doc("gallery").get()
      .then(snap => setVisible(!snap.exists || snap.data().visible !== false))
      .catch(() => setVisible(true));

    // 2) isPublished=true 사진을 직접 조회 (orderBy 제거 → 복합 인덱스 불필요, 클라이언트 정렬)
    db.collection("galleryItems")
      .where("isPublished", "==", true)
      .limit(48)
      .get()
      .then(snap => {
        const list = snap.docs.map(d => ({ id: d.id, ...d.data() }));
        list.sort((a, b) => {
          const ta = a.uploadedAt ? (a.uploadedAt.seconds || 0) : 0;
          const tb = b.uploadedAt ? (b.uploadedAt.seconds || 0) : 0;
          return tb - ta;
        });
        setItems(list);
      })
      .catch(() => {});
  }, []);

  // 라이트박스 키보드 내비게이션
  React.useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => {
      if (e.key === "Escape") setLightbox(null);
      if (e.key === "ArrowRight") setLightbox(lb => {
        const next = (lb.idx + 1) % lb.allItems.length;
        return { ...lb, item: lb.allItems[next], idx: next };
      });
      if (e.key === "ArrowLeft") setLightbox(lb => {
        const prev = (lb.idx - 1 + lb.allItems.length) % lb.allItems.length;
        return { ...lb, item: lb.allItems[prev], idx: prev };
      });
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [!!lightbox]);

  if (visible === null || visible === false) return null;
  if (items.length === 0) return null;

  // 앨범별로 그룹화 (표시용)
  const byAlbum = {};
  items.forEach(it => {
    const key = it.albumName || "기타";
    if (!byAlbum[key]) byAlbum[key] = [];
    byAlbum[key].push(it);
  });
  const albumGroups = Object.entries(byAlbum);

  const openLightbox = (item, albumItems) => {
    const idx = albumItems.findIndex(i => i.id === item.id);
    setLightbox({ item, allItems: albumItems, idx });
  };

  return (
    <section id="gallery" style={{ padding: "72px 0", background: "var(--paper-2)", position: "relative", overflow: "hidden" }}>
      <div style={{ maxWidth: 1240, margin: "0 auto", padding: "0 32px" }}>
        <div style={{ marginBottom: 36 }}>
          <div className="eyebrow" style={{ color: "var(--mint-deep)", marginBottom: 6 }}>{window.getCopy ? window.getCopy("gallery.eyebrow") : "Gallery · 세광갤러리"}</div>
          <h2 style={{ fontSize: "clamp(28px,4vw,42px)", fontFamily: "var(--font-display)", fontWeight: 500, color: "var(--ink)", lineHeight: 1.2, margin: "0 0 6px" }}>
            {window.getCopy ? window.getCopy("gallery.title") : "함께한 소중한 순간들"}
          </h2>
          <p style={{ fontSize: 15, color: "var(--ink-3)", margin: 0 }}>
            {window.getCopy ? window.getCopy("gallery.desc") : "교회 가족과 나눈 은혜로운 시간을 기억합니다."}
          </p>
        </div>

        {/* 앨범 그룹별 표시 — 전체 항목 표시, 클릭 시 라이트박스 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 48 }}>
          {albumGroups.map(([albumName, albumItems]) => (
            <AlbumCarousel key={albumName} albumName={albumName} albumItems={albumItems} openLightbox={openLightbox}/>
          ))}
        </div>

        {/* 교인마당 바로가기 */}
        <div style={{ textAlign: "center", marginTop: 48 }}>
          <a href="community/community.html?goto=gallery" style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "12px 24px", borderRadius: 999,
            background: "var(--mint-deep)", color: "white",
            fontSize: 14, fontWeight: 600, textDecoration: "none",
          }}
            onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 6px 20px -6px rgba(78,164,159,0.5)"; }}
            onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}>
            교인마당에서 더 보기
          </a>
        </div>
      </div>

      {/* 라이트박스 */}
      {lightbox && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 9999,
          background: "rgba(0,0,0,0.92)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}
          onClick={() => setLightbox(null)}
          onTouchStart={(e) => { window._lbTouchX = e.touches[0].clientX; }}
          onTouchEnd={(e) => {
            var dx = e.changedTouches[0].clientX - (window._lbTouchX || 0);
            if (dx < -55) setLightbox(lb => { var n=(lb.idx+1)%lb.allItems.length; return {...lb,item:lb.allItems[n],idx:n}; });
            else if (dx > 55) setLightbox(lb => { var n=(lb.idx-1+lb.allItems.length)%lb.allItems.length; return {...lb,item:lb.allItems[n],idx:n}; });
          }}>
          {/* 닫기 버튼 */}
          <button onClick={() => setLightbox(null)} style={{
            position: "absolute", top: 20, right: 24,
            background: "rgba(255,255,255,0.12)", border: "none",
            color: "white", borderRadius: "50%", width: 44, height: 44,
            fontSize: 22, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
          }}>✕</button>

          {/* 이전 버튼 */}
          {lightbox.allItems.length > 1 && (
            <button onClick={(e) => { e.stopPropagation(); setLightbox(lb => { const prev = (lb.idx - 1 + lb.allItems.length) % lb.allItems.length; return { ...lb, item: lb.allItems[prev], idx: prev }; }); }} style={{
              position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)",
              background: "rgba(255,255,255,0.12)", border: "none", color: "white",
              borderRadius: "50%", width: 48, height: 48, fontSize: 22, cursor: "pointer",
            }}>‹</button>
          )}

          {/* 미디어 영역 */}
          <div style={{ maxWidth: "90vw", maxHeight: "85vh", display: "flex", flexDirection: "column", alignItems: "center" }}
            onClick={e => e.stopPropagation()}>
            {lightbox.item.fileType && lightbox.item.fileType.startsWith("video") ? (
              <video src={lightbox.item.downloadURL} controls autoPlay
                style={{ maxWidth: "90vw", maxHeight: "75vh", borderRadius: 12, background: "#000" }}
              />
            ) : (
              <img src={lightbox.item.driveFileId
                  ? 'https://drive.google.com/thumbnail?id=' + lightbox.item.driveFileId + '&sz=w1600'
                  : ((lightbox.item.driveViewUrl || lightbox.item.downloadURL || '').match(/[?&]id=([^&]+)/)
                    ? 'https://drive.google.com/thumbnail?id=' + (lightbox.item.driveViewUrl || lightbox.item.downloadURL || '').match(/[?&]id=([^&]+)/)[1] + '&sz=w1600'
                    : lightbox.item.downloadURL)}
                alt={lightbox.item.title || ""}
                style={{ maxWidth: "90vw", maxHeight: "75vh", borderRadius: 12, objectFit: "contain" }}/>
            )}
            {/* 캡션 */}
            {(lightbox.item.title || lightbox.item.albumName) && (
              <div style={{ marginTop: 14, color: "white", textAlign: "center" }}>
                {lightbox.item.title && <div style={{ fontSize: 16, fontWeight: 600 }}>{lightbox.item.title}</div>}
                {lightbox.item.albumName && <div style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", marginTop: 4 }}>{lightbox.item.albumName}</div>}
              </div>
            )}
            {/* 인덱스 표시 */}
            <div style={{ marginTop: 10, fontSize: 12, color: "rgba(255,255,255,0.45)" }}>
              {lightbox.idx + 1} / {lightbox.allItems.length}
            </div>
          </div>

          {/* 다음 버튼 */}
          {lightbox.allItems.length > 1 && (
            <button onClick={(e) => { e.stopPropagation(); setLightbox(lb => { const next = (lb.idx + 1) % lb.allItems.length; return { ...lb, item: lb.allItems[next], idx: next }; }); }} style={{
              position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)",
              background: "rgba(255,255,255,0.12)", border: "none", color: "white",
              borderRadius: "50%", width: 48, height: 48, fontSize: 22, cursor: "pointer",
            }}>›</button>
          )}
        </div>
      )}

      <style>{`
        @media (max-width: 600px) {
          #gallery { padding: 60px 0 !important; }
          #gallery > div { padding: 0 16px !important; }
        }
      `}</style>
    </section>
  );
}

function ClassicFooter() {
  const c = window.CHURCH;
  return (
    <footer style={{ background: "var(--paper-3)", padding: "32px 0 14px", borderTop: "1px solid var(--line-2)" }}>
      <div className="container" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 32 }}>
        <div>
          <img src={(window.getCopy && window.getCopy("footer.logoImg")) || "assets/logo-blue.png"} alt="맑은빛 세광교회" style={{ height: 80, width: "auto", display: "block" }}/>
          <p style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--ink-3)", marginTop: 12, marginBottom: 0, lineHeight: 1.7 }}>
            {c.denomination}<br />
            창립 {c.founded}
          </p>
        </div>
        <div className="footer-info-col" style={{ fontFamily: "var(--font-sans)", fontSize: 13 }}>
          <div style={{ fontWeight: 700, marginBottom: 12 }}>예배</div>
          <div style={{ color: "var(--ink-3)", lineHeight: 2 }}>
            {(function(){
              const gc = window.getCopy;
              const t = gc ? gc("footer.worship") : "";
              if (t) { const lines = t.split("\n"); return <React.Fragment>{lines[0]}{lines[1] ? <React.Fragment><br />{lines[1]}</React.Fragment> : null}</React.Fragment>; }
              return <React.Fragment>주일 9:30 / 11:00<br />수요 10:30 / 아침 5:30</React.Fragment>;
            })()}
          </div>
        </div>
        <div className="footer-info-col" style={{ fontFamily: "var(--font-sans)", fontSize: 13 }}>
          <div style={{ fontWeight: 700, marginBottom: 12 }}>연락</div>
          <div style={{ color: "var(--ink-3)", lineHeight: 2 }}>
            {c.phone}<br />
            {c.email}
          </div>
        </div>
        <div className="footer-info-col" style={{ fontFamily: "var(--font-sans)", fontSize: 13 }}>
          <div style={{ fontWeight: 700, marginBottom: 12 }}>온라인</div>
          <div style={{ color: "var(--ink-3)", lineHeight: 2 }}>
            YouTube · {c.youtube}<br />
            {c.domain}
          </div>
        </div>
      </div>
      <div className="container" style={{ marginTop: 14, paddingTop: 10, borderTop: "1px solid var(--line-2)", fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--ink-3)", display: "flex", justifyContent: "space-between", flexWrap: "wrap" }}>
        <div>© 2026 맑은빛 세광교회 · Heallight Church</div>
        <div>{window.getCopy ? window.getCopy("footer.tagline") : "주를 알고, 주를 알리며, 주와 함께"}</div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          footer > .container { grid-template-columns: 1fr 1fr !important; }
          footer > .container > .footer-info-col {
            padding-top: 0 !important;
            align-self: end !important;
            margin-top: auto !important;
          }
        }
        @media (max-width: 380px) {
          footer > .container { grid-template-columns: 1fr !important; gap: 18px !important; }
          footer > .container > .footer-info-col {
            margin-top: 0 !important;
          }
        }
      `}</style>
    </footer>);

}

function VariantClassic() {
  const [ytIsLive, setYtIsLive] = React.useState(null);
  React.useEffect(() => {
    const check = () => {
      fetch(`https://www.googleapis.com/youtube/v3/search?key=${YT_API_KEY}&channelId=${YT_CHANNEL_ID}&part=snippet&eventType=live&type=video`)
        .then(r => r.json())
        .then(data => {
          if (data.error) { setYtIsLive(null); return; }
          setYtIsLive(!!(data.items && data.items.length > 0));
        })
        .catch(() => setYtIsLive(null));
    };
    check();
    const t = setInterval(check, 120000); // 2분마다
    return () => clearInterval(t);
  }, []);
  // YouTube API 실패(null) 시 현재 시간 기반으로 예배 시간대 판단
  const _timeBasedLive = (() => {
    const now = new Date();
    const day = now.getDay(); // 0=일, 1=월...
    const tot = now.getHours() * 60 + now.getMinutes();
    // 아침예배: 월~금 05:15~07:00
    if (day >= 1 && day <= 5 && tot >= 315 && tot < 420) return true;
    // 수요예배: 수요일 10:15~12:00
    if (day === 3 && tot >= 615 && tot < 720) return true;
    // 주일2부예배: 일요일 09:15~11:00
    if (day === 0 && tot >= 555 && tot < 660) return true;
    return false;
  })();
  // API 결과 우선, null이면 시간 기반 사용
  const effectiveLive = ytIsLive !== null ? ytIsLive : (_timeBasedLive ? true : false);
  return (
    <div style={{ background: "var(--paper)" }}>
      <ClassicNav />
      <main>
        <ClassicHero isLive={effectiveLive} />
        <ClassicMission />
        <ClassicAbout />
        <ClassicWorship />
        <ClassicThisWeek isLive={effectiveLive} />
        <ClassicMedia isLive={effectiveLive} />
        <ClassicBulletin />
        <ClassicPrayer />
        <ClassicVisit />
        <SegyangGallery />
      </main>
      <ClassicFooter />
    </div>);

}

Object.assign(window, { VariantClassic });
