/* Nav.jsx — PMT Innovation */
const { useState, useEffect, useRef } = React;

const NAV_HEIGHT = 72;

function PMTNav({ page, navigate, subPage, setSubPage }) {
  const [scrolled, setScrolled] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const [mobileW, setMobileW] = useState(window.innerWidth);
  const dropdownTimer = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    const h = () => setMobileW(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);

  /* 페이지 이동 시 모바일 메뉴 닫기 */
  useEffect(() => { setMenuOpen(false); }, [page]);

  const isMobile = mobileW < 900;

  const navItems = [
    { id: 'solutions', label: '솔루션·업종별 제안', sub: ['성형·비만클리닉', '한의원', '대학교 연구소·연구기관', '의류업체', '에스테틱·필라테스'] },
    { id: 'products',  label: '제품',               sub: ['SHAPENIX', 'PFS-304', 'PFS-N304', 'Shape Care'] },
    { id: 'cases',     label: '도입사례' },
    { id: 'news',      label: '뉴스·블로그' },
  ];

  const handleMouseEnter = (id) => { clearTimeout(dropdownTimer.current); setActiveDropdown(id); };
  const handleMouseLeave = () => { dropdownTimer.current = setTimeout(() => setActiveDropdown(null), 120); };
  const isActive = (id) => page === id;

  const isTransparent = !menuOpen;
  const textColor = 'rgba(255,255,255,0.9)';
  const activeColor = '#C8271D';

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
        height: NAV_HEIGHT,
        background: (scrolled || page !== 'home') ? 'rgba(8,10,18,0.92)' : 'transparent',
        borderBottom: (scrolled || page !== 'home') ? '1px solid rgba(255,255,255,0.07)' : '1px solid transparent',
        boxShadow: (scrolled || page !== 'home') ? '0 4px 32px rgba(0,0,0,0.25)' : 'none',
        backdropFilter: (scrolled || page !== 'home') ? 'blur(20px)' : 'none',
        WebkitBackdropFilter: (scrolled || page !== 'home') ? 'blur(20px)' : 'none',
        transition: 'all 300ms cubic-bezier(0.16,1,0.3,1)',
        display: 'flex', alignItems: 'center',
        padding: isMobile ? '0 20px' : '0 48px',
      }}>
        {/* Logo */}
        <div onClick={() => navigate('home')} style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', userSelect:'none', flexShrink:0 }}>
          <img src="assets/logo.png" alt="PMT" style={{ height:38, transition:'filter 300ms' }} />
          <div style={{ fontSize:19, fontWeight:800, color: '#fff', letterSpacing:'-0.03em', lineHeight:1.1 }}>PMT Innovation Co.,Ltd</div>
        </div>

        {/* 데스크탑 네비 */}
        {!isMobile && (
          <ul style={{ display:'flex', gap:0, listStyle:'none', margin:'0 auto', padding:0, alignItems:'center' }}>
            {navItems.map(item => (
              <li key={item.id} style={{ position:'relative' }}
                onMouseEnter={() => item.sub && handleMouseEnter(item.id)}
                onMouseLeave={handleMouseLeave}
              >
                <button
                  onClick={() => { navigate(item.id); if(item.sub) setSubPage && setSubPage(null); }}
                  style={{
                    background:'none', border:'none', cursor:'pointer',
                    fontSize:14, fontWeight: isActive(item.id) ? 700 : 600,
                    color: isActive(item.id) ? activeColor : textColor,
                    padding:'24px 16px', fontFamily:'inherit', letterSpacing:'-0.02em',
                    borderBottom: isActive(item.id) ? `2px solid ${activeColor}` : '2px solid transparent',
                    transition:'color 200ms, border-color 200ms',
                    display:'flex', alignItems:'center', gap:4,
                  }}
                  onMouseEnter={e => { if(!isActive(item.id)) e.currentTarget.style.color=activeColor; }}
                  onMouseLeave={e => { if(!isActive(item.id)) e.currentTarget.style.color=textColor; }}
                >
                  {item.label}
                  {item.sub && (
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{ marginTop:1, transition:'transform 200ms', transform: activeDropdown===item.id ? 'rotate(180deg)':'rotate(0deg)' }}>
                      <path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                    </svg>
                  )}
                </button>
                {item.sub && (
                  <div
                    onMouseEnter={() => handleMouseEnter(item.id)}
                    onMouseLeave={handleMouseLeave}
                    style={{
                      position:'absolute', top:'100%', left:'50%',
                      background:'#fff', borderRadius:10, border:'1px solid #e8e8e8',
                      boxShadow:'0 16px 48px rgba(0,0,0,0.10)',
                      padding:'8px 0', minWidth:180,
                      opacity: activeDropdown===item.id ? 1 : 0,
                      pointerEvents: activeDropdown===item.id ? 'all' : 'none',
                      transform: activeDropdown===item.id ? 'translateX(-50%) translateY(0)' : 'translateX(-50%) translateY(-8px)',
                      transition:'opacity 200ms, transform 200ms', zIndex:200,
                    }}
                  >
                    {item.sub.map(sub => (
                      <button key={sub}
                        onClick={() => { navigate(item.id); setSubPage && setSubPage(sub); setActiveDropdown(null); }}
                        style={{
                          display:'block', width:'100%', textAlign:'left',
                          background:'none', border:'none', cursor:'pointer',
                          padding:'10px 20px', fontSize:13, fontWeight:600,
                          color:'#444', fontFamily:'inherit', letterSpacing:'-0.01em',
                          transition:'background 150ms, color 150ms',
                        }}
                        onMouseEnter={e => { e.currentTarget.style.background='#fafafa'; e.currentTarget.style.color='#C8271D'; }}
                        onMouseLeave={e => { e.currentTarget.style.background='none'; e.currentTarget.style.color='#444'; }}
                      >{sub}</button>
                    ))}
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}

        <div style={{ marginLeft: isMobile ? 'auto' : 0, display:'flex', alignItems:'center', gap:12 }}>
          {/* 데스크탑 CTA */}
          {!isMobile && (
            <button onClick={() => navigate('contact')} style={{
              background:'#C8271D', color:'#fff', border:'none',
              borderRadius:99, padding:'10px 24px',
              fontSize:13, fontWeight:700, cursor:'pointer',
              fontFamily:'inherit', letterSpacing:'-0.01em',
              transition:'all 200ms', flexShrink:0,
              boxShadow:'0 2px 12px rgba(200,39,29,0.25)',
            }}
              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>
          )}

          {/* 모바일 햄버거 */}
          {isMobile && (
            <button
              onClick={() => setMenuOpen(o => !o)}
              style={{ background:'none', border:'none', cursor:'pointer', padding:8, display:'flex', flexDirection:'column', gap:5, alignItems:'center', justifyContent:'center' }}
            >
              <span style={{ display:'block', width:22, height:2, background: '#fff', borderRadius:2, transition:'all 250ms', transform: menuOpen ? 'rotate(45deg) translate(5px, 5px)' : 'none' }} />
              <span style={{ display:'block', width:22, height:2, background: '#fff', borderRadius:2, transition:'all 250ms', opacity: menuOpen ? 0 : 1 }} />
              <span style={{ display:'block', width:22, height:2, background: '#fff', borderRadius:2, transition:'all 250ms', transform: menuOpen ? 'rotate(-45deg) translate(5px, -5px)' : 'none' }} />
            </button>
          )}
        </div>
      </nav>

      {/* 모바일 드로어 메뉴 */}
      {isMobile && (
        <div style={{
          position:'fixed', top: NAV_HEIGHT, left:0, right:0, bottom: menuOpen ? 0 : '100%',
          background:'rgba(8,10,18,0.96)', backdropFilter:'blur(24px)',
          zIndex:999, overflowY:'auto',
          opacity: menuOpen ? 1 : 0,
          transition:'opacity 250ms, bottom 0ms',
          pointerEvents: menuOpen ? 'all' : 'none',
        }}>
          <div style={{ padding:'16px 0 32px' }}>
            {navItems.map((item, idx) => (
              <div key={item.id}>
                <button
                  onClick={() => { navigate(item.id); setSubPage && setSubPage(null); }}
                  style={{
                    display:'flex', alignItems:'center', justifyContent:'space-between',
                    width:'100%', padding:'16px 24px', background:'none', border:'none',
                    fontSize:16, fontWeight: isActive(item.id) ? 700 : 600,
                    color: isActive(item.id) ? '#C8271D' : 'rgba(255,255,255,0.88)',
                    fontFamily:'inherit', letterSpacing:'-0.02em', cursor:'pointer',
                    borderBottom:'1px solid rgba(255,255,255,0.07)',
                  }}
                >
                  {item.label}
                  {isActive(item.id) && <span style={{ width:6, height:6, borderRadius:'50%', background:'#C8271D', display:'block' }} />}
                </button>
                {item.sub && item.sub.map(sub => (
                  <button key={sub}
                    onClick={() => { navigate(item.id); setSubPage && setSubPage(sub); }}
                    style={{
                      display:'block', width:'100%', textAlign:'left',
                      padding:'12px 24px 12px 40px', background:'none', border:'none',
                      fontSize:14, fontWeight:500, color:'rgba(255,255,255,0.45)',
                      fontFamily:'inherit', letterSpacing:'-0.01em', cursor:'pointer',
                      borderBottom:'1px solid rgba(255,255,255,0.05)',
                    }}
                  >— {sub}</button>
                ))}
              </div>
            ))}
            <div style={{ padding:'24px 24px 0' }}>
              <button onClick={() => navigate('contact')} style={{
                width:'100%', background:'#C8271D', color:'#fff', border:'none',
                borderRadius:10, padding:'14px', fontSize:15, fontWeight:700,
                cursor:'pointer', fontFamily:'inherit',
              }}>문의하기 →</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { PMTNav, NAV_HEIGHT });
