/* CasesPage.jsx */

/* ── Google Sheets ── */
var SHEET_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQSz--YfCUH_wrvqXx0oGNgIYrf0uJBXIkVsAm7bIynUwsIS_utNUutew9fgVY3qYDQ9Zy7v4DRN1E7/pub?gid=0&single=true&output=csv';

/* ── 영상 URL → embed 변환 ── */
function toVideoEmbed(url) {
  if (!url) return '';
  if (/youtube\.com|youtu\.be/.test(url)) {
    if (url.includes('/embed/')) return url;
    const shorts = url.match(/\/shorts\/([^?&\s]+)/);
    if (shorts) return `https://www.youtube.com/embed/${shorts[1]}`;
    const short = url.match(/youtu\.be\/([^?&\s]+)/);
    if (short) return `https://www.youtube.com/embed/${short[1]}`;
    const watch = url.match(/[?&]v=([^&\s]+)/);
    if (watch) return `https://www.youtube.com/embed/${watch[1]}`;
  }
  if (/drive\.google\.com/.test(url)) {
    if (url.includes('/preview')) return url;
    const fileMatch = url.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
    if (fileMatch) return `https://drive.google.com/file/d/${fileMatch[1]}/preview`;
    const idMatch = url.match(/[?&]id=([a-zA-Z0-9_-]+)/);
    if (idMatch) return `https://drive.google.com/file/d/${idMatch[1]}/preview`;
  }
  return url;
}

function isEmbeddable(url) {
  return /youtube\.com|youtu\.be|drive\.google\.com/.test(url);
}

/* ── 구글 드라이브 이미지 URL 변환 ── */
function toDriveImg(url) {
  if (!url) return '';
  if (url.includes('drive.google.com') || url.includes('docs.google.com')) {
    const m = url.match(/[-\w]{25,}/g);
    const id = m ? m[m.length - 1] : null;
    return id ? `https://drive.google.com/thumbnail?id=${id}&sz=w800` : url;
  }
  if (!url.startsWith('http')) return 'assets/' + url;
  return url;
}

/* ── CSV 파서 ── */
function parseSheetCSV(text) {
  var rows = [], cur = [], field = '', inQ = false;
  for (var i = 0; i < text.length; i++) {
    var ch = text[i];
    if (ch === '"') {
      if (inQ && text[i+1] === '"') { field += '"'; i++; }
      else { inQ = !inQ; }
    } else if (ch === ',' && !inQ) {
      cur.push(field.trim()); field = '';
    } else if ((ch === '\n' || ch === '\r') && !inQ) {
      cur.push(field.trim()); field = '';
      if (cur.some(function(c){ return c; })) rows.push(cur);
      cur = [];
      if (ch === '\r' && text[i+1] === '\n') i++;
    } else {
      field += ch;
    }
  }
  if (field || cur.length) { cur.push(field.trim()); rows.push(cur); }
  if (rows.length < 2) return [];
  var headers = rows[0];
  return rows.slice(1).map(function(row) {
    var obj = {};
    headers.forEach(function(h, i) { obj[h] = row[i] || ''; });
    obj.imgs = obj.img
      ? obj.img.split('|').map(function(u){ return toDriveImg(u.trim()); }).filter(Boolean)
      : [];
    obj.img = obj.imgs[0] || '';
    return obj;
  }).filter(function(obj) { return obj.title && obj.title.trim(); });
}

/* ── Fallback 데이터 ── */
const FALLBACK_CASES = [
  {
    category: '한의원', title: '전국 54개 한의원 도입 사례',
    location: '서울·경기·부산 외 전국', product: 'PFS-304 Series',
    img: 'assets/한의원.png', imgs: ['assets/한의원.png'], video: 'https://www.youtube.com/embed/GYGHwfb3oHw',
    content: '비만·자세 상담에 3D 바디스캐너를 도입하여 상담 시간 단축 및 환자 만족도 향상. 한 번의 스캔으로 비만 수치와 자세 분석을 동시에 제공합니다.',
    date: '',
  },
  {
    category: '비만센터·병원', title: '비만관리 전문 클리닉 도입 사례',
    location: '서울 강남구', product: 'PFS-304 Series',
    img: 'assets/수정본성형비만.png', imgs: ['assets/수정본성형비만.png'], video: '',
    content: '지방흡입 수술 전후 바디라인 설계 및 3D 비교 분석에 활용. 집도의가 수술 계획 수립에 3D 데이터를 적극 활용하며 환자 상담 만족도가 높아졌습니다.',
    date: '',
  },
  {
    category: '연구기관', title: '대학교 의류학과 연구 도입 사례',
    location: '국내 주요 대학교', product: 'SHAPENIX',
    img: 'assets/연구기관.png', imgs: ['assets/연구기관.png'], video: '',
    content: 'ISO 20685 국제 표준 기반의 SHAPENIX를 활용하여 국가 인체 표준 데이터 구축 연구에 적용. 150여개 항목의 정밀 자동 측정으로 연구 효율을 극대화하였습니다.',
    date: '',
  },
  {
    category: '에스테틱', title: '에스테틱·피트니스 센터 도입 사례',
    location: '서울·부산 다수 지점', product: 'Shape Care',
    img: 'assets/에스테틱.png', imgs: ['assets/에스테틱.png'], video: '',
    content: '체성분 분석과 3D 바디 스캔을 동시에 제공하는 Shape Care 도입으로 고객 케어 프로그램의 질을 높이고 재등록률을 향상시켰습니다.',
    date: '',
  },
  {
    category: '의류', title: '의류 업체 맞춤 치수 측정 사례',
    location: '국내 패션·의류 브랜드', product: 'PFS-304 Series',
    img: 'assets/의류센터.png', imgs: ['assets/의류센터.png'], video: '',
    content: '줄자 측정의 불편함과 오차를 없애고, 의상 전용 29개 치수를 10초 이내에 자동 측정. 숙련도에 관계없이 일관된 수치를 제공합니다.',
    date: '',
  },
  {
    category: '해외 수출', title: '일본·인도네시아 수출 사례',
    location: '일본, 인도네시아', product: 'PFS-304 Series / SHAPENIX',
    img: 'assets/보건소.png', imgs: ['assets/보건소.png'], video: '',
    content: '한국을 넘어 일본, 인도네시아 등 해외 시장으로 진출. 다국어 지원 소프트웨어와 현지화된 교육 프로그램을 통해 글로벌 시장에서도 기술력을 인정받고 있습니다.',
    date: '',
  },
];

const CACHE_KEY = 'pmt-cases-cache';

/* ── 히어로 섹션 (뉴스와 다른 라이트 카드 스타일) ── */
function CaseFeaturedHero({ cases, onOpen }) {
  const [idx, setIdx] = React.useState(0);
  const [hoveredIdx, setHoveredIdx] = React.useState(null);
  const limited = cases.slice(0, 4);
  const len = limited.length;

  /* 카드가 고정 px 크기라 화면이 좁아지면(또는 창을 반만 띄운 노트북 화면 등)
     화면 밖으로 카드가 잘려버리는 문제를 막기 위해, 창 너비에 맞춰
     계단식이 아니라 연속적으로 카드 크기를 다시 계산합니다. */
  const w = useWindowWidth();
  const isMobile = w < 640;
  const MAIN_W = isMobile ? Math.min(w - 48, 480) : Math.min(w - 160, 980);
  const MAIN_H = isMobile ? 320 : Math.max(300, Math.min(500, Math.round(MAIN_W * 500 / 980)));
  const PEEK_W = isMobile ? 0 : Math.min(280, Math.round(MAIN_W * 0.3));
  const PEEK_H = isMobile ? 0 : Math.min(380, Math.round(MAIN_H * 0.78));
  const GAP = isMobile ? 0 : -90;

  React.useEffect(() => {
    if (len < 2) return;
    const t = setInterval(() => setIdx(p => (p + 1) % len), 5000);
    return () => clearInterval(t);
  }, [len]);

  if (!len) return null;

  return (
    <div style={{ background: 'linear-gradient(180deg,#eef1ff 0%,#f0f4ff 25%,#f8f9ff 65%,#fff 100%)', padding: '36px 0 40px', overflow: 'hidden' }}>
      {/* 헤더 */}
      <div style={{ textAlign: 'center', marginBottom: 28, paddingTop: 24 }}>
        <span style={{ fontSize: 11, color: '#C8271D', fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase', display: 'block', marginBottom: 10 }}>Case Studies</span>
        <h2 style={{ fontSize: 'clamp(24px,3.5vw,40px)', fontWeight: 900, color: '#111', letterSpacing: '-0.04em', lineHeight: 1, margin: 0 }}>도입사례</h2>
      </div>

      {/* 캐러셀 */}
      <div style={{ position: 'relative', height: MAIN_H + 100, marginBottom: 32 }}>
        {limited.map((item, i) => {
          const raw = i - idx;
          const norm = ((raw % len) + len) % len;
          const adj = norm > len / 2 ? norm - len : norm;
          const isMain = adj === 0;
          const isPeek = Math.abs(adj) === 1;
          if (!isMain && !isPeek) return null;
          if (isMobile && !isMain) return null; /* 모바일에서는 메인 카드만 표시 */

          const tx = adj * (MAIN_W / 2 + PEEK_W / 2 + GAP);
          const w = isMain ? MAIN_W : PEEK_W;
          const h = isMain ? MAIN_H : PEEK_H;
          const opacity = isMain ? 1 : 0.42;
          const scale = isMain ? 1 : 0.92;
          const zIdx = isMain ? 10 : 5;

          const isHovered = hoveredIdx === i;

          return (
            <div key={i}
              onClick={() => isMain ? onOpen(item) : setIdx(i)}
              onMouseEnter={() => setHoveredIdx(i)}
              onMouseLeave={() => setHoveredIdx(null)}
              style={{
                position: 'absolute', top: '50%', left: '50%',
                width: w, height: h,
                transform: `translateX(calc(-50% + ${tx}px)) translateY(-50%) scale(${scale})`,
                opacity,
                transition: 'all 650ms cubic-bezier(0.16,1,0.3,1)',
                zIndex: zIdx,
                cursor: 'pointer',
                borderRadius: 20,
                overflow: 'hidden',
                boxShadow: isMain
                  ? (isHovered ? '0 36px 90px rgba(10,22,40,0.38)' : '0 28px 80px rgba(10,22,40,0.28)')
                  : '0 8px 32px rgba(0,0,0,0.09)',
              }}>

              {/* 이미지 꽉 채우기 */}
              {item.img
                ? <img src={item.img} alt={item.title} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', transition: 'transform 500ms ease', transform: isHovered ? 'scale(1.04)' : 'scale(1)' }} />
                : <div style={{ width: '100%', height: '100%', background: 'linear-gradient(135deg,#1a2e4a,#0d3060)' }} />
              }

              {/* 호버 컬러 오버레이 */}
              <div style={{
                position: 'absolute', inset: 0,
                background: isHovered
                  ? 'linear-gradient(to top, rgba(200,39,29,0.55) 0%, rgba(10,22,40,0.45) 50%, rgba(10,22,40,0.10) 100%)'
                  : 'linear-gradient(to top, rgba(10,22,40,0.82) 0%, rgba(10,22,40,0.35) 55%, transparent 100%)',
                transition: 'background 350ms ease',
              }} />

              {/* 텍스트 오버레이 */}
              {isMain ? (
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: isMobile ? '22px 22px' : '40px 44px' }}>
                  {item.category && (
                    <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#ff6b5b', background: 'rgba(200,39,29,0.22)', borderRadius: 6, padding: '4px 12px', display: 'inline-block', marginBottom: 16 }}>{item.category}</span>
                  )}
                  <h3 style={{ fontSize: 24, fontWeight: 800, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1.4, margin: '0 0 12px' }}>{item.title}</h3>
                  {item.location && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 16 }}>
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                        <path d="M6 1C3.79 1 2 2.79 2 5c0 3 4 6 4 6s4-3 4-6c0-2.21-1.79-4-4-4z" stroke="rgba(255,255,255,0.6)" strokeWidth="1.3"/>
                        <circle cx="6" cy="5" r="1.2" fill="rgba(255,255,255,0.6)"/>
                      </svg>
                      <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', fontWeight: 500 }}>{item.location}</span>
                    </div>
                  )}
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
                    {item.product && (
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {item.product.split('/').map((p, pi) => (
                          <span key={pi} style={{ fontSize: 11, fontWeight: 600, color: 'rgba(255,255,255,0.8)', background: 'rgba(255,255,255,0.15)', borderRadius: 6, padding: '4px 10px' }}>{p.trim()}</span>
                        ))}
                      </div>
                    )}
                    <button onClick={e => { e.stopPropagation(); onOpen(item); }}
                      style={{ background: '#C8271D', color: '#fff', border: 'none', borderRadius: 99, padding: '10px 24px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'all 200ms', letterSpacing: '-0.01em' }}
                      onMouseEnter={e => e.currentTarget.style.background = '#a81f17'}
                      onMouseLeave={e => e.currentTarget.style.background = '#C8271D'}>
                      자세히 보기 →
                    </button>
                  </div>
                </div>
              ) : (
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '20px 20px' }}>
                  {item.category && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#ff8f85', display: 'block', marginBottom: 6 }}>{item.category}</span>}
                  <h3 style={{ fontSize: 13, fontWeight: 800, color: '#fff', letterSpacing: '-0.02em', lineHeight: 1.5, margin: 0, display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{item.title}</h3>
                </div>
              )}
            </div>
          );
        })}

        {/* 화살표 */}
        <button onClick={() => setIdx(p => (p - 1 + len) % len)}
          style={{ position: 'absolute', left: 20, top: '50%', transform: 'translateY(-50%)', width: 44, height: 44, borderRadius: '50%', border: '1.5px solid #d0d8e8', background: 'rgba(255,255,255,0.9)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 30, backdropFilter: 'blur(8px)', transition: 'all 200ms' }}
          onMouseEnter={e => { e.currentTarget.style.background = '#111'; e.currentTarget.style.borderColor = '#111'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.9)'; e.currentTarget.style.borderColor = '#d0d8e8'; }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M10 3L5 8l5 5" stroke="#111" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
        <button onClick={() => setIdx(p => (p + 1) % len)}
          style={{ position: 'absolute', right: 20, top: '50%', transform: 'translateY(-50%)', width: 44, height: 44, borderRadius: '50%', border: '1.5px solid #d0d8e8', background: 'rgba(255,255,255,0.9)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 30, backdropFilter: 'blur(8px)', transition: 'all 200ms' }}
          onMouseEnter={e => { e.currentTarget.style.background = '#111'; e.currentTarget.style.borderColor = '#111'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.9)'; e.currentTarget.style.borderColor = '#d0d8e8'; }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M6 3l5 5-5 5" stroke="#111" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
      </div>

      {/* 도트 */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 8 }}>
        {limited.map((_, i) => (
          <button key={i} onClick={() => setIdx(i)} style={{
            width: i === idx ? 28 : 8, height: 8, borderRadius: 4,
            background: i === idx ? '#C8271D' : '#c8d0e4',
            border: 'none', cursor: 'pointer', padding: 0, flexShrink: 0,
            transition: 'all 300ms cubic-bezier(0.16,1,0.3,1)',
          }} />
        ))}
      </div>
    </div>
  );
}

/* ── 카드 컴포넌트 (참고2 스타일) ── */
function CaseCard({ case_, onClick }) {
  const [hov, setHov] = React.useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{
        borderRadius: 16, overflow: 'hidden', cursor: 'pointer',
        border: '1.5px solid #e8e8e8',
        boxShadow: hov ? '0 12px 40px rgba(0,0,0,0.12)' : '0 2px 8px rgba(0,0,0,0.05)',
        transform: hov ? 'translateY(-4px)' : 'none',
        transition: 'all 260ms cubic-bezier(0.16,1,0.3,1)',
        background: '#fff',
      }}
    >
      <div style={{ position: 'relative', overflow: 'hidden', aspectRatio: '16/10' }}>
        {case_.img
          ? <img src={case_.img} alt={case_.title} style={{
              width: '100%', height: '100%', objectFit: 'cover', display: 'block',
              transform: hov ? 'scale(1.05)' : 'scale(1)',
              transition: 'transform 500ms cubic-bezier(0.16,1,0.3,1)',
            }} />
          : <div style={{ width: '100%', height: '100%', background: '#f5f5f5' }} />
        }
      </div>

      <div style={{ padding: '20px 22px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          {case_.category && (
            <span style={{
              fontSize: 11, fontWeight: 700, color: '#C8271D',
              background: 'rgba(200,39,29,0.08)', borderRadius: 99,
              padding: '3px 10px', letterSpacing: '0.06em',
            }}>{case_.category}</span>
          )}
          {case_.date && (
            <span style={{ fontSize: 12, color: '#bbb', fontWeight: 500 }}>{case_.date}</span>
          )}
        </div>

        <h3 style={{
          fontSize: 16, fontWeight: 800, color: '#1a1a1a',
          letterSpacing: '-0.02em', lineHeight: 1.4, margin: '0 0 10px',
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>{case_.title}</h3>

        {case_.location && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 12 }}>
            <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
              <path d="M6 1C3.79 1 2 2.79 2 5c0 3 4 6 4 6s4-3 4-6c0-2.21-1.79-4-4-4z" stroke="#bbb" strokeWidth="1.3"/>
              <circle cx="6" cy="5" r="1.2" fill="#bbb"/>
            </svg>
            <span style={{ fontSize: 12, color: '#bbb', fontWeight: 500 }}>{case_.location}</span>
          </div>
        )}

        {case_.product && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {case_.product.split('/').map((p, i) => (
              <span key={i} style={{
                fontSize: 11, fontWeight: 600, color: '#999',
                background: '#f5f5f5', borderRadius: 6, padding: '4px 10px',
              }}>{p.trim()}</span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

/* ── 메인 페이지 ── */
function CasesPage({ navigate, subPage, setSubPage }) {
  const [activeFilter, setActiveFilter] = React.useState('전체');
  const [sheetCases, setSheetCases] = React.useState(() => {
    try {
      const cached = localStorage.getItem(CACHE_KEY);
      return cached ? JSON.parse(cached) : FALLBACK_CASES;
    } catch(e) { return FALLBACK_CASES; }
  });

  React.useEffect(() => {
    fetch(SHEET_URL)
      .then(function(r) { return r.text(); })
      .then(function(text) {
        try {
          var parsed = parseSheetCSV(text);
          if (parsed.length > 0) {
            setSheetCases(parsed);
            localStorage.setItem(CACHE_KEY, JSON.stringify(parsed));
          }
        } catch(e) {}
      })
      .catch(function() {});
  }, []);

  const goDetail = (c) => {
    setSubPage && setSubPage(c.title);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };
  const goBack = () => {
    setSubPage && setSubPage(null);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const activeCases = sheetCases || FALLBACK_CASES;
  const categories = ['전체', ...new Set(activeCases.map(c => c.category).filter(Boolean))];
  const filtered = activeFilter === '전체' ? activeCases : activeCases.filter(c => c.category === activeFilter);

  const detailCase = subPage ? activeCases.find(c => c.title === subPage) : null;
  if (detailCase) return <CaseDetailPage case_={detailCase} onBack={goBack} navigate={navigate} />;

  /* 전체 탭: 앞 3개는 히어로, 나머지는 그리드 */
  const gridItems = activeFilter === '전체' ? activeCases.slice(3) : filtered;

  return (
    <div style={{ paddingTop: NAV_HEIGHT, background: '#fff', minHeight: '100vh' }}>

      {/* ── 히어로 (전체 탭) ── */}
      {activeFilter === '전체' && (
        <CaseFeaturedHero cases={activeCases} onOpen={goDetail} />
      )}

      {/* ── 탭 필터 (참고2 스타일: 다크 필 탭) ── */}
      <div style={{
        background: '#fff', borderBottom: 'none',
        position: 'sticky', top: NAV_HEIGHT, zIndex: 100,
      }}>
        <div className="pmt-pad-lg" style={{
          maxWidth: 1280, margin: '0 auto',
          padding: '14px 48px', display: 'flex', gap: 8,
          overflowX: 'auto', flexWrap: 'nowrap',
        }}>
          {categories.map(f => (
            <button key={f} onClick={() => { setActiveFilter(f); window.scrollTo({ top: 0, behavior: 'smooth' }); }} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              padding: '18px 22px', fontSize: 14, fontWeight: 700,
              color: activeFilter === f ? '#C8271D' : '#888',
              borderBottom: activeFilter === f ? '2.5px solid #C8271D' : '2.5px solid transparent',
              fontFamily: 'inherit', whiteSpace: 'nowrap', flexShrink: 0,
              transition: 'color 200ms', letterSpacing: '-0.01em',
            }}>{f}</button>
          ))}
        </div>
      </div>

      {/* ── 카드 그리드 (2열, 참고2 스타일) ── */}
      <div className="pmt-pad-lg" style={{ maxWidth: 1280, margin: '0 auto', padding: '48px 48px 80px' }}>
        {gridItems.length > 0 ? (
          <div className="rgrid-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 28 }}>
            {gridItems.map((c, i) => (
              <CaseCard key={i} case_={c} onClick={() => goDetail(c)} />
            ))}
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: '80px 0', color: '#bbb', fontSize: 15 }}>
            {activeFilter === '전체' ? '' : '해당 카테고리의 사례가 없습니다.'}
          </div>
        )}
      </div>

      {/* ── CTA ── */}
      <div className="pmt-pad-lg" style={{ background: '#fff', borderTop: '1px solid #e8e8e8', padding: '64px 48px', textAlign: 'center', marginTop: 16 }}>
        <div style={{ maxWidth: 560, margin: '0 auto' }}>
          <h3 style={{ fontSize: 28, fontWeight: 800, color: '#1a1a1a', letterSpacing: '-0.03em', marginBottom: 16 }}>우리 기관에도 도입하고 싶다면?</h3>
          <p style={{ fontSize: 16, color: '#888', fontWeight: 500, marginBottom: 28, lineHeight: 1.7 }}>현장 방문 데모 시연 및 무료 견적 상담을 신청하세요.</p>
          <button onClick={() => navigate('contact')}
            style={{ background: '#C8271D', color: '#fff', border: 'none', borderRadius: 99, padding: '15px 36px', fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', boxShadow: '0 4px 20px rgba(200,39,29,0.2)', transition: 'all 200ms' }}
            onMouseEnter={e => { e.currentTarget.style.background = '#a81f17'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = '#C8271D'; e.currentTarget.style.transform = ''; }}
          >견적 문의하기 →</button>
        </div>
      </div>

    </div>
  );
}

/* ── 마크다운 렌더러 ── */
function renderInline(text, key) {
  const parts = text.split(/(\*\*\*[^*]+\*\*\*|\*\*[^*]+\*\*|\*\*[^*]+$|\*[^*]+\*|\*[^*]+$|https?:\/\/[^\s]+)/g);
  return (
    <React.Fragment key={key}>
      {parts.map((part, i) => {
        if (/^\*\*\*/.test(part) && /\*\*\*$/.test(part))
          return <strong key={i} style={{ fontWeight:800, color:'#111' }}>{part.slice(3, part.endsWith('***') ? -3 : 0) || part.slice(3)}</strong>;
        if (/^\*\*/.test(part))
          return <strong key={i} style={{ fontWeight:700, color:'#222' }}>{part.replace(/^\*\*|\*\*$/g, '')}</strong>;
        if (/^\*/.test(part))
          return <em key={i} style={{ fontStyle:'italic' }}>{part.replace(/^\*|\*$/g, '')}</em>;
        if (/^https?:\/\//.test(part))
          return <a key={i} href={part} target="_blank" rel="noopener noreferrer"
            style={{ color:'#C8271D', textDecoration:'underline', wordBreak:'break-all' }}>{part}</a>;
        return part;
      })}
    </React.Fragment>
  );
}

function MarkdownContent({ text }) {
  if (!text) return null;
  const lines = text.split('\n');
  const elements = [];
  let listItems = [];
  let checkItems = [];
  let key = 0;

  const flushList = () => {
    if (!listItems.length) return;
    elements.push(
      <ul key={key++} style={{ margin:'8px 0 12px 20px', padding:0, listStyle:'disc' }}>
        {listItems.map((item, j) => <li key={j} style={{ marginBottom:4 }}>{renderInline(item, j)}</li>)}
      </ul>
    );
    listItems = [];
  };

  const flushCheck = () => {
    if (!checkItems.length) return;
    elements.push(
      <ul key={key++} style={{ margin:'8px 0 12px 0', padding:0, listStyle:'none' }}>
        {checkItems.map((item, j) => (
          <li key={j} style={{ marginBottom:6, display:'flex', alignItems:'flex-start', gap:8 }}>
            <span style={{ color:'#C8271D', fontWeight:700, flexShrink:0 }}>✓</span>
            <span>{renderInline(item, j)}</span>
          </li>
        ))}
      </ul>
    );
    checkItems = [];
  };

  lines.forEach((line) => {
    if (/^!\[.*?\]\(.*?\)/.test(line)) {
      flushList(); flushCheck();
      const m = line.match(/^!\[(.*?)\]\((.*?)\)/);
      if (m) {
        const alt = m[1];
        const src = toDriveImg(m[2].trim());
        elements.push(
          <div key={key++} style={{ margin:'16px 0' }}>
            <img src={src} alt={alt} style={{ width:'100%', borderRadius:10, display:'block', border:'1px solid #ebebeb' }} />
            {alt && <div style={{ fontSize:13, color:'#aaa', textAlign:'center', marginTop:6 }}>{alt}</div>}
          </div>
        );
      }
    } else if (/^\*{3}\s*\S/.test(line)) {
      flushList(); flushCheck();
      const heading = line.replace(/^\*{3}\s*/, '');
      elements.push(
        <h3 key={key++} style={{ fontSize:18, fontWeight:800, color:'#1a1a1a', margin:'28px 0 10px', letterSpacing:'-0.02em', borderBottom:'1.5px solid #ebebeb', paddingBottom:8 }}>
          {heading}
        </h3>
      );
    } else if (/^✓/.test(line)) {
      flushList();
      checkItems.push(line.replace(/^✓\s*/, ''));
    } else if (/^[-]\s+/.test(line)) {
      flushCheck();
      listItems.push(line.replace(/^[-]\s+/, ''));
    } else {
      flushList(); flushCheck();
      if (line.trim()) {
        elements.push(<p key={key++} style={{ margin:'0 0 12px' }}>{renderInline(line, key)}</p>);
      } else {
        elements.push(<div key={key++} style={{ height:8 }} />);
      }
    }
  });
  flushList(); flushCheck();

  return (
    <div style={{ fontSize:19, color:'#444', lineHeight:2.0, fontWeight:400 }}>
      {elements}
    </div>
  );
}

function CaseDetailPage({ case_, onBack, navigate }) {
  return (
    <div style={{ paddingTop: NAV_HEIGHT, background:'#fff', minHeight:'100vh' }}>

      <div style={{ borderBottom:'1px solid #e8e8e8', background:'#fff', position:'sticky', top:NAV_HEIGHT, zIndex:100 }}>
        <div className="pmt-pad-lg" style={{ maxWidth:1280, margin:'0 auto', padding:'0 48px', height:52, display:'flex', alignItems:'center' }}>
          <button onClick={onBack} style={{
            display:'flex', alignItems:'center', gap:8, background:'none', border:'none',
            cursor:'pointer', fontSize:14, fontWeight:600, color:'#555', fontFamily:'inherit',
            transition:'color 200ms', padding:0,
          }}
            onMouseEnter={e=>e.currentTarget.style.color='#C8271D'}
            onMouseLeave={e=>e.currentTarget.style.color='#555'}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            도입사례 목록으로
          </button>
        </div>
      </div>

      <div className="pmt-pad-lg" style={{ maxWidth:950, margin:'0 auto', padding:'64px 48px 80px' }}>

        <div style={{ marginBottom:40 }}>
          <div style={{ fontSize:15, fontWeight:700, letterSpacing:'0.16em', textTransform:'uppercase', color:'#C8271D', marginBottom:14 }}>{case_.category} · {case_.location}</div>
          <h1 style={{ fontSize:'clamp(22px,2vw,32px)', fontWeight:700, color:'#1a1a1a', letterSpacing:'-0.04em', lineHeight:1.2, margin:'0 0 16px' }}>{case_.title}</h1>
          {case_.product && (
            <div style={{ display:'inline-flex', alignItems:'center', background:'#fafafa', border:'1px solid #e8e8e8', borderRadius:99, padding:'6px 16px' }}>
              <span style={{ fontSize:14, fontWeight:700, color:'#666' }}>도입 제품: {case_.product}</span>
            </div>
          )}
        </div>

        {case_.video && (() => {
          return isEmbeddable(case_.video) ? (
            <div style={{ marginBottom:48, borderRadius:16, overflow:'hidden', boxShadow:'0 4px 24px rgba(0,0,0,0.10)', aspectRatio:'16/9' }}>
              <iframe src={toVideoEmbed(case_.video)} title="현장 영상"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen style={{ width:'100%', height:'100%', border:'none', display:'block' }} />
            </div>
          ) : (
            <div style={{ marginBottom:48 }}>
              <a href={case_.video} target="_blank" rel="noopener noreferrer"
                style={{ display:'inline-flex', alignItems:'center', gap:10, background:'#1a1a1a', color:'#fff',
                  borderRadius:10, padding:'14px 24px', fontSize:15, fontWeight:600, textDecoration:'none',
                  transition:'background 200ms' }}
                onMouseEnter={e=>e.currentTarget.style.background='#C8271D'}
                onMouseLeave={e=>e.currentTarget.style.background='#1a1a1a'}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <polygon points="5,3 19,12 5,21" fill="white"/>
                </svg>
                영상 보기
              </a>
            </div>
          );
        })()}

        {case_.imgs && case_.imgs.length > 0 && (
          <div style={{ marginBottom:48, display:'flex', flexDirection:'column', gap:12 }}>
            {case_.imgs.map((src, i) => (
              <div key={i} style={{ borderRadius:16, overflow:'hidden', border:'1px solid #e8e8e8' }}>
                <img src={src} alt={`${case_.title} ${i+1}`} style={{ width:'100%', display:'block', objectFit:'cover', maxHeight:480 }} />
              </div>
            ))}
          </div>
        )}

        <MarkdownContent text={case_.content} />

        {case_.date && (
          <div style={{ marginTop:48, display:'flex', justifyContent:'flex-end', alignItems:'center', gap:6 }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <rect x="1.5" y="2.5" width="13" height="12" rx="2" stroke="#aaa" strokeWidth="1.4"/>
              <path d="M5 1v3M11 1v3" stroke="#aaa" strokeWidth="1.4" strokeLinecap="round"/>
              <path d="M1.5 6.5h13" stroke="#aaa" strokeWidth="1.4"/>
            </svg>
            <span style={{ fontSize:13, color:'#aaa', fontWeight:500 }}>{case_.date}</span>
          </div>
        )}

        <div style={{ textAlign:'center', paddingTop:56, marginTop:56, borderTop:'1px solid #ebebeb' }}>
          <button onClick={()=>navigate('contact')}
            style={{ background:'#C8271D', color:'#fff', border:'none', borderRadius:99, padding:'16px 48px', fontSize:16, fontWeight:700, cursor:'pointer', fontFamily:'inherit', boxShadow:'0 4px 20px rgba(200,39,29,0.25)', transition:'all 200ms' }}
            onMouseEnter={e=>{ e.currentTarget.style.background='#a81f17'; e.currentTarget.style.transform='translateY(-1px)'; }}
            onMouseLeave={e=>{ e.currentTarget.style.background='#C8271D'; e.currentTarget.style.transform=''; }}
          >우리 기관도 도입 문의하기 →</button>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { CasesPage });
