// AgencyServiceDetail.jsx — agency 카테고리 상세 페이지
//   상단: ● [EN] eyebrow (좌) + SAGUO 로고(상단 오른쪽은 헤더가 처리)
//   가로 검은 라인 → 큰 헤딩(타이핑) + 한글 부제 + 본문 2줄
//   우측 큰 페이드 번호(워터마크)
//   하단: 4개 세부 항목 그리드 (번호·이름·설명)
//   톤앤매너는 Hero/AgencyServices 와 통일 — Pretendard, #F2F2F2, 빨강 dot #000.
const agencyDetailStyles = {
  outer: {
    background: '#F2F2F2',
    width: '100%',
    boxSizing: 'border-box',
    minHeight: 'calc(100svh - 52px)',
    display: 'flex', flexDirection: 'column',
  },
  wrap: {
    maxWidth: 1280, margin: '0 auto',
    width: '100%',
    boxSizing: 'border-box',
    padding: '40px 36px 60px',
    flex: 1, display: 'flex', flexDirection: 'column',
  },
  eyebrowRow: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    paddingBottom: 16,
    borderBottom: '1px solid #000',
    marginBottom: 56,
  },
  eyebrow: {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    fontFamily: "'Pretendard'", fontSize: 11, fontWeight: 700,
    letterSpacing: '0.08em', textTransform: 'uppercase', color: '#000',
    margin: 0,
  },
  eyebrowDot: {
    width: 6, height: 6, borderRadius: '50%', background: '#000',
  },
  back: {
    background: 'none', border: 'none', cursor: 'pointer',
    fontFamily: "'Pretendard'", fontSize: 11, fontWeight: 700,
    letterSpacing: '0.06em', textTransform: 'uppercase', color: '#000',
    padding: 0, display: 'inline-flex', alignItems: 'center', gap: 6,
  },
  titleArea: { position: 'relative', minHeight: 200 },
  title: {
    fontFamily: "'Pretendard'", fontWeight: 700,
    fontSize: 'clamp(18px, 3.2vw, 58px)',
    letterSpacing: '-0.04em', textTransform: 'uppercase',
    color: '#000', lineHeight: 1.02,
    margin: '0 0 14px',
  },
  titleDot: { color: '#000' },
  ko: {
    fontFamily: "'Pretendard'", fontWeight: 700, fontSize: 15,
    letterSpacing: '-0.02em', color: '#000',
    margin: '0 0 22px',
  },
  lead: {
    fontFamily: "'Pretendard'", fontWeight: 400, fontSize: 13.5,
    letterSpacing: '-0.02em', color: '#444', lineHeight: 1.8,
    margin: 0, wordBreak: 'keep-all',
    maxWidth: 720,
  },
  watermark: {
    position: 'absolute', top: -160, right: 0,
    fontFamily: "'Pretendard'", fontWeight: 800,
    fontSize: 'clamp(80px, 11vw, 180px)',
    letterSpacing: '-0.04em', color: '#E5E5E5', lineHeight: 1,
    pointerEvents: 'none', userSelect: 'none',
  },
  listRule: {
    width: '100%', height: 1, background: '#000', margin: '120px 0 0',
  },
  itemsGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    gap: 24,
    paddingTop: 36,
  },
  itemCol: {
    display: 'flex', flexDirection: 'column', gap: 14,
    paddingRight: 12,
  },
  itemNum: {
    fontFamily: "'Pretendard'", fontWeight: 700, fontSize: 13,
    letterSpacing: '0.06em', color: '#000', lineHeight: 1,
  },
  itemName: {
    fontFamily: "'Pretendard'", fontWeight: 700, fontSize: 14.5,
    letterSpacing: '-0.02em', color: '#000', lineHeight: 1.3,
  },
  itemDesc: {
    fontFamily: "'Pretendard'", fontWeight: 400, fontSize: 12.5,
    letterSpacing: '-0.02em', color: '#666', lineHeight: 1.7,
    margin: 0, wordBreak: 'keep-all',
  },
};

function AgencyServiceDetail({ categoryId, onBack }) {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const handler = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);

  const all = (typeof window !== 'undefined' && window.SAGUO_AGENCY_CATEGORIES) || [];
  const cat = all.find((c) => c.id === categoryId) || all[0];
  if (!cat) return null;

  // ── 타이핑 효과 (ModelsIndex / AgencyServices 와 동일 패턴) ──
  // 마운트 시 1회. 점은 별도 렌더로 빨강 처리 — 등장 시 자연스럽게 빨강으로 바뀜.
  const TITLE = (cat.en || '').toUpperCase() + '.';
  const [typed, setTyped] = React.useState('');
  React.useEffect(() => {
    setTyped('');
    let i = 0;
    let interval;
    const startDelay = setTimeout(() => {
      interval = setInterval(() => {
        i++;
        setTyped(TITLE.slice(0, i));
        if (i >= TITLE.length) clearInterval(interval);
      }, 46);
    }, 200);
    return () => { clearTimeout(startDelay); if (interval) clearInterval(interval); };
  }, [categoryId]);
  const hasDot = typed.endsWith('.');
  const typedBody = hasDot ? typed.slice(0, -1) : typed;

  return (
    <div style={agencyDetailStyles.outer}>
      <section style={{ ...agencyDetailStyles.wrap, padding: isMobile ? '32px 20px 48px' : '40px 36px 60px' }}>
        <div style={agencyDetailStyles.eyebrowRow}>
          <p style={agencyDetailStyles.eyebrow}>
            <span style={agencyDetailStyles.eyebrowDot} aria-hidden="true" />
            {cat.en}
          </p>
          <button type="button" onClick={onBack} style={agencyDetailStyles.back} aria-label="목록으로">
            <span aria-hidden="true" style={{ fontSize: 14, lineHeight: 1 }}>←</span>
            Services
          </button>
        </div>

        {/* 데스크톱: 메인 영역을 viewport 가운데로 정렬 — 옵션 A */}
        <div style={{
          flex: 1,
          display: 'flex', flexDirection: 'column',
          justifyContent: isMobile ? 'flex-start' : 'center',
          gap: isMobile ? 0 : 48,
        }}>
        <div style={agencyDetailStyles.titleArea}>
          {!isMobile && (
            <span aria-hidden="true" style={agencyDetailStyles.watermark}>{cat.no}</span>
          )}
          <h1 style={{
            ...agencyDetailStyles.title,
            fontSize: isMobile ? '24px' : '58px',
            margin: isMobile ? '0 0 10px' : '0 0 14px',
            paddingRight: isMobile ? 0 : 200,
          }}>
            {typedBody}
            {hasDot && <span style={agencyDetailStyles.titleDot}>.</span>}
            <span style={{
              display: 'inline-block',
              width: '0.06em', height: '0.82em',
              background: '#000',
              marginLeft: '0.05em', verticalAlign: 'middle',
              animation: 'hero-cursor-blink .65s step-end infinite',
            }} />
          </h1>

          <p style={agencyDetailStyles.ko}>{cat.ko}</p>

          <p style={{ ...agencyDetailStyles.lead, paddingRight: isMobile ? 0 : 200 }}>
            {cat.lead.map((line, i) => (
              <React.Fragment key={i}>
                {line}
                {i < cat.lead.length - 1 && <br />}
              </React.Fragment>
            ))}
          </p>
        </div>

        <div style={{ ...agencyDetailStyles.listRule, margin: isMobile ? '120px 0 0' : '0' }} />

        <div style={{
          ...agencyDetailStyles.itemsGrid,
          gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)',
          gap: isMobile ? 28 : 24,
          paddingTop: isMobile ? 36 : 36,
        }}>
          {cat.items.map((it, i) => {
            // 컬럼 사이 희미한 세로 구분선 — 마지막 컬럼은 제외, 모바일에선 짝수번째 우측만 비움(2열)
            const lastIndex = cat.items.length - 1;
            const isLast = i === lastIndex;
            const skipBorderMobile = isMobile && (i + 1) % 2 === 0; // 2열일 때 오른쪽 컬럼
            const showBorder = !isLast && !skipBorderMobile;
            return (
              <div key={it.no} style={{
                ...agencyDetailStyles.itemCol,
                borderRight: showBorder ? '1px solid rgba(0,0,0,0.15)' : 'none',
              }}>
                <span style={agencyDetailStyles.itemNum}>{it.no}</span>
                <span style={agencyDetailStyles.itemName}>{it.name}</span>
                <p style={agencyDetailStyles.itemDesc}>{it.desc}</p>
              </div>
            );
          })}
        </div>
        </div>
      </section>
    </div>
  );
}

window.AgencyServiceDetail = AgencyServiceDetail;
