/* global React, ReactDOM, Nav, Hero, About, Services, Skills, Portfolio, MoaiCloud, Solutions, SolutionModal, Process, Contact, Footer, ResumeModal, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakSlider, TweakToggle, useTweaks, LangProvider */

const { useState, useEffect } = React;

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "default",
  "anim": "regular",
  "fontStyle": "cute",
  "snap": "off"
}/*EDITMODE-END*/;

const PALETTES = {
  default: {
    '--c-lavender': '#E0D7FF', '--c-pink': '#FFD6F0', '--c-yellow': '#FFF2C4', '--c-cyan': '#C4F1F9',
    '--bg': '#FAF7FF', '--bg-2': '#F2EDFF', '--c-purple': '#6B5BA8',
  },
  peach: {
    '--c-lavender': '#FFE4D6', '--c-pink': '#FFCFD2', '--c-yellow': '#FFF4B8', '--c-cyan': '#D4F0C7',
    '--bg': '#FFFAF5', '--bg-2': '#FFEFE3', '--c-purple': '#C4633D',
  },
  mint: {
    '--c-lavender': '#D7E9FF', '--c-pink': '#E8DFFF', '--c-yellow': '#FFE4F2', '--c-cyan': '#D8F5E3',
    '--bg': '#F5FAFF', '--bg-2': '#E8F0FF', '--c-purple': '#4A7A8F',
  },
  candy: {
    '--c-lavender': '#FFD6E0', '--c-pink': '#FFEFCF', '--c-yellow': '#C7F0DB', '--c-cyan': '#C9E4FF',
    '--bg': '#FFF7FA', '--bg-2': '#FFEEF3', '--c-purple': '#C2517C',
  },
};

function App() {
  const [t, setTweak] = useTweaks(DEFAULTS);

  // Apply palette
  useEffect(() => {
    const p = PALETTES[t.palette] || PALETTES.default;
    Object.entries(p).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
  }, [t.palette]);

  // Animation intensity — controls bob speed via root variable
  useEffect(() => {
    const factor = t.anim === 'subtle' ? '1.5' : t.anim === 'lively' ? '0.65' : '1';
    document.documentElement.style.setProperty('--anim-speed', factor);
    // Reset all bob animations
    document.querySelectorAll('.bob, .bob-slow, .twinkle, .spin-slow').forEach(el => {
      const cs = getComputedStyle(el).animationName;
      // Just nudge them — they'll already pick up new global rules if we re-set
    });
  }, [t.anim]);

  // Font style
  useEffect(() => {
    if (t.fontStyle === 'cute') {
      document.documentElement.style.setProperty('--f-display', "'Jua', system-ui, sans-serif");
      document.documentElement.style.setProperty('--f-body', "'Gowun Dodum', 'Pretendard', system-ui, sans-serif");
    } else {
      document.documentElement.style.setProperty('--f-display', "'Pretendard', system-ui, sans-serif");
      document.documentElement.style.setProperty('--f-body', "'Pretendard', system-ui, sans-serif");
    }
  }, [t.fontStyle]);

  // Scroll state
  const [scrollY, setScrollY] = useState(0);
  const [progress, setProgress] = useState(0);
  const [active, setActive] = useState('intro');
  const [openResume, setOpenResume] = useState(null);
  const [openSolution, setOpenSolution] = useState(null);

  // Snap-scroll toggle
  useEffect(() => {
    document.documentElement.classList.toggle('snap-scroll', t.snap === 'on');
  }, [t.snap]);

  // Per-section scroll-progress CSS var (0..1 as section traverses viewport)
  useEffect(() => {
    let raf = null;
    const update = () => {
      const sections = document.querySelectorAll('.section');
      const vh = window.innerHeight;
      sections.forEach(sec => {
        const r = sec.getBoundingClientRect();
        const start = vh;          // section bottom at viewport bottom = 0 progress
        const end = -r.height;     // section top at viewport top = 1 progress
        const p = 1 - (r.top - end) / (start - end);
        const clamped = Math.max(0, Math.min(1, p));
        sec.style.setProperty('--scroll-p', clamped.toFixed(3));
      });
      raf = null;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  useEffect(() => {
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        const max = document.documentElement.scrollHeight - window.innerHeight;
        setScrollY(y);
        setProgress(Math.min(100, (y / max) * 100));
        // Active section
        const sections = ['intro', 'about', 'services', 'skills', 'portfolio', 'cloud', 'solutions', 'process'];
        for (let i = sections.length - 1; i >= 0; i--) {
          const el = document.getElementById(sections[i]);
          if (el && el.getBoundingClientRect().top <= window.innerHeight * 0.4) {
            setActive(sections[i]);
            break;
          }
        }
        raf = null;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <>
      <div className="bg-field"></div>
      <div className="progress-bar" style={{ width: `${progress}%` }}></div>
      <Nav active={active} />
      <main>
        <Hero scrollY={scrollY} />
        <About onOpenResume={setOpenResume} />
        <Services />
        <Skills />
        <Portfolio />
        <MoaiCloud />
        <Solutions onOpenSolution={setOpenSolution} />
        <Process />
        <Contact />
      </main>
      <Footer />

      {openResume && (
        <ResumeModal memberId={openResume} onClose={() => setOpenResume(null)} />
      )}

      {openSolution && (
        <SolutionModal solutionId={openSolution} onClose={() => setOpenSolution(null)} />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="컬러 팔레트">
          <TweakRadio
            value={t.palette}
            onChange={v => setTweak('palette', v)}
            options={[
              { value: 'default', label: '라벤더' },
              { value: 'peach', label: '피치' },
              { value: 'mint', label: '민트' },
              { value: 'candy', label: '캔디' },
            ]}
          />
        </TweakSection>
        <TweakSection label="애니메이션">
          <TweakRadio
            value={t.anim}
            onChange={v => setTweak('anim', v)}
            options={[
              { value: 'subtle', label: '잔잔' },
              { value: 'regular', label: '보통' },
              { value: 'lively', label: '활발' },
            ]}
          />
        </TweakSection>
        <TweakSection label="폰트 스타일">
          <TweakRadio
            value={t.fontStyle}
            onChange={v => setTweak('fontStyle', v)}
            options={[
              { value: 'cute', label: '둥글둥글' },
              { value: 'clean', label: '정돈된' },
            ]}
          />
        </TweakSection>
        <TweakSection label="스크롤 스냅">
          <TweakRadio
            label="섹션 스냅"
            value={t.snap}
            onChange={v => setTweak('snap', v)}
            options={[
              { value: 'off', label: '자유 스크롤' },
              { value: 'on', label: '섹션 스냅' },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <LangProvider><App /></LangProvider>
);
