/* Chrome — shared components: Nav, Footer, Placeholder, Logo, SectionHead, Reveal */
/* global React, useT */

const { useEffect, useState, useRef } = React;

// ───── Logo ─────────────────────────────────────────────────────────

function Logo({ inverse = false }) {
  const color = inverse ? '#fff' : 'var(--ink)';
  return (
    <span className="nav__brand" style={{ color }}>
      <span className="nav__brand-mark" style={{ borderColor: color }}>Æ</span>
      <span>AESTHEFORA</span>
    </span>);

}

// ───── Nav ──────────────────────────────────────────────────────────

const NAV_KEYS = [
{ id: 'about', k: 'nav.about' },
{ id: 'education', k: 'nav.education' },
{ id: 'clinical', k: 'nav.clinical' },
{ id: 'research', k: 'nav.research' },
{ id: 'faculty', k: 'nav.faculty' },
{ id: 'contact', k: 'nav.contact' }];


function Nav({ route, onNavigate }) {
  const { t, locale, setLocale } = useT();
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

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

  // 라우트 바뀌면 모바일 메뉴 자동 닫기
  useEffect(() => { setMenuOpen(false); }, [route]);

  // 메뉴 열린 동안 body 스크롤 lock
  useEffect(() => {
    if (menuOpen) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [menuOpen]);

  const handleClick = (id) => (e) => { e.preventDefault(); setMenuOpen(false); onNavigate(id); };

  return (
    <React.Fragment>
      <nav className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
        <div className="nav__inner">
          <a href="#home" onClick={handleClick('home')} aria-label="Home">
            <Logo />
          </a>
          <ul className="nav__links" role="list">
            {NAV_KEYS.map((item) =>
            <li key={item.id}>
                <a
                href={`#${item.id}`}
                onClick={handleClick(item.id)}
                className="nav__link"
                aria-current={route === item.id ? 'page' : undefined}>

                  {t(item.k)}
                </a>
              </li>
            )}
          </ul>
          <div className="nav__right">
            <LocaleSwitcher locale={locale} setLocale={setLocale} />
            <a
              href="#partnership"
              onClick={handleClick('partnership')}
              className="btn btn--primary">

              {t('cta.partnership')}
              <span className="btn__arrow">→</span>
            </a>
          </div>
          <button
            type="button"
            className="nav__burger"
            aria-label={menuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen((v) => !v)}>
            <span className={`nav__burger-icon ${menuOpen ? 'is-open' : ''}`}>
              <span></span>
              <span></span>
              <span></span>
            </span>
          </button>
        </div>
      </nav>

      <div
        className={`nav__mobile__backdrop ${menuOpen ? 'is-open' : ''}`}
        onClick={() => setMenuOpen(false)}
        aria-hidden="true" />

      <div
        className={`nav__mobile ${menuOpen ? 'is-open' : ''}`}
        aria-hidden={!menuOpen}>
        <ul className="nav__mobile__links" role="list">
          {NAV_KEYS.map((item) =>
          <li key={item.id}>
              <a
                href={`#${item.id}`}
                onClick={handleClick(item.id)}
                className="nav__mobile__link"
                aria-current={route === item.id ? 'page' : undefined}>
                {t(item.k)}
              </a>
            </li>
          )}
        </ul>
        <div className="nav__mobile__bottom">
          <LocaleSwitcher locale={locale} setLocale={setLocale} />
          <a
            href="#partnership"
            onClick={handleClick('partnership')}
            className="btn btn--primary nav__mobile__cta">
            {t('cta.partnership')}
            <span className="btn__arrow">→</span>
          </a>
        </div>
      </div>
    </React.Fragment>);

}

// ───── Locale switcher ────────────────────────────────────────────

function LocaleSwitcher({ locale, setLocale }) {
  const opts = [
  { v: 'en', label: 'EN' },
  { v: 'ko', label: 'KO' },
  { v: 'uk', label: 'UK' }];

  return (
    <div
      role="radiogroup"
      aria-label="Language"
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 2,
        border: '1px solid var(--line)',
        borderRadius: 999,
        padding: 3,
        fontFamily: 'var(--font-mono)',
        fontSize: 11,
        letterSpacing: '0.12em',
        textTransform: 'uppercase'
      }}>
      
      {opts.map((o) =>
      <button
        key={o.v}
        type="button"
        role="radio"
        aria-checked={locale === o.v}
        onClick={() => setLocale(o.v)}
        title={`Switch to ${o.label}`}
        style={{
          padding: '4px 9px',
          borderRadius: 999,
          background: locale === o.v ? 'var(--ink)' : 'transparent',
          color: locale === o.v ? '#fff' : 'var(--ink-mute)',
          cursor: 'pointer',
          transition: 'background 0.15s, color 0.15s',
          letterSpacing: '0.12em',
          fontSize: 11,
          fontWeight: 500
        }}>
        {o.label}</button>
      )}
    </div>);

}

// ───── Footer ───────────────────────────────────────────────────────

function Footer({ onNavigate }) {
  const { t } = useT();
  const year = new Date().getFullYear();
  const linkClick = (id) => (e) => {e.preventDefault();onNavigate(id);};

  const networkItems = [
  { k: 'foot.net.1', route: 'education' },
  { k: 'foot.net.2', route: 'education' },
  { k: 'foot.net.3', route: 'research' },
  { k: 'foot.net.4', route: 'faculty' },
  { k: 'foot.net.5', route: 'clinical' }];


  return (
    <footer className="footer">
      <div className="footer__top">
        <div className="footer__col footer__brand">
          <Logo />
          <div className="display-s" style={{ marginTop: 20, maxWidth: '24ch' }}>
            {t('foot.tag')}
          </div>
          <p className="footer__addr" style={{ marginTop: 20 }}>
            {t('foot.addrLine1')}<br />
            {t('foot.addrLine2')}<br />
            {t('foot.addrLine3')}
          </p>
        </div>
        <div className="footer__col">
          <h4>{t('foot.h.site')}</h4>
          <ul>
            {NAV_KEYS.map((i) =>
            <li key={i.id}><a href={`#${i.id}`} onClick={linkClick(i.id)}>{t(i.k)}</a></li>
            )}
          </ul>
        </div>
        <div className="footer__col">
          <h4>{t('foot.h.network')}</h4>
          <ul>
            {networkItems.map((i, idx) =>
            <li key={idx}><a href={`#${i.route}`} onClick={linkClick(i.route)}>{t(i.k)}</a></li>
            )}
          </ul>
        </div>
        <div className="footer__col">
          <h4>{t('foot.h.contact')}</h4>
          <ul>
            <li>info@aesthefora.com</li>
            <li>+82 10 2785 1996</li>
            <li><a href="#contact" onClick={linkClick('contact')}>{t('foot.p.regional')}</a></li>
          </ul>
        </div>
      </div>
      <div className="footer__bottom">
        <span>{t('foot.copyright', { year })}</span>
        <span>{t('foot.certs')}</span>
      </div>
    </footer>);

}

// ───── Placeholder ──────────────────────────────────────────────────

function Placeholder({
  label = 'IMAGE',
  meta = '',
  ratio = '1/1',
  invert = false,
  className = '',
  src = '',
  alt = '',
  objectPosition = 'center',
  objectFit = 'cover',
  children = null
}) {
  const ratioClass =
  ratio === '1/1' || ratio === 'square' ? 'placeholder--square' :
  ratio === '16/9' || ratio === 'wide' ? 'placeholder--wide' :
  ratio === '4/5' || ratio === 'portrait' ? 'placeholder--portrait' : '';
  const style = ratioClass ? null : { aspectRatio: ratio };
  const hasImage = !!src;
  return (
    <div className={`placeholder ${ratioClass} ${invert ? 'placeholder--invert' : ''} ${hasImage ? 'placeholder--filled' : ''} ${className}`} style={style}>
      {hasImage ?
      <React.Fragment>
          <img
          src={src}
          alt={alt || label}
          className="placeholder__img"
          style={{ objectFit, objectPosition }}
          loading="lazy" />
        
          {meta && <div className="placeholder__corner placeholder__corner--onimg">{meta}</div>}
        </React.Fragment> :

      <React.Fragment>
          <div className="placeholder__stripes"></div>
          {meta && <div className="placeholder__corner">{meta}</div>}
          <div className="placeholder__label">{label}</div>
        </React.Fragment>
      }
      {children}
    </div>);

}

// ───── Section Header ───────────────────────────────────────────────

function SectionHead({ no, eyebrow, title, kicker }) {
  return (
    <div className="section__head">
      <div className="section__meta">
        {no && <div className="section__no">§ {no}</div>}
        {eyebrow && <div className="eyebrow eyebrow--blue">{eyebrow}</div>}
      </div>
      <div>
        <h2 className="display-m section__title">{title}</h2>
        {kicker && <p className="lede" style={{ marginTop: 20 }}>{kicker}</p>}
      </div>
    </div>);

}

// ───── Scroll reveal ────────────────────────────────────────────────

function Reveal({ children, delay = 0, as: As = 'div', className = '', style }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((en) => {
          if (en.isIntersecting) {
            setTimeout(() => el.classList.add('in'), delay);
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.12, rootMargin: '0px 0px -8% 0px' }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <As ref={ref} className={`reveal ${className}`} style={style}>{children}</As>;
}

// ───── Export ───────────────────────────────────────────────────────

Object.assign(window, {
  Logo, Nav, NAV_KEYS, Footer, Placeholder, SectionHead, Reveal, LocaleSwitcher
});