/* global React, CharLead, CharPlanner, CharDev, CharDesigner, CharDesigner2, Cloud, Star, Heart, Sparkle, Diamond, Flower, IcoBrand, IcoWeb, IcoApp, IcoRocket, IcoChart, IcoChat, IcoSwatch, IcoFlag, ProjectThumb, PortfolioMockup, WorksSection, useLang, LangSwitcher */

const { useState, useEffect, useRef } = React;

const WCS_BRAND_PATH_LANGS = new Set([
  'en', 'ko', 'ja', 'de', 'fr', 'es', 'pt', 'hi', 'id', 'vi', 'th', 'tr', 'it', 'pl', 'nl',
]);

function moaiBrandUrl(lang) {
  const locale = WCS_BRAND_PATH_LANGS.has(lang) ? lang : 'en';
  return `https://moai.page/${locale}/moai`;
}

/* =========================================================
   useReveal — IntersectionObserver hook for scroll-trigger reveal
   ========================================================= */
function useReveal(threshold = 0.15) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach(e => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
      },
      { threshold }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [threshold]);
  return [ref, seen];
}

/* =========================================================
   useTyping — typewriter effect cycling phrases
   ========================================================= */
function useTyping(phrases, speed = 90, pauseMs = 1400) {
  const [text, setText] = useState('');
  const [i, setI] = useState(0);
  const [del, setDel] = useState(false);
  useEffect(() => {
    const cur = phrases[i % phrases.length];
    let t;
    if (!del && text.length < cur.length) {
      t = setTimeout(() => setText(cur.slice(0, text.length + 1)), speed);
    } else if (!del && text.length === cur.length) {
      t = setTimeout(() => setDel(true), pauseMs);
    } else if (del && text.length > 0) {
      t = setTimeout(() => setText(cur.slice(0, text.length - 1)), speed / 2);
    } else if (del && text.length === 0) {
      setDel(false);
      setI(v => v + 1);
    }
    return () => clearTimeout(t);
  }, [text, del, i, phrases, speed, pauseMs]);
  return text;
}

/* =========================================================
   Nav
   ========================================================= */
function Nav({ active }) {
  const { t, lang } = useLang();
  const brandName = lang === 'ko' ? '우친소' : 'WCS';
  const links = [
    { id: 'intro', label: t('nav_intro') },
    { id: 'about', label: t('nav_about') },
    { id: 'services', label: t('nav_services') },
    { id: 'skills', label: t('nav_skills') },
    { id: 'portfolio', label: t('nav_portfolio') },
    { id: 'cloud', label: t('nav_cloud') },
    { id: 'solutions', label: t('nav_solutions') },
    { id: 'process', label: t('nav_process') },
  ];
  return (
    <header className="site-header">
      <div className="site-header-inner">
        <div className="brand">
          <a href="#intro" className="brand-link">
            <img src="/favicon.png" className="brand-logo" alt="WCS" />
            <span>{brandName}</span>
          </a>
          <a
            href={moaiBrandUrl(lang)}
            target="_blank"
            rel="noopener noreferrer"
            className="brand-moai"
            title="모아이 바로가기"
            aria-label="모아이 바로가기"
          >
            <img src="/images/eng_moai.png" className="brand-logo-moai" alt="모아이" />
          </a>
        </div>
        <nav className="nav">
          <div className="nav-links">
            {links.map(l => (
              <a key={l.id} href={`#${l.id}`} className={`nav-link ${active === l.id ? 'active' : ''}`}>
                {l.label}
              </a>
            ))}
          </div>
          <a href="#contact" className="nav-cta">{t('nav_cta')}</a>
        </nav>
        <div className="nav-lang">
          <LangSwitcher />
        </div>
      </div>
    </header>
  );
}

/* =========================================================
   Hero / Intro
   ========================================================= */
function Hero({ scrollY }) {
  const { t, lang } = useLang();
  const brandTitle = lang === 'ko'
    ? '우친소(WCS)'
    : lang === 'ja'
      ? 'WCS | Woochinso（ウチンソ）'
      : 'WCS | Woochinso';
  const phrases = [
    t('hero_phrase1'), t('hero_phrase2'), t('hero_phrase3'), t('hero_phrase4'),
  ];
  const organizationNote = lang === 'ko'
    ? '우친소(WCS)는 웹·앱 개발, UI/UX 디자인, 제품 기획을 제공하며 MOAI AI 앱을 운영합니다.'
    : lang === 'ja'
      ? 'WCS（ウチンソ）はWeb・アプリ開発、UI/UXデザイン、プロダクト企画を提供し、MOAI（モアイ）AIアプリを運営しています。'
      : 'WCS | Woochinso provides web and app development, UI/UX design, and product planning, and operates the MOAI AI app.';
  const typed = useTyping(phrases);

  const py = (factor) => `translateY(${scrollY * factor}px)`;

  return (
    <section className="section hero" id="intro">
      {/* Decorations with parallax */}
      <Cloud size={6} className="deco-cloud" style={{ top: 140, left: '6%', transform: py(-0.15) }} />
      <Cloud size={4} className="deco-cloud" style={{ top: 240, right: '12%', transform: py(-0.10) }} />
      <Star size={5} className="deco-star twinkle" style={{ top: 200, left: '38%', transform: py(0.10) }} />
      <Sparkle size={4} className="deco-star twinkle" style={{ top: 460, left: '10%', transform: py(0.20) }} />
      <Diamond size={4} className="deco-star twinkle" style={{ top: 720, right: '8%', transform: py(0.18) }} />
      <Heart size={4} className="deco-star" style={{ top: 600, right: '4%', transform: py(-0.08) }} />
      <Flower size={4} className="deco-cloud" style={{ bottom: 80, left: '4%', transform: py(-0.05) }} />

      <div className="section-inner" style={{ width: '100%' }}>
        <div className="hero-grid">
          <div>
            <div className="hero-eyebrow-row">
              <span className="eyebrow"><span className="eyebrow-dot"></span>{t('hero_eyebrow')}</span>
            </div>
            <h1 className="hero-title">
              <span className="hero-brand-title">{brandTitle}</span>
              <span className="under">{t('hero_line1')}</span>
              <br />
              <span className="nowrap">{t('hero_line2')}</span>
            </h1>
            <p className="hero-sub">{t('hero_sub')}</p>
            <p className="hero-sub" style={{ marginTop: 10, maxWidth: '58ch', fontSize: '0.95rem' }}>{organizationNote}</p>
            <div className="hero-typing">
              <span className="prompt">{t('hero_prompt')}</span>
              <span>{typed}</span>
              <span className="caret"></span>
            </div>
            <div className="hero-cta-row">
              <a className="btn" href="#portfolio">
                {t('hero_cta1')} <span style={{ fontSize: 18 }}>→</span>
              </a>
              <a className="btn ghost" href="#contact">
                <Heart size={2} color="#D88BB8" /> {t('hero_cta2')}
              </a>
            </div>
          </div>

          {/* Right scene — characters floating */}
          <div className="hero-scene">
            <div style={{ position: 'absolute', inset: '5% 8%', borderRadius: '50%', background: 'radial-gradient(closest-side, rgba(255, 214, 240, 0.55), transparent 75%)' }}></div>
            <div style={{ position: 'absolute', inset: '14% 22%', borderRadius: '50%', background: 'radial-gradient(closest-side, rgba(196, 241, 249, 0.40), transparent 75%)' }}></div>

            {/* Pixel ground */}
            <div style={{ position: 'absolute', left: '5%', right: '5%', bottom: '8%', height: 8, background: 'repeating-linear-gradient(90deg, #C4B6F0 0 12px, transparent 12px 22px)', borderRadius: 4 }}></div>

            <div className="hero-character bob bob-0" style={{ left: '12%', bottom: '14%' }}>
              <CharLead size={6} />
            </div>
            <div className="hero-character bob bob-2" style={{ left: '37%', bottom: '14%' }}>
              <CharDesigner size={6} />
            </div>
            <div className="hero-character bob bob-3" style={{ left: '62%', bottom: '14%' }}>
              <CharPlanner size={6} />
            </div>
            <div className="hero-character bob bob-0" style={{ left: '87%', bottom: '14%' }}>
              <CharDev size={6} />
            </div>

            {/* Floating stat cards */}
            <div className="hero-stat-card bob bob-2" style={{ top: '10%', right: '0%' }}>
              <Star size={3} color="#D4A82E" />
              <div>
                <div className="num">{t('hero_stat1_num')}</div>
                <div className="label">{t('hero_stat1_label')}</div>
              </div>
            </div>
            <div className="hero-stat-card bob bob-1" style={{ top: '38%', left: '-8%' }}>
              <Sparkle size={3} color="#8B7BC4" />
              <div>
                <div className="num">{t('hero_stat2_num')}</div>
                <div className="label">{t('hero_stat2_label')}</div>
              </div>
            </div>

            {/* Tiny floating sparkles */}
            <Sparkle size={3} className="twinkle" style={{ position: 'absolute', top: '18%', left: '50%' }} />
            <Sparkle size={3} className="twinkle" style={{ position: 'absolute', top: '60%', right: '5%', animationDelay: '-1s' }} />
            <Star size={3} className="twinkle" style={{ position: 'absolute', top: '70%', left: '8%', animationDelay: '-1.5s' }} color="#FFE89A" />
          </div>
        </div>
      </div>

      <div className="scroll-cue">
        <div className="scroll-cue-mouse"></div>
        <span>{t('scroll')}</span>
      </div>
    </section>
  );
}

/* =========================================================
   About
   ========================================================= */

Object.assign(window, { Nav, Hero, useReveal });
