// MSECM Sections
const { useState, useEffect, useRef, useMemo } = React;

// 한국어 조사 자동 선택 — 단어 마지막 글자의 받침 유무로 결정.
// 한글 음절은 (초성×21+중성)×28+종성 구조라 (코드-0xAC00)%28 === 0 이면 받침 없음.
// 예: josa('교육','을','를') → '을' (육=받침○),  josa('콘텐츠','을','를') → '를' (츠=받침✗)
function josa(word, withBatchim, withoutBatchim) {
  if (!word) return withoutBatchim;
  const code = word.charCodeAt(word.length - 1);
  if (code < 0xac00 || code > 0xd7a3) return withoutBatchim; // 한글 음절 아니면 기본
  const hasBatchim = (code - 0xac00) % 28 !== 0;
  return hasBatchim ? withBatchim : withoutBatchim;
}

function SectionLabel({ theme, index, label, color, accentColor }) {
  const ac = accentColor || theme.accent;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12, letterSpacing: '.18em', textTransform: 'uppercase', fontWeight: 600, color: color || theme.inkSub, whiteSpace: 'nowrap' }}>
      <span style={{ display: 'inline-block', width: 24, height: 1, background: ac, flexShrink: 0 }}></span>
      <span style={{ color: ac, fontVariantNumeric: 'tabular-nums' }}>{index}</span>
      <span>{label}</span>
    </div>
  );
}

// HERO with scroll-driven word morph
function Hero({ theme, scrollY }) {
  const words = window.MSECM_DATA.heroWords;
  const sectionH = 600 * 7;
  const progress = Math.max(0, Math.min(1, scrollY / sectionH));
  const stepRaw = progress * words.length;
  const step = Math.min(Math.floor(stepRaw), words.length - 1);
  const subProg = Math.min(1, Math.max(0, stepRaw - step));
  const phase = subProg < 0.5 ? 'exit' : 'enter';
  const phaseProg = phase === 'exit' ? subProg * 2 : (subProg - 0.5) * 2;
  const shown = phase === 'exit' ? words[step] : words[Math.min(step + 1, words.length - 1)];
  const chars = [...shown];

  return (
    <section data-screen-label="01 Hero" data-bg-id="hero" style={{ position: 'relative', height: sectionH, color: theme.ink }}>
      <div style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          backgroundImage: `linear-gradient(${theme.gridLine} 1px, transparent 1px), linear-gradient(90deg, ${theme.gridLine} 1px, transparent 1px)`,
          backgroundSize: '80px 80px',
          maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
          WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
          opacity: 0.5,
        }}/>
        <div aria-hidden style={{
          position: 'absolute', width: '60vw', height: '60vw', borderRadius: '50%',
          background: `radial-gradient(circle, ${theme.glow} 0%, transparent 60%)`,
          left: '50%', top: '50%',
          transform: `translate(-50%, -50%) translate(${Math.sin(progress * 6) * 80}px, ${Math.cos(progress * 6) * 40}px)`,
          filter: 'blur(40px)', opacity: .7, transition: 'transform .6s ease-out',
        }}/>

        <div style={{ position: 'relative', textAlign: 'center', maxWidth: 1200, padding: '0 40px', zIndex: 2 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '7px 14px 7px 12px', borderRadius: 999,
            background: theme.chipBg, border: `0.5px solid ${theme.chipBorder}`,
            fontSize: 12.5, fontWeight: 500, color: theme.inkSub, marginBottom: 36, letterSpacing: '-.005em',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: theme.accent, flexShrink: 0 }}></span>
            <span style={{ whiteSpace: 'nowrap' }}>MSECM · 2008년부터 18년, 경남과 함께합니다</span>
          </div>
          <h1 style={{ fontSize: 'clamp(48px, 7.5vw, 108px)', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1.02, margin: 0, color: theme.ink }}>
            좋은 연결로<br/>
            <span style={{ display: 'inline-block', position: 'relative', minWidth: '5ch' }}>
              {chars.map((ch, i) => {
                const stagger = i / Math.max(chars.length, 1) * 0.6;
                const local = Math.max(0, Math.min(1, (phaseProg - stagger) / 0.4));
                const o = phase === 'exit' ? 1 - local : local;
                const ty = phase === 'exit' ? local * -30 : (1 - local) * 30;
                return (
                  <span key={i + ch + phase} style={{
                    display: 'inline-block', color: theme.accent, opacity: o,
                    transform: `translateY(${ty}px)`,
                    transition: 'opacity .15s linear, transform .15s linear',
                    whiteSpace: 'pre',
                  }}>{ch === ' ' ? '\u00A0' : ch}</span>
                );
              })}
            </span><br/>
            {josa(shown, '을', '를')} 다시 정의합니다.
          </h1>
          <p style={{ fontSize: 'clamp(16px, 1.5vw, 21px)', color: theme.inkSub, marginTop: 36, maxWidth: 640, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.55, letterSpacing: '-.005em' }}>
            경상남도 교육·위탁운영 NO.1 파트너. 공무원·시민·교원을 위한 실질적 역량을 설계합니다.
          </p>
          <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 56 }}>
            {words.map((w, i) => (
              <div key={i} style={{
                width: i === step ? 24 : 6, height: 6, borderRadius: 3,
                background: i === step ? theme.accent : theme.dotIdle,
                transition: 'width .35s cubic-bezier(.2,.8,.2,1), background .25s',
              }}/>
            ))}
          </div>
          <div style={{
            position: 'absolute', bottom: -180, left: '50%', transform: 'translateX(-50%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
            color: theme.inkSub, fontSize: 11, letterSpacing: '.15em', textTransform: 'uppercase',
            opacity: Math.max(0, 1 - progress * 5),
          }}>
            <span>Scroll</span>
            <div style={{ width: 1, height: 36, background: `linear-gradient(${theme.inkSub}, transparent)` }}/>
          </div>
        </div>
      </div>
    </section>
  );
}

// 회사 브로슈어에서 추출한 실제 사업 현장 사진. 각 사업 영역에 매핑.
const CAPABILITY_IMAGES = {
  'E': '/assets/cap-education.jpg',  // 회의·토론
  'C': '/assets/cap-contents.jpg',   // 강의실 참여형 교육
  'M': '/assets/cap-management.jpg', // 발표 강사 (운영 현장)
  '+': '/assets/cap-gn_partner.jpg', // 야외 활동 (경남 지역)
};

function Capabilities({ theme }) {
  const isMobile = window.useIsMobile();
  return (
    <section id="sec-capabilities" data-screen-label="02 Capabilities" data-bg-id="capabilities" style={{ color: theme.inkOnDeep, padding: isMobile ? '100px 16px' : '160px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionLabel theme={theme} index="01" label="Capabilities" color={theme.inkOnDeepSub} accentColor={theme.accentOnDeep} />
        <h2 data-anim="up" style={{ fontSize: 'clamp(28px, 5vw, 72px)', fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.1, margin: isMobile ? '20px 0 56px' : '24px 0 96px', maxWidth: 980 }}>
          E.C.M. — 교육과 콘텐츠, <span style={{ whiteSpace: 'nowrap' }}>그리고 운영.</span><br/>
          <span style={{ color: theme.accentOnDeep }}>세 개의 축</span>으로 움직입니다.
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 1, background: theme.divOnDeep, border: `0.5px solid ${theme.divOnDeep}` }}>
          {window.MSECM_DATA.capabilities.map((c) => (
            <div key={c.num} style={{ background: 'rgba(255,255,255,.02)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              {/* 셀 상단 이미지 — 16:9 비율, 살짝 어두운 그라데이션으로 텍스트 영역과 부드럽게 연결 */}
              <div style={{ aspectRatio: '16/9', position: 'relative', overflow: 'hidden', background: '#0a1f44' }}>
                <img
                  src={CAPABILITY_IMAGES[c.num]}
                  alt=""
                  loading="lazy"
                  style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
                />
                <div aria-hidden style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, transparent 55%, rgba(10,31,68,.55))',
                  pointerEvents: 'none',
                }}/>
              </div>
              {/* 텍스트 영역 */}
              <div style={{ padding: isMobile ? '32px 28px 40px' : '40px 48px 56px', display: 'flex', flexDirection: 'column', flex: 1 }}>
                <div style={{
                  fontSize: 14, fontWeight: 700, letterSpacing: '.04em', marginBottom: 24,
                  color: theme.inkOnDeep,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  width: 36, height: 36, borderRadius: 999,
                  background: 'rgba(255,255,255,.08)',
                  border: '0.5px solid rgba(255,255,255,.15)',
                }}>{c.num}</div>
                <h3 style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.025em', margin: 0, lineHeight: 1.2 }}>{c.title}</h3>
                <p style={{ fontSize: 15.5, lineHeight: 1.7, color: theme.inkOnDeepSub, marginTop: 16, letterSpacing: '-.005em' }}>{c.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function News({ theme }) {
  const isMobile = window.useIsMobile();
  const fallback = window.MSECM_DATA.news;
  const [news, setNews] = useState(fallback);
  const [status, setStatus] = useState('idle'); // 'idle' | 'loading' | 'live' | 'fallback'
  const [lastSync, setLastSync] = useState(null);
  const [now, setNow] = useState(new Date());
  useEffect(() => { const t = setInterval(() => setNow(new Date()), 60000); return () => clearInterval(t); }, []);

  useEffect(() => {
    let cancelled = false;
    setStatus('loading');
    // cache: 'no-store' — 클라이언트 캐시는 우회. 서버(Vercel Edge)가 s-maxage로 캐시하므로 충분.
    fetch('/api/news', { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then(data => {
        if (cancelled) return;
        if (data.items && data.items.length > 0) {
          // API 응답 아이템 수가 적으면 fallback으로 빈자리 채움 (레이아웃은 8칸 고정)
          const merged = [...data.items, ...fallback].slice(0, 8);
          setNews(merged);
          setStatus('live');
          setLastSync(new Date(data.fetchedAt));
        } else {
          setStatus('fallback');
        }
      })
      .catch(() => { if (!cancelled) setStatus('fallback'); });
    return () => { cancelled = true; };
  }, []);

  const time = (lastSync || now).toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' });
  const liveLabel = status === 'live'
    ? `LIVE · 마지막 동기화 ${time}`
    : status === 'loading'
      ? '동기화 중…'
      : `미리보기 · ${time}`;
  const dotColor = status === 'live' ? '#22c55e' : status === 'loading' ? '#f59e0b' : 'rgba(10,23,41,.3)';

  return (
    <section id="sec-news" data-screen-label="03 News" data-bg-id="news" style={{ color: theme.ink, padding: isMobile ? '100px 16px' : '160px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 56, flexWrap:'wrap', gap: 20 }}>
          <div>
            <SectionLabel theme={theme} index="02" label="Industry News" />
            <h2 data-anim="up" style={{ fontSize: 'clamp(36px, 4.5vw, 60px)', fontWeight: 700, letterSpacing: '-.03em', margin: '20px 0 0', lineHeight: 1.1 }}>
              교육·디지털 산업, <span style={{ color: theme.accent }}>지금 이 순간</span>.
            </h2>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap: 10, fontSize: 13, color: theme.inkSub, fontVariantNumeric:'tabular-nums', whiteSpace: 'nowrap' }}>
            <span style={{
              width:8, height:8, borderRadius:'50%', background: dotColor,
              boxShadow: status === 'live' ? '0 0 12px rgba(34,197,94,.6)' : 'none',
              flexShrink: 0,
              animation: status === 'loading' ? 'msecmPulse 1.2s ease-in-out infinite' : 'none',
            }}></span>
            {liveLabel}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(12, 1fr)', gap: isMobile ? 14 : 20 }}>
          <NewsCard variant={isMobile ? 'side' : 'feature'} item={news[0]} theme={theme} isMobile={isMobile} />
          {news.slice(1, 5).map((n, i) => (
            <NewsCard key={`s-${i}`} variant="side" item={n} theme={theme} isMobile={isMobile} />
          ))}
          {news.slice(5).map((n, i) => (
            <NewsCard key={`b-${i}`} variant={isMobile ? 'side' : 'bottom'} item={n} theme={theme} isMobile={isMobile} />
          ))}
        </div>
      </div>
      <style>{`@keyframes msecmPulse{0%,100%{opacity:.4;transform:scale(1)}50%{opacity:1;transform:scale(1.2)}}`}</style>
    </section>
  );
}

// 카드 변형은 3가지 — feature(특집, 6열×2행), side(사이드, 3열), bottom(하단, 4열).
// link가 있는 RSS 아이템은 <a>로 감싸 새 탭으로 원문 이동.
function NewsCard({ variant, item, theme, isMobile }) {
  const wrap = (child, extraStyle = {}) => {
    const baseStyle = { textDecoration: 'none', color: 'inherit', display: 'block', ...extraStyle };
    return item?.link
      ? <a href={item.link} target="_blank" rel="noopener noreferrer" style={baseStyle}>{child}</a>
      : <div style={baseStyle}>{child}</div>;
  };

  if (variant === 'feature') {
    return wrap(
      <article style={{ background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 20, overflow: 'hidden', display:'flex', flexDirection:'column', height: '100%' }}>
        {/* 시각 영역 — 이미지 있으면 사진 cover + 어두운 오버레이, 없으면 색상 그라데이션 */}
        <div style={{ flex: 1, minHeight: 360, padding: '32px 36px', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', background: item.image ? '#0a1f44' : `linear-gradient(135deg, ${item.img} 0%, ${theme.accent} 100%)` }}>
          {item.image && (
            <img src={item.image} alt="" loading="lazy" referrerPolicy="no-referrer"
              onError={(e) => { e.currentTarget.style.display = 'none'; }}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          )}
          {/* 가독성 그라데이션 오버레이 — 위·아래 어둡게 */}
          <div aria-hidden style={{ position: 'absolute', inset: 0, background: item.image ? 'linear-gradient(180deg, rgba(8,18,40,.45) 0%, rgba(8,18,40,.15) 35%, rgba(8,18,40,.85) 100%)' : 'radial-gradient(circle at 70% 30%, rgba(255,255,255,.25), transparent 60%)', pointerEvents: 'none' }}/>
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 10 }}>
            <span style={{ color: 'rgba(255,255,255,.92)', fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', fontWeight: 600 }}>{item.cat}</span>
            <span style={{ color: 'rgba(255,255,255,.78)', fontSize: 13, fontWeight: 500, display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ fontWeight: 600, color: 'rgba(255,255,255,.95)' }}>{item.source}</span>
              <span>·</span>
              <span style={{ fontVariantNumeric: 'tabular-nums' }}>{item.time}</span>
            </span>
          </div>
          <h3 style={{ position: 'relative', fontSize: 'clamp(24px, 2.4vw, 34px)', fontWeight: 700, color: '#fff', letterSpacing: '-.028em', lineHeight: 1.25, margin: 0, textShadow: '0 1px 6px rgba(0,0,0,.35)' }}>{item.title}</h3>
        </div>
        {item.summary && (
          <div style={{ padding: '20px 30px 26px' }}>
            <p style={{ fontSize: 15, color: theme.inkSub, lineHeight: 1.65, margin: 0 }}>{item.summary}</p>
          </div>
        )}
      </article>,
      isMobile ? {} : { gridColumn: 'span 6', gridRow: 'span 2' }
    );
  }

  if (variant === 'side') {
    return wrap(
      <article data-anim="up" style={{ background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 180, height: '100%' }}>
        {item.image && (
          <div style={{ aspectRatio: '16/9', overflow: 'hidden', background: item.img }}>
            <img src={item.image} alt="" loading="lazy" referrerPolicy="no-referrer"
              onError={(e) => { e.currentTarget.parentElement.style.display = 'none'; }}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          </div>
        )}
        <div style={{ padding: '16px 20px 18px', display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 22, height: 22, borderRadius: 5, background: item.img, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 9.5, fontWeight: 700 }}>{item.source.charAt(0)}</span>
            <span style={{ fontSize: 12, fontWeight: 600, color: theme.ink }}>{item.source}</span>
            <span style={{ fontSize: 11, color: theme.inkSub, marginLeft: 'auto' }}>{item.time}</span>
          </div>
          <h3 style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-.015em', lineHeight: 1.4, margin: 0, color: theme.ink, flex: 1, display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{item.title}</h3>
          <div style={{ fontSize: 10.5, letterSpacing: '.1em', textTransform: 'uppercase', color: theme.accent, fontWeight: 600 }}>{item.cat}</div>
        </div>
      </article>,
      isMobile ? {} : { gridColumn: 'span 3' }
    );
  }

  // bottom
  return wrap(
    <article data-anim="up" style={{ background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{ width: 64, height: 64, borderRadius: 12, overflow: 'hidden', flexShrink: 0, background: item.image ? '#0a1f44' : `linear-gradient(135deg, ${item.img}, ${theme.accent})`, position: 'relative' }}>
        {item.image && (
          <img src={item.image} alt="" loading="lazy" referrerPolicy="no-referrer"
            onError={(e) => { e.currentTarget.style.display = 'none'; }}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        )}
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11, color: theme.inkSub, display:'flex', gap: 8 }}>
          <span style={{ fontWeight: 600 }}>{item.source}</span><span>·</span><span>{item.time}</span>
        </div>
        <h3 style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-.01em', lineHeight: 1.4, margin: '4px 0 0', color: theme.ink, display:'-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient:'vertical', overflow:'hidden' }}>{item.title}</h3>
      </div>
    </article>,
    isMobile ? {} : { gridColumn: 'span 4' }
  );
}

function Blog({ theme }) {
  const isMobile = window.useIsMobile();
  const fallback = window.MSECM_DATA.blogTopics;
  const [topics, setTopics] = useState(fallback);
  const [status, setStatus] = useState('idle'); // 'loading' | 'live' | 'fallback'
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [progress, setProgress] = useState(0);

  // 네이버 블로그 자체 RSS에서 라이브 가져오기 — 운영자가 글 발행하면 자동 반영
  useEffect(() => {
    let cancelled = false;
    setStatus('loading');
    fetch('/api/insights', { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then(data => {
        if (cancelled) return;
        if (data.topics && data.topics.length > 0) {
          setTopics(data.topics);
          setStatus('live');
          setIdx(0);
        } else {
          setStatus('fallback');
        }
      })
      .catch(() => { if (!cancelled) setStatus('fallback'); });
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (paused) return;
    const tick = 50, dur = 6000;
    const t = setInterval(() => {
      setProgress(p => {
        const next = p + tick / dur;
        if (next >= 1) { setIdx(i => (i + 1) % topics.length); return 0; }
        return next;
      });
    }, tick);
    return () => clearInterval(t);
  }, [paused, topics.length]);
  const t = topics[idx] || topics[0];
  if (!t) return null;

  return (
    <section id="sec-blog" data-screen-label="04 Blog" data-bg-id="blog" style={{ color: theme.inkOnDeep, padding: isMobile ? '100px 16px' : '160px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 20, marginBottom: 0 }}>
          <div>
            <SectionLabel theme={theme} color={theme.inkOnDeepSub} accentColor={theme.accentOnDeep} index="03" label="MSECM Lab — Insights" />
            <h2 data-anim="up" style={{ fontSize: 'clamp(36px, 4.5vw, 60px)', fontWeight: 700, letterSpacing: '-.03em', margin: '20px 0 0', lineHeight: 1.1, maxWidth: 880 }}>
              교육·운영 현장의<br/>
              <span style={{ color: theme.accentOnDeep }}>살아있는 기록</span>을 공유합니다.
            </h2>
          </div>
          {status === 'live' && (
            <a href="https://blog.naver.com/ms_ecm" target="_blank" rel="noopener noreferrer" style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: theme.inkOnDeepSub,
              textDecoration: 'none', whiteSpace: 'nowrap',
            }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#22c55e', boxShadow: '0 0 12px rgba(34,197,94,.6)' }}/>
              blog.naver.com/ms_ecm
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M7 17L17 7M9 7h8v8"/></svg>
            </a>
          )}
        </div>
        <div style={{ marginBottom: 56 }}></div>
        <div style={{ display: 'flex', gap: 4, marginBottom: 48, flexWrap: 'wrap' }} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
          {topics.map((top, i) => {
            const active = i === idx;
            return (
              <button key={top.key} onClick={() => { setIdx(i); setProgress(0); }} style={{
                position: 'relative', padding: '14px 22px', borderRadius: 12,
                border: `0.5px solid ${active ? theme.accent : theme.divOnDeep}`,
                background: active ? 'rgba(59,130,246,.12)' : 'transparent',
                color: active ? theme.inkOnDeep : theme.inkOnDeepSub,
                fontSize: 14, fontWeight: active ? 600 : 500, letterSpacing: '-.005em',
                cursor: 'pointer', fontFamily: 'inherit', overflow: 'hidden',
                transition: 'all .3s cubic-bezier(.2,.8,.2,1)', whiteSpace: 'nowrap',
              }}>
                {top.label}
                {active && (
                  <span style={{ position: 'absolute', left: 0, bottom: 0, height: 2, width: `${progress * 100}%`, background: theme.accent, transition: 'width .05s linear' }}/>
                )}
              </button>
            );
          })}
        </div>
        <div key={t.key} style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 14 : 20, animation: 'msecmFadeIn .55s cubic-bezier(.2,.8,.2,1) both' }}>
          {t.posts.map((p, i) => {
            const cardInner = (
            <article style={{
              background: theme.cardOnDeep, borderRadius: 18,
              border: `0.5px solid ${theme.divOnDeep}`,
              display: 'flex', flexDirection: 'column',
              position: 'relative', overflow: 'hidden',
              animationDelay: `${i * 60}ms`,
              height: '100%',
            }}>
              {/* 썸네일: img 태그 + referrerpolicy='no-referrer'로 네이버 CDN referer 차단 우회.
                  배경 그라데이션은 이미지 로드 전/실패 시 placeholder 역할. */}
              <div style={{
                aspectRatio: '16/9',
                background: `linear-gradient(135deg, ${t.color} 0%, ${theme.accent} 100%)`,
                position: 'relative', overflow: 'hidden',
              }}>
                {p.thumbnail && (
                  <img
                    src={p.thumbnail}
                    alt=""
                    referrerPolicy="no-referrer"
                    loading="lazy"
                    style={{
                      position: 'absolute', inset: 0, width: '100%', height: '100%',
                      objectFit: 'cover', display: 'block',
                    }}
                  />
                )}
                {!p.thumbnail && (
                  <div aria-hidden style={{
                    position: 'absolute', inset: 0,
                    backgroundImage: 'radial-gradient(circle at 70% 30%, rgba(255,255,255,.22), transparent 60%)',
                  }}/>
                )}
              </div>
              <div style={{ padding: '24px 24px 26px', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <span style={{
                    fontSize: 10.5, letterSpacing: '.12em', fontWeight: 600,
                    color: theme.inkOnDeep,
                    background: 'rgba(255,255,255,.08)',
                    padding: '5px 10px',
                    border: '0.5px solid rgba(255,255,255,.15)',
                    borderRadius: 999, whiteSpace: 'nowrap',
                  }}>{p.tag}</span>
                  <span style={{ fontSize: 12, color: theme.inkOnDeepSub, whiteSpace: 'nowrap' }}>{p.read}</span>
                </div>
                <h3 style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-.015em', lineHeight: 1.4, margin: 0, color: theme.inkOnDeep, flex: 1 }}>{p.title}</h3>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end' }}>
                  <span style={{ fontSize: 12.5, color: theme.inkOnDeepSub, fontVariantNumeric:'tabular-nums' }}>{p.date}</span>
                  <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(255,255,255,.06)', border: `0.5px solid ${theme.divOnDeep}`, display:'inline-flex', alignItems:'center', justifyContent:'center', color: theme.inkOnDeep }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M7 17L17 7M9 7h8v8"/></svg>
                  </span>
                </div>
              </div>
            </article>
            );
            return p.link
              ? <a key={i} href={p.link} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', color: 'inherit', display: 'block' }}>{cardInner}</a>
              : <div key={i}>{cardInner}</div>;
          })}
        </div>
      </div>
      <style>{`@keyframes msecmFadeIn{0%{opacity:0;transform:translateY(12px)}100%{opacity:1;transform:translateY(0)}}`}</style>
    </section>
  );
}

function Portfolio({ theme }) {
  const isMobile = window.useIsMobile();
  const tl = window.MSECM_DATA.timeline;
  return (
    <section id="sec-portfolio" data-screen-label="05 Portfolio" data-bg-id="portfolio" style={{ color: theme.ink, padding: isMobile ? '100px 16px' : '160px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionLabel theme={theme} index="04" label="Track Record" />
        <h2 data-anim="up" style={{ fontSize: 'clamp(28px, 4.5vw, 60px)', fontWeight: 700, letterSpacing: '-.03em', margin: '20px 0 16px', lineHeight: 1.1, maxWidth: 980 }}>
          18년간 경남과 함께한<br/>
          <span style={{ color: theme.accent }}>발자취</span>입니다.
        </h2>
        <p style={{ fontSize: isMobile ? 15 : 17, color: theme.inkSub, maxWidth: 640, lineHeight: 1.6, marginBottom: isMobile ? 56 : 80 }}>
          경상남도청·교육청·시·군, 공공시설 위탁운영까지 — 매해 더 큰 조직과 더 본질적인 변화에 참여해왔습니다.
        </p>
        <div style={{ position: 'relative' }}>
          {!isMobile && <div style={{ position: 'absolute', left: 120, top: 0, bottom: 0, width: 1, background: theme.divLine }}/>}
          {tl.map((row, ri) => (
            <div key={row.year} style={{
              display: isMobile ? 'block' : 'grid',
              gridTemplateColumns: isMobile ? undefined : '120px 1fr',
              gap: isMobile ? undefined : 40,
              paddingBottom: isMobile ? 40 : 56,
              position: 'relative',
            }}>
              <div style={{
                fontSize: isMobile ? 32 : 'clamp(28px, 3vw, 44px)',
                fontWeight: 700, letterSpacing: '-.02em',
                color: ri === 0 ? theme.accent : theme.ink,
                fontVariantNumeric: 'tabular-nums', lineHeight: 1,
                marginBottom: isMobile ? 16 : 0,
              }}>{row.year}</div>
              {!isMobile && (
                <div style={{ position: 'absolute', left: 116, top: 12, width: 9, height: 9, borderRadius: '50%', background: ri === 0 ? theme.accent : theme.ink, boxShadow: `0 0 0 4px ${theme.bgLight}`, zIndex: 1 }}/>
              )}
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(auto-fill, minmax(280px, 1fr))', gap: isMobile ? 10 : 14 }}>
                {row.items.map((it, i) => (
                  <div key={i} style={{ padding: '20px 22px', background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 14 }}>
                    <div style={{ fontSize: 11, letterSpacing: '.1em', fontWeight: 600, color: theme.accent, textTransform: 'uppercase' }}>CLIENT</div>
                    <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-.015em', marginTop: 6, marginBottom: 8 }}>{it.client}</div>
                    <div style={{ fontSize: 13.5, color: theme.inkSub, lineHeight: 1.5 }}>{it.label}</div>
                    <div style={{ fontSize: 12, color: theme.ink, marginTop: 10, fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>{it.scale}</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function iconBtn(theme) {
  return { width: 32, height: 32, borderRadius: 10, border: `0.5px solid ${theme.divLine}`, background: 'transparent', color: theme.ink, cursor: 'pointer', display:'inline-flex', alignItems:'center', justifyContent:'center' };
}

function Materials({ theme }) {
  const isMobile = window.useIsMobile();
  const mats = window.MSECM_DATA.materials;
  return (
    <section id="sec-materials" data-screen-label="06 Materials" data-bg-id="materials" style={{ color: theme.ink, padding: isMobile ? '100px 16px' : '160px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 64, flexWrap:'wrap', gap: 30 }}>
          <div>
            <SectionLabel theme={theme} index="05" label="Free Resources" />
            <h2 data-anim="up" style={{ fontSize: 'clamp(36px, 4.5vw, 60px)', fontWeight: 700, letterSpacing: '-.03em', margin: '20px 0 0', lineHeight: 1.1 }}>
              모든 자료, <span style={{ color: theme.accent }}>무료로</span> 가져가십시오.
            </h2>
          </div>
          <p style={{ fontSize: 16, color: theme.inkSub, lineHeight: 1.6, maxWidth: 360 }}>
            18년간 축적한 공무원·시민 교육과 공공시설 운영 노하우를 eBook·워크북으로 정리했습니다. 가입 없이 다운로드, 자유롭게 공유 가능합니다.
          </p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(290px, 1fr))', gap: 18 }}>
          {mats.map((m, i) => (
            <article key={i} data-anim="up" style={{ background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 18, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              <div style={{ aspectRatio: '4/3', position: 'relative', background: `linear-gradient(135deg, ${m.color}, ${theme.accent})`, color: '#fff', padding: 24, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
                  <span style={{ fontSize: 10.5, letterSpacing: '.15em', textTransform:'uppercase', fontWeight: 600, opacity: .85 }}>{m.type}</span>
                  {m.tag && <span style={{ fontSize: 10, letterSpacing: '.12em', fontWeight: 700, background: 'rgba(255,255,255,.18)', backdropFilter: 'blur(8px)', padding: '4px 8px', borderRadius: 999 }}>{m.tag}</span>}
                </div>
                <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-.015em', lineHeight: 1.3, textShadow: '0 1px 2px rgba(0,0,0,.1)' }}>{m.title}</div>
                <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(45deg, transparent 0 14px, rgba(255,255,255,.03) 14px 15px)', pointerEvents:'none' }}/>
              </div>
              <div style={{ padding: '18px 22px', display: 'flex', alignItems:'center', justifyContent:'space-between' }}>
                <div style={{ fontSize: 12.5, color: theme.inkSub }}>{m.pages}p · {m.dl} downloads</div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button style={iconBtn(theme)} aria-label="다운로드">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
                  </button>
                  <button style={iconBtn(theme)} aria-label="공유">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.6" y1="13.5" x2="15.4" y2="17.5"/><line x1="15.4" y1="6.5" x2="8.6" y2="10.5"/></svg>
                  </button>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function Stats({ theme }) {
  const isMobile = window.useIsMobile();
  const stats = window.MSECM_DATA.stats;
  return (
    <section data-screen-label="07 Stats" data-bg-id="stats" style={{ color: theme.inkOnDeep, padding: isMobile ? '80px 16px' : '140px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: isMobile ? 1 : 0, background: isMobile ? theme.divOnDeep : 'transparent' }}>
          {stats.map((s, i) => (
            <div key={i} style={{
              padding: isMobile ? '24px 20px' : '36px 32px',
              borderLeft: !isMobile && i > 0 ? `0.5px solid ${theme.divOnDeep}` : 'none',
              background: isMobile ? 'rgba(255,255,255,.02)' : 'transparent',
            }}>
              <div style={{ fontSize: isMobile ? 36 : 'clamp(48px, 6vw, 88px)', fontWeight: 700, letterSpacing: '-.04em', lineHeight: 1, color: theme.accentOnDeep, fontVariantNumeric: 'tabular-nums' }}>{s.v}</div>
              <div style={{ fontSize: 13, color: theme.inkOnDeep, marginTop: isMobile ? 10 : 18, lineHeight: 1.5, letterSpacing: '-.005em' }}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Clients({ theme }) {
  const logos = window.MSECM_DATA.clients;
  const row = [...logos, ...logos];
  return (
    <section data-screen-label="08 Clients" data-bg-id="clients" style={{ color: theme.ink, padding: '120px 0', overflow: 'hidden' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto 56px', padding: '0 40px' }}>
        <SectionLabel theme={theme} index="06" label="Partners & Clients" />
        <h2 data-anim="up" style={{ fontSize: 'clamp(32px, 4vw, 52px)', fontWeight: 700, letterSpacing: '-.03em', margin: '20px 0 0', lineHeight: 1.15 }}>
          경상남도 18개 시·군 중 <span style={{ color: theme.accent }}>대다수 기관</span>이<br/>MSECM과 함께합니다.
        </h2>
      </div>
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', gap: 60, animation: 'msecmMarquee 50s linear infinite', width: 'max-content' }}>
          {row.map((l, i) => (
            <div key={i} style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-.02em', color: theme.inkSub, fontFamily: '"Pretendard", "Helvetica Neue", sans-serif', whiteSpace: 'nowrap', opacity: .65 }}>{l}</div>
          ))}
        </div>
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: `linear-gradient(90deg, var(--bg-wash, ${theme.bgLight}), transparent 12%, transparent 88%, var(--bg-wash, ${theme.bgLight}))` }}/>
      </div>
      <style>{`@keyframes msecmMarquee{from{transform:translateX(0)}to{transform:translateX(-50%)}}`}</style>
    </section>
  );
}

function Press({ theme }) {
  const isMobile = window.useIsMobile();
  const press = window.MSECM_DATA.press;
  const awards = window.MSECM_DATA.awards;
  return (
    <section id="sec-press" data-screen-label="09 Press" data-bg-id="press" style={{ color: theme.ink, padding: isMobile ? '80px 16px 100px' : '120px 40px 160px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionLabel theme={theme} index="07" label="Press & Awards" />
        <h2 data-anim="up" style={{ fontSize: 'clamp(28px, 4.5vw, 60px)', fontWeight: 700, letterSpacing: '-.03em', margin: isMobile ? '20px 0 40px' : '20px 0 64px', lineHeight: 1.1 }}>
          업계가 주목하고,<br/>
          <span style={{ color: theme.accent }}>언론이 인용합니다.</span>
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.4fr 1fr', gap: isMobile ? 48 : 64 }}>
          <div>
            <h3 style={{ fontSize: 13, letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 600, color: theme.inkSub, margin: '0 0 24px' }}>주요 보도</h3>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, borderTop: `0.5px solid ${theme.divLine}` }}>
              {press.map((p, i) => (
                <li key={i} style={{
                  display: 'grid',
                  gridTemplateColumns: isMobile ? '1fr 20px' : '120px 90px 1fr 24px',
                  gap: isMobile ? 8 : 20,
                  padding: isMobile ? '16px 0' : '22px 0',
                  borderBottom: `0.5px solid ${theme.divLine}`,
                  alignItems: isMobile ? 'start' : 'center',
                }}>
                  {isMobile ? (
                    <div>
                      <div style={{ fontSize: 12, color: theme.inkSub, display: 'flex', gap: 8, marginBottom: 6 }}>
                        <span style={{ fontWeight: 600, color: theme.ink }}>{p.media}</span>
                        <span>·</span>
                        <span style={{ fontVariantNumeric: 'tabular-nums' }}>{p.date}</span>
                      </div>
                      <div style={{ fontSize: 14, color: theme.ink, letterSpacing: '-.01em', lineHeight: 1.5 }}>{p.headline}</div>
                    </div>
                  ) : (
                    <>
                      <span style={{ fontSize: 13, fontWeight: 600, color: theme.ink, letterSpacing: '-.005em' }}>{p.media}</span>
                      <span style={{ fontSize: 12.5, color: theme.inkSub, fontVariantNumeric: 'tabular-nums' }}>{p.date}</span>
                      <span style={{ fontSize: 15, color: theme.ink, letterSpacing: '-.01em', lineHeight: 1.5 }}>{p.headline}</span>
                    </>
                  )}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.inkSub} strokeWidth="2" strokeLinecap="round" style={{ marginTop: isMobile ? 4 : 0 }}><path d="M7 17L17 7M9 7h8v8"/></svg>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <h3 style={{ fontSize: 13, letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 600, color: theme.inkSub, margin: '0 0 24px' }}>수상 · 인증</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {awards.map((a, i) => (
                <div key={i} style={{ padding: '20px 22px', background: theme.cardBg, border: `0.5px solid ${theme.divLine}`, borderRadius: 14, display: 'flex', alignItems: 'center', gap: 16 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0, background: `linear-gradient(135deg, ${theme.accent}, ${theme.accent}aa)`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{a.y}</div>
                  <div>
                    <div style={{ fontSize: 14.5, fontWeight: 600, letterSpacing: '-.015em' }}>{a.name}</div>
                    <div style={{ fontSize: 12, color: theme.inkSub, marginTop: 2 }}>{a.org}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer({ theme }) {
  const isMobile = window.useIsMobile();
  const c = window.MSECM_DATA.company;
  return (
    <footer data-screen-label="10 Footer" data-bg-id="footer" style={{ color: theme.inkOnDeep, padding: isMobile ? '64px 16px 32px' : '100px 40px 48px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr 1fr' : '2fr 1fr 1fr 1fr',
          gap: isMobile ? 32 : 40,
          paddingBottom: isMobile ? 48 : 80,
          borderBottom: `0.5px solid ${theme.divOnDeep}`,
        }}>
          <div style={{ gridColumn: isMobile ? 'span 2' : 'auto' }}>
            <img src="/assets/msecm-logo.avif" alt="MSECM" style={{ height: 40, width: 'auto', display: 'block', filter: 'brightness(0) invert(1)' }} />
            <p style={{ fontSize: 14, lineHeight: 1.7, color: theme.inkOnDeepSub, marginTop: 16, maxWidth: 360 }}>
               “좋은 연결, 좋은 세상.”— 교육을 통해 공공과 민간을 잇고,<br/>사람과 사람다움을 이어주며 지속 가능한 미래를 만듭니다.
            </p>
            <div style={{ marginTop: 32, fontSize: 12.5, color: theme.inkOnDeepSub, lineHeight: 1.8 }}>
              <div>{c.address}</div>
              <div>TEL {c.tel} · FAX {c.fax}</div>
              <div>{c.email}</div>
            </div>
          </div>
          {[
            { h: '사업영역', items: ['공무원 역량강화', '시민·교원 교육', '공공시설 위탁운영', '탄소중립 교육'] },
            { h: '리소스', items: ['자료실', 'MSECM Lab', '뉴스레터', '회사소개서'] },
            { h: '회사', items: ['소개', '실적', '채용', '문의'] },
          ].map(col => (
            <div key={col.h}>
              <div style={{ fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 600, color: theme.inkOnDeepSub, marginBottom: 18 }}>{col.h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.items.map(it => (
                  <li key={it} style={{ fontSize: 14, color: theme.inkOnDeep }}>{it}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32, fontSize: 12, color: theme.inkOnDeepSub, flexWrap: 'wrap', gap: 12 }}>
          <div>© 2025 {c.name} · 대표 {c.ceo} · 설립 {c.founded}</div>
          <div style={{ display: 'flex', gap: 20 }}>
            <span>이용약관</span><span>개인정보처리방침</span><span>사이트맵</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

function Nav({ theme, scrollY }) {
  const scrolled = scrollY > 60;
  const isMobile = window.useIsMobile();
  const [menuOpen, setMenuOpen] = useState(false);
  const menuItems = [
    { l: 'Capabilities', id: 'sec-capabilities' },
    { l: 'News',         id: 'sec-news' },
    { l: 'Insights',     id: 'sec-blog' },
    { l: 'Track Record', id: 'sec-portfolio' },
    { l: 'Resources',    id: 'sec-materials' },
    { l: 'Press',        id: 'sec-press' },
  ];
  const goTo = (id) => (e) => {
    e.preventDefault();
    setMenuOpen(false);
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY + 80;
    window.scrollTo({ top, behavior: 'smooth' });
  };
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      padding: scrolled ? (isMobile ? '12px 16px' : '14px 32px') : (isMobile ? '16px 16px' : '22px 40px'),
      transition: 'padding .4s cubic-bezier(.2,.8,.2,1), background .35s',
      background: scrolled || menuOpen ? theme.navBg : 'transparent',
      backdropFilter: (scrolled || menuOpen) ? 'blur(24px) saturate(180%)' : 'none',
      WebkitBackdropFilter: (scrolled || menuOpen) ? 'blur(24px) saturate(180%)' : 'none',
      borderBottom: (scrolled || menuOpen) ? `0.5px solid ${theme.divLine}` : '0.5px solid transparent',
      color: theme.navInk,
    }}>
      <div style={{ maxWidth: 1400, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a href="#" onClick={(e)=>{e.preventDefault(); setMenuOpen(false); window.scrollTo({top:0, behavior:'smooth'});}} style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none', flexShrink: 0 }} aria-label="MSECM">
          <img src="/assets/msecm-logo.avif" alt="MSECM" style={{ height: scrolled ? 38 : 48, width: 'auto', display: 'block', transition: 'height .4s cubic-bezier(.2,.8,.2,1)' }} />
        </a>
        {/* 데스크탑 메뉴 */}
        {!isMobile && (
          <nav style={{ display: 'flex', gap: 36, fontSize: 13.5, fontWeight: 500 }}>
            {menuItems.map(n => (
              <a key={n.l} href={'#'+n.id} onClick={goTo(n.id)} style={{ color: theme.navInk, textDecoration: 'none', opacity: .85, cursor: 'pointer', whiteSpace: 'nowrap' }}>{n.l}</a>
            ))}
          </nav>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 8 : 16, flexShrink: 0 }}>
          <button onClick={goTo('sec-press')} style={{ padding: isMobile ? '7px 14px' : '9px 18px', borderRadius: 999, border: 'none', background: theme.accent, color: '#fff', fontSize: isMobile ? 12 : 13, fontWeight: 600, cursor: 'pointer', letterSpacing: '-.005em', whiteSpace: 'nowrap', flexShrink: 0 }}>상담 문의</button>
          {/* 모바일 햄버거 토글 */}
          {isMobile && (
            <button onClick={() => setMenuOpen(o => !o)} aria-label="메뉴" style={{ width: 36, height: 36, borderRadius: 10, border: 'none', background: 'transparent', color: theme.navInk, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
              {menuOpen ? (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
              ) : (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
              )}
            </button>
          )}
        </div>
      </div>
      {/* 모바일 드롭다운 메뉴 */}
      {isMobile && menuOpen && (
        <nav style={{
          position: 'absolute', left: 0, right: 0, top: '100%',
          background: theme.navBg,
          backdropFilter: 'blur(24px) saturate(180%)',
          WebkitBackdropFilter: 'blur(24px) saturate(180%)',
          borderBottom: `0.5px solid ${theme.divLine}`,
          padding: '8px 16px 20px',
          display: 'flex', flexDirection: 'column',
        }}>
          {menuItems.map(n => (
            <a key={n.l} href={'#'+n.id} onClick={goTo(n.id)} style={{
              color: theme.navInk, textDecoration: 'none', cursor: 'pointer',
              fontSize: 16, fontWeight: 500, letterSpacing: '-.01em',
              padding: '14px 4px', borderBottom: `0.5px solid ${theme.divLine}`,
            }}>{n.l}</a>
          ))}
        </nav>
      )}
    </header>
  );
}

Object.assign(window, { Hero, Capabilities, News, Blog, Portfolio, Materials, Stats, Clients, Press, Footer, Nav });
