// v5 — grounded industrial. Reuses v4-core data (V4_PRODUCTS / V4_CATS / V4_CAPABILITY / Rise / useInView / CountUp).

// ╔══════════════════════════════════════════════════════════════╗
// ║  회사 대표 이메일 — 실제 주소로 바꾸실 곳은 아래 한 줄뿐입니다.   ║
// ║  따옴표 안의 주소만 고치면 사이트 전체(안내 박스, 복사 버튼,     ║
// ║  연락처 카드, 접수 완료 화면)에 한 번에 반영됩니다.             ║
// ╚══════════════════════════════════════════════════════════════╝
const TSENG_EMAIL = 'tesung3951@naver.com';

// ─── Palette: deep graphite base, warm bone text, one restrained steel blue ───
const D = {
  base:   '#0B0F14',   // page
  base2:  '#111721',   // raised band
  base3:  '#161D28',   // card
  line:   'rgba(237,235,231,0.13)',
  line2:  'rgba(237,235,231,0.07)',
  bone:   '#EDEBE7',
  bone70: 'rgba(237,235,231,0.70)',
  bone45: 'rgba(237,235,231,0.52)',
  bone28: 'rgba(237,235,231,0.30)',
  steel:  '#4C7ACF',   // accent — used sparingly
  steelD: '#2F5AA8',
};

// ─── Micro label ───
function Tag5({ children, tone = 'steel', style = {} }) {
  return (
    <span className="mono" style={{
      display: 'inline-block', fontSize: 10.5, fontWeight: 500,
      letterSpacing: '0.22em', textTransform: 'uppercase',
      color: tone === 'steel' ? D.steel : tone === 'mute' ? D.bone45 : D.bone,
      ...style,
    }}>{children}</span>
  );
}

// ─── Heading ───
function H5({ children, size = 'clamp(30px,3.6vw,58px)', color = D.bone, style = {} }) {
  return (
    <h2 style={{
      fontSize: size, fontWeight: 700, lineHeight: 1.06,
      letterSpacing: '-0.042em', color, textWrap: 'pretty', ...style,
    }}>{children}</h2>
  );
}

// ─── Button: square, quiet, deliberate ───
function B5({ children, href = '#', onClick, tone = 'solid', size = 'md' }) {
  const [h, setH] = useState(false);
  const pad = size === 'lg' ? '17px 30px' : size === 'sm' ? '10px 17px' : '14px 24px';
  const fs  = size === 'lg' ? 14 : size === 'sm' ? 12.5 : 13.5;
  const map = {
    solid: { bg: h ? D.bone : D.steel, fg: h ? D.base : '#fff', bd: 'transparent' },
    line:  { bg: h ? 'rgba(237,235,231,0.09)' : 'transparent', fg: D.bone, bd: h ? D.bone : D.line },
    ghost: { bg: 'transparent', fg: h ? D.bone : D.bone70, bd: 'transparent' },
  }[tone];
  return (
    <a href={href} onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      className="b5"
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: pad,
        fontSize: fs, fontWeight: 600, letterSpacing: '-0.012em', cursor: 'pointer',
        background: map.bg, color: map.fg, border: `1px solid ${map.bd}`,
        transition: 'background .45s cubic-bezier(.2,.7,.3,1), color .45s, border-color .45s',
      }}>
      {children}
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
        strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
        style={{ transform: h ? 'translateX(3px)' : 'none', transition: 'transform .45s cubic-bezier(.2,.7,.3,1)' }}>
        <path d="M5 12h13M12 5.5 18.5 12 12 18.5"/>
      </svg>
    </a>
  );
}

// ─── Section shell: consistent rhythm ───
function Sec5({ id, children, bg = D.base, pad = 'clamp(88px,12vh,168px)', style = {} }) {
  return (
    <section id={id} style={{ background: bg, paddingTop: pad, paddingBottom: pad, ...style }}>
      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '0 clamp(20px,4vw,60px)' }}>
        {children}
      </div>
    </section>
  );
}

// ─── Media slot with an opaque designed fallback until a photo is dropped ───
// tint  = 하단이 진해지는 기본 스크림 (히어로용, 사진 위 큰 글씨)
// solid = true 면 위쪽까지 고르게 덮습니다. 흰 벽·금속판처럼
//         밝은 사진 위에 작은 글씨를 얹는 카드에 쓰세요.
function Media5({ id, label, ratio, tint = 0.5, solid = false, children, minH, src, eager = false }) {
  const ref = useRef(null);
  const [filled, setFilled] = useState(!!src);
  useEffect(() => {
    if (src) return;
    const t = setInterval(() => {
      const sr = ref.current && ref.current.shadowRoot;
      const has = !!sr && Array.from(sr.querySelectorAll('img')).some(i => i.currentSrc && i.naturalWidth > 0);
      setFilled(v => (v === has ? v : has));
    }, 700);
    return () => clearInterval(t);
  }, [src]);
  return (
    <div style={{ position: 'relative', overflow: 'hidden', aspectRatio: ratio, minHeight: minH, background: D.base2 }}>
      {src ? (
        <img src={src} alt="" loading={eager ? 'eager' : 'lazy'} decoding="async"
          fetchpriority={eager ? 'high' : 'low'}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}/>
      ) : (
        <div style={{ position: 'absolute', inset: 0 }}>
          <image-slot ref={ref} id={id} shape="rect" fit="cover" placeholder={label}
            style={{ width: '100%', height: '100%' }}></image-slot>
        </div>
      )}
      {/* opaque designed layer hides the empty-state affordance */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        opacity: filled ? 0 : 1, transition: 'opacity .8s ease',
        background: `radial-gradient(130% 100% at 72% 22%, ${D.base3} 0%, ${D.base2} 52%, ${D.base} 100%)`,
      }}>
        <div style={{
          position: 'absolute', inset: 0, opacity: .55,
          backgroundImage: `linear-gradient(${D.line2} 1px, transparent 1px), linear-gradient(90deg, ${D.line2} 1px, transparent 1px)`,
          backgroundSize: '76px 76px',
          maskImage: 'radial-gradient(76% 68% at 66% 40%, #000 0%, transparent 80%)',
          WebkitMaskImage: 'radial-gradient(76% 68% at 66% 40%, #000 0%, transparent 80%)',
        }}/>
      </div>
      {tint > 0 && (
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: solid
            ? `linear-gradient(to top, rgba(9,12,17,${Math.min(tint + 0.32, 0.96)}) 0%, rgba(9,12,17,${Math.min(tint + 0.1, 0.9)}) 45%, rgba(9,12,17,${Math.max(tint - 0.15, 0.34)}) 100%)`
            : `linear-gradient(to top, rgba(9,12,17,${tint + 0.34}) 0%, rgba(9,12,17,${tint * 0.5}) 46%, rgba(9,12,17,${tint * 0.22}) 100%)`,
        }}/>
      )}
      {children}
      {!src && <MediaBtn5 slotRef={ref} filled={filled}/>}
    </div>
  );
}

function MediaBtn5({ slotRef, filled }) {
  const [h, setH] = useState(false);
  return (
    <button onClick={() => slotRef.current && slotRef.current.click()}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        position: 'absolute', right: 14, bottom: 14, zIndex: 4,
        display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px',
        border: `1px solid ${h ? 'rgba(237,235,231,.45)' : 'rgba(237,235,231,.2)'}`,
        background: h ? 'rgba(9,12,17,.72)' : 'rgba(9,12,17,.5)',
        backdropFilter: 'blur(10px)', color: h ? D.bone : D.bone70,
        fontSize: 11, fontWeight: 600, cursor: 'pointer', transition: 'all .3s',
      }}>
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/>
      </svg>
      {filled ? '사진 교체' : '사진 넣기'}
    </button>
  );
}

// ─── Hero slides ───
// ══ 히어로 배경 사진 ══
// src 경로만 바꾸면 배경이 교체됩니다. src를 지우면 드래그앤드롭 업로드 슬롯으로 바뀝니다.
// 여분 사진: photos/factory/spare-*.png (교체용으로 보관 중)
const V5_SLIDES = [
  {
    tag: 'Taesung Engineering',
    ko: <>정밀한 기술로<br/>신뢰를 완성합니다.</>,
    en: <>Precision that<br/>completes trust.</>,
    subKo: '조립식 건축 부속자재부터 정밀 금속가공까지 한 곳에서 책임집니다.',
    subEn: 'Prefab building components and precision metalwork — one shop, drawing to finished part.',
    ctaKo: '제품 · 규격 보기', ctaEn: 'View products', href: '#products',
    slot: 'v5-hero-1', slotKo: 'CNC선반 내부', src: 'photos/site/cnc-interior-clean.webp',
  },
  {
    tag: 'Fabrication',
    ko: <>도면대로,<br/>공차 안에서.</>,
    en: <>To the drawing,<br/>inside tolerance.</>,
    subKo: '시제품 소량부터 반복 양산까지, 요구 공차에 맞춰 제작합니다.',
    subEn: 'From small prototype runs to repeat production, built to your tolerance.',
    ctaKo: '제작 역량 보기', ctaEn: 'Our capability', href: '#capability',
    slot: 'v5-hero-2', slotKo: 'CNC 제어 패널', src: 'photos/factory/cnc-control-panel.webp',
  },
  {
    tag: 'Delivery',
    ko: <>제작건에 맞춘<br/>빠른 납기 대응.</>,
    en: <>Lead times built<br/>around the job.</>,
    subKo: '수량과 사양에 맞춰 현실적인 일정을 안내합니다.',
    subEn: 'A realistic schedule for your volume and spec.',
    ctaKo: '제작 문의', ctaEn: 'Request a quote', href: '#contact',
    slot: 'v5-hero-3', slotKo: '자재 보유 현황', src: 'photos/site/pipes-coils-clean.webp',
  },
];

const V5_MARQUEE = [
  '조립식 건축 부속자재', 'CNC선반 가공', '금형 · 프레스', '편철 · 앵글 용접',
  '크랭크로라', '편개 · 양개 도어', '스톱바', '브라켓', '도면 기반 주문제작',
];

Object.assign(window, { D, TSENG_EMAIL, Tag5, H5, B5, Sec5, Media5, MediaBtn5, V5_SLIDES, V5_MARQUEE });
