// v5 — Nav, Hero carousel, Marquee, Pillars

// ═════════ NAV ═════════
function Nav5() {
  const [sc, setSc] = useState(false);
  const t = useV4(); const ko = t.lang !== 'en';
  useEffect(() => {
    const f = () => setSc(window.scrollY > 20);
    window.addEventListener('scroll', f, { passive: true });
    return () => window.removeEventListener('scroll', f);
  }, []);
  const items = [
    { ko: '회사소개', en: 'Company', id: 'company' },
    { ko: '사업분야', en: 'Scope', id: 'pillars' },
    { ko: '제작역량', en: 'Capability', id: 'capability' },
    { ko: '제품 · 규격', en: 'Products', id: 'products' },
    { ko: '자주 묻는 질문', en: 'FAQ', id: 'faq' },
    { ko: '오시는 길', en: 'Location', id: 'location' },
  ];
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 90, height: 72,
      background: sc ? 'rgba(11,15,20,0.82)' : 'transparent',
      backdropFilter: sc ? 'blur(18px) saturate(1.3)' : 'none',
      borderBottom: `1px solid ${sc ? D.line2 : 'transparent'}`,
      transition: 'background .5s ease, border-color .5s ease',
    }}>
      <div className="nav5-bar" style={{
        maxWidth: 1400, margin: '0 auto', height: '100%',
        padding: '0 clamp(20px,4vw,60px)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24,
      }}>
        <a href="#top" id="top-logo" style={{ display: 'flex', alignItems: 'baseline', gap: 9 }}>
          <span style={{ fontSize: 21, fontWeight: 700, letterSpacing: '-0.05em', color: D.bone }}>태성ENG</span>
          <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.2em', color: D.bone28, textTransform: 'uppercase' }}>Taesung</span>
        </a>
        <nav className="nav5-links">
          {items.map(n => <NavItem5 key={n.id} href={`#${n.id}`}>{ko ? n.ko : n.en}</NavItem5>)}
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 'clamp(8px,1.2vw,16px)' }}>
          <LangSwitch5/>
          <span className="nav5-cta"><B5 href="#contact" size="sm" tone="line">{ko ? '제작 문의' : 'Contact'}</B5></span>
        </div>
      </div>
    </header>
  );
}
// ── 언어 전환 (상단 네비) — 방문자용. 편집 도구의 Tweaks 패널과는 별개입니다 ──
function LangSwitch5() {
  const t = useV4();
  const cur = t.lang === 'en' ? 'en' : 'ko';
  return (
    <div style={{ display: 'flex', alignItems: 'center', border: `1px solid ${D.line2}` }}>
      {[['ko', 'KO'], ['en', 'EN']].map(([v, l], i) => (
        <button key={v} onClick={() => t.setLang && t.setLang(v)}
          aria-label={v === 'ko' ? '한국어' : 'English'}
          aria-pressed={cur === v}
          className="mono lang5"
          style={{
            padding: '8px 12px', cursor: 'pointer',
            fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em',
            background: cur === v ? 'rgba(237,235,231,.1)' : 'transparent',
            color: cur === v ? D.bone : D.bone28,
            borderLeft: i === 1 ? `1px solid ${D.line2}` : 'none',
            transition: 'background .3s, color .3s',
          }}>{l}</button>
      ))}
    </div>
  );
}

function NavItem5({ children, href }) {
  const [h, setH] = useState(false);
  return (
    <a href={href} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ position: 'relative', padding: '10px 15px', fontSize: 13.5, fontWeight: 500, letterSpacing: '-0.012em', color: h ? D.bone : D.bone70, transition: 'color .3s' }}>
      {children}
      <span style={{
        position: 'absolute', left: 15, right: 15, bottom: 4, height: 1,
        background: D.steel, transform: h ? 'scaleX(1)' : 'scaleX(0)', transformOrigin: 'left',
        transition: 'transform .5s cubic-bezier(.2,.7,.3,1)',
      }}/>
    </a>
  );
}

// ═════════ HERO — media carousel, numbered rail ═════════
const HERO_MS = 7000;

function Hero5() {
  const t = useV4(); const ko = t.lang !== 'en';
  const [i, setI] = useState(0);
  const [key, setKey] = useState(0);   // restarts the rail animation
  const n = V5_SLIDES.length;

  useEffect(() => {
    const id = setTimeout(() => { setI(v => (v + 1) % n); setKey(k => k + 1); }, HERO_MS);
    return () => clearTimeout(id);
  }, [i, key, n]);

  const go = (v) => { setI(v); setKey(k => k + 1); };
  const s = V5_SLIDES[i];

  return (
    <section id="top" style={{ position: 'relative', minHeight: '100svh', overflow: 'hidden', background: D.base }}>
      {/* stacked media layers */}
      {V5_SLIDES.map((sl, idx) => (
        <div key={sl.slot} style={{
          position: 'absolute', inset: 0,
          opacity: idx === i ? 1 : 0,
          transition: 'opacity 1.4s cubic-bezier(.4,0,.2,1)',
          pointerEvents: idx === i ? 'auto' : 'none',
        }}>
          <Media5 id={sl.slot} src={sl.src} label={ko ? sl.slotKo : 'Background photo'} tint={0.46} minH="100svh" eager={idx === 0}/>
        </div>
      ))}

      {/* left edge scrim so text always reads */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(100deg, rgba(9,12,17,.93) 0%, rgba(9,12,17,.82) 34%, rgba(9,12,17,.42) 64%, rgba(9,12,17,.22) 100%)',
      }}/>

      {/* content */}
      <div style={{
        position: 'relative', zIndex: 3, minHeight: '100svh',
        maxWidth: 1400, margin: '0 auto',
        padding: '110px clamp(20px,4vw,60px) clamp(32px,6vh,64px)',
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
        pointerEvents: 'none',
      }}>
        <div className="g5-hero">
          <div key={i} style={{ pointerEvents: 'auto', animation: 'none' }}>
            <div style={{ opacity: 0, animation: 'v5in .9s cubic-bezier(.2,.7,.3,1) .05s forwards' }}>
              <Tag5>{s.tag}</Tag5>
            </div>
            <div style={{ opacity: 0, animation: 'v5in 1s cubic-bezier(.2,.7,.3,1) .14s forwards' }}>
              <h1 style={{
                marginTop: 22, fontSize: 'clamp(38px,5.6vw,92px)', fontWeight: 700,
                lineHeight: .99, letterSpacing: '-0.05em', color: D.bone,
              }}>{ko ? s.ko : s.en}</h1>
            </div>
            <div style={{ opacity: 0, animation: 'v5in 1s cubic-bezier(.2,.7,.3,1) .26s forwards' }}>
              <p style={{ marginTop: 26, maxWidth: 560, fontSize: 16.5, lineHeight: 1.76, color: D.bone70 }}>
                {ko ? s.subKo : s.subEn}
              </p>
            </div>
            <div style={{ opacity: 0, animation: 'v5in 1s cubic-bezier(.2,.7,.3,1) .38s forwards', marginTop: 38, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <B5 href={s.href} tone="solid" size="lg">{ko ? s.ctaKo : s.ctaEn}</B5>
              <B5 href="#contact" tone="line" size="lg">{ko ? '견적 요청' : 'Get a quote'}</B5>
            </div>
          </div>

          {/* numbered rail */}
          <div className="h5-rail" style={{ pointerEvents: 'auto', display: 'flex', flexDirection: 'column', gap: 2, alignSelf: 'end' }}>
            {V5_SLIDES.map((sl, idx) => {
              const on = idx === i;
              return (
                <button key={sl.slot} onClick={() => go(idx)} style={{
                  display: 'grid', gridTemplateColumns: '34px 1fr', alignItems: 'center', gap: 14,
                  padding: '15px 0', cursor: 'pointer', textAlign: 'left', minHeight: 48,
                  borderTop: `1px solid ${D.line2}`,
                }}>
                  <span className="mono" style={{
                    fontSize: 11, fontWeight: 500, letterSpacing: '0.1em',
                    color: on ? D.bone : D.bone28, transition: 'color .5s',
                  }}>{String(idx + 1).padStart(2, '0')}</span>
                  <span style={{ position: 'relative', display: 'block' }}>
                    <span style={{
                      display: 'block', fontSize: 13, fontWeight: 500, letterSpacing: '-0.015em',
                      color: on ? D.bone : D.bone45, transition: 'color .5s', marginBottom: 9,
                    }}>{sl.tag}</span>
                    <span style={{ display: 'block', height: 2, background: D.line, position: 'relative', overflow: 'hidden' }}>
                      {on && (
                        <span key={key} style={{
                          position: 'absolute', inset: 0, background: D.steel,
                          transformOrigin: 'left', transform: 'scaleX(0)',
                          animation: `v5fill ${HERO_MS}ms linear forwards`,
                        }}/>
                      )}
                    </span>
                  </span>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes v5in{from{opacity:0;transform:translateY(22px)}to{opacity:1;transform:none}}
        @keyframes v5fill{from{transform:scaleX(0)}to{transform:scaleX(1)}}
      `}</style>
    </section>
  );
}

// ═════════ MARQUEE ═════════
function Marquee5() {
  const row = [...V5_MARQUEE, ...V5_MARQUEE];
  return (
    <div style={{ background: D.base, borderTop: `1px solid ${D.line2}`, borderBottom: `1px solid ${D.line2}`, overflow: 'hidden', padding: '20px 0' }}>
      <div style={{ display: 'flex', width: 'max-content', animation: 'm5-marquee 46s linear infinite' }}>
        {row.map((w, i) => (
          <span key={i} className="mono" style={{
            display: 'inline-flex', alignItems: 'center', gap: 30, paddingRight: 30,
            fontSize: 11.5, letterSpacing: '0.16em', textTransform: 'uppercase',
            color: D.bone28, whiteSpace: 'nowrap',
          }}>
            {w}<span style={{ width: 3, height: 3, background: D.steel, opacity: .6 }}/>
          </span>
        ))}
      </div>
    </div>
  );
}

// ═════════ PILLARS — two large media cards ═════════
function Pillars5() {
  const t = useV4(); const ko = t.lang !== 'en';
  const cards = [
    {
      slot: 'v5-pillar-1', slotKo: '조립식 건물 · 부속자재 사진', src: 'photos/site/forming-line-card.webp',
      tag: 'Building Components',
      ko: '조립식 건축 부속자재', en: 'Prefab building components',
      dKo: '브라켓, 로라, 도어 부속, 스톱바 등 현장 조건에 맞춰 제작합니다. 규격품과 도면 기반 주문제작을 함께 대응합니다.',
      dEn: 'Brackets, rollers, door hardware and stop bars built to site conditions — stock sizes and drawing-based custom work.',
      href: '#products',
    },
    {
      slot: 'v5-pillar-2', slotKo: '가공 설비 · 용접 사진', src: 'photos/factory/cnc-chuck.webp',
      tag: 'Metal Fabrication',
      ko: '정밀 금속가공 · 제작', en: 'Precision metal fabrication',
      dKo: 'CNC선반 가공, 금형·프레스, 편철·앵글 용접을 자체 설비로 수행합니다. 시제품 소량부터 반복 양산까지 일관 생산합니다.',
      dEn: 'CNC turning, die & press work and angle welding in-house — from small prototype runs to repeat production.',
      href: '#capability',
    },
  ];
  return (
    <Sec5 id="pillars">
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap', marginBottom: 'clamp(36px,5vh,64px)' }}>
        <Rise>
          <Tag5>What we do</Tag5>
          <H5 style={{ marginTop: 18, maxWidth: 720 }}>
            {ko ? <>두 개의 축으로<br/>현장의 요구에 대응합니다.</> : <>Two lines of work,<br/>one standard of precision.</>}
          </H5>
        </Rise>
        <Rise delay={.1}>
          <p style={{ maxWidth: 480, fontSize: 15, lineHeight: 1.78, color: D.bone45 }}>
            {ko
              ? <>부속자재 제조와 금속가공 —<br/>두 영역을 한 공장에서 운영해 설계 변경과 납기 조정에 빠르게 대응합니다.</>
              : 'Component manufacturing and metal fabrication under one roof — fast to absorb design changes and schedule shifts.'}
          </p>
        </Rise>
      </div>

      <div className="g5-two">
        {cards.map((c, i) => (
          <Rise key={c.slot} delay={i * .1} y={34}>
            <PillarCard5 c={c} ko={ko}/>
          </Rise>
        ))}
      </div>
    </Sec5>
  );
}

function PillarCard5({ c, ko }) {
  const [h, setH] = useState(false);
  return (
    <a href={c.href} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      onFocus={() => setH(true)} onBlur={() => setH(false)}
      style={{
        display: 'block', position: 'relative', overflow: 'hidden',
        border: `1px solid ${h ? D.line : D.line2}`, transition: 'border-color .5s',
        background: D.base2, outline: 'none',
      }}>
      {/* 호버 시 사진이 살짝 확대되면서 어두워집니다 */}
      <div style={{
        transform: h ? 'scale(1.045)' : 'scale(1)',
        filter: h ? 'brightness(.78) saturate(1.05)' : 'brightness(1)',
        transition: 'transform 1.1s cubic-bezier(.2,.7,.3,1), filter .6s ease',
      }}>
        {/* solid 스크림 — 밝은 사진(흰 벽·금속판) 위에서도 작은 글씨가 읽히게 합니다.
            solid를 빼거나 tint를 낮추면 카드 위 흰 글씨가 하이라이트에 묻힙니다. */}
        <Media5 id={c.slot} src={c.src} label={ko ? c.slotKo : 'Photo'} ratio="16/11" tint={0.58} solid/>
      </div>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: 'clamp(22px,2.6vw,38px)', pointerEvents: 'none' }}>
        {/* 호버 시 왼쪽에서 자라나는 강조 라인 */}
        <span style={{
          display: 'block', height: 2, width: h ? 46 : 0, marginBottom: h ? 16 : 0,
          background: D.steel, opacity: h ? 1 : 0,
          transition: 'width .6s cubic-bezier(.2,.7,.3,1), margin-bottom .6s cubic-bezier(.2,.7,.3,1), opacity .4s',
        }}/>
        <Tag5 tone={h ? 'bone' : 'mute'} style={{ transition: 'color .45s' }}>{c.tag}</Tag5>
        <h3 style={{
          marginTop: 14, fontSize: 'clamp(21px,2.3vw,32px)', fontWeight: 700,
          letterSpacing: '-0.038em', lineHeight: 1.14, color: D.bone,
        }}>{ko ? c.ko : c.en}</h3>
        <p style={{
          marginTop: 13, maxWidth: 420, fontSize: 14.5, lineHeight: 1.74,
          color: h ? D.bone : D.bone70, transition: 'color .45s',
        }}>
          {ko ? c.dKo : c.dEn}
        </p>
        <span style={{
          marginTop: 20, display: 'inline-flex', alignItems: 'center', gap: 9,
          fontSize: 13, fontWeight: 600, color: h ? D.bone : D.bone70, transition: 'color .4s',
        }}>
          {ko ? '자세히 보기' : 'Learn more'}
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
            style={{ transform: h ? 'translateX(4px)' : 'none', transition: 'transform .5s cubic-bezier(.2,.7,.3,1)' }}>
            <path d="M5 12h13M12 5.5 18.5 12 12 18.5"/>
          </svg>
        </span>
      </div>
    </a>
  );
}

Object.assign(window, { Nav5, NavItem5, LangSwitch5, Hero5, Marquee5, Pillars5, PillarCard5 });
