// karm.dev — App orchestrator

const { useState, useEffect, useCallback } = React;

// Edit-mode persisted defaults
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "heroVariant": "terminal",
  "lang": "es",
  "sectionProjects": true,
  "sectionExperience": true,
  "sectionSkills": true,
  "sectionContact": true
}/*EDITMODE-END*/;

function App() {
  // load persisted state
  const [theme, setTheme] = useState(() => {
    try { return localStorage.getItem('karm_theme') || TWEAK_DEFAULTS.theme; } catch { return TWEAK_DEFAULTS.theme; }
  });
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem('karm_lang') || TWEAK_DEFAULTS.lang; } catch { return TWEAK_DEFAULTS.lang; }
  });
  const [heroVariant, setHeroVariant] = useState(() => {
    try { return localStorage.getItem('karm_hero') || TWEAK_DEFAULTS.heroVariant; } catch { return TWEAK_DEFAULTS.heroVariant; }
  });
  const [sections, setSections] = useState({
    projects: TWEAK_DEFAULTS.sectionProjects,
    experience: TWEAK_DEFAULTS.sectionExperience,
    skills: TWEAK_DEFAULTS.sectionSkills,
    contact: TWEAK_DEFAULTS.sectionContact,
  });

  const [current, setCurrent] = useState('home');
  const [introDone, setIntroDone] = useState(() => {
    try { return sessionStorage.getItem('karm_intro_v2') === '1'; } catch { return false; }
  });
  const [editMode, setEditMode] = useState(false);

  // persist theme
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    try { localStorage.setItem('karm_theme', theme); } catch {}
  }, [theme]);
  useEffect(() => { try { localStorage.setItem('karm_lang', lang); } catch {} }, [lang]);
  useEffect(() => { try { localStorage.setItem('karm_hero', heroVariant); } catch {} }, [heroVariant]);

  // translation helper
  const t = useCallback((key) => {
    const dict = I18N[lang] || I18N.es;
    return dict[key] ?? key;
  }, [lang]);

  const scrollTo = (id) => {
    setCurrent(id);
    if (id === 'home') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      const el = document.getElementById(id);
      if (el) {
        const y = el.getBoundingClientRect().top + window.pageYOffset - 72;
        window.scrollTo({ top: y, behavior: 'smooth' });
      }
    }
  };

  const downloadCV = () => {
    const a = document.createElement('a');
    a.href = 'assets/Kevin_Rosales_CV_AI_Engineer_EN_v2.pdf';
    a.download = 'Kevin_Rosales_CV.pdf';
    a.target = '_blank';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  // intro done -> persist
  useEffect(() => {
    if (introDone) { try { sessionStorage.setItem('karm_intro_v2', '1'); } catch {} }
  }, [introDone]);

  // Edit mode protocol
  useEffect(() => {
    const handler = (event) => {
      if (!event.data || !event.data.type) return;
      if (event.data.type === '__activate_edit_mode') setEditMode(true);
      else if (event.data.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', handler);
    // announce after listener is attached
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', handler);
  }, []);

  const persistTweak = (patch) => {
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
  };

  const handleSetTheme = (v) => { setTheme(v); persistTweak({ theme: v }); };
  const handleSetHero = (v) => { setHeroVariant(v); persistTweak({ heroVariant: v }); };
  const handleSetSections = (next) => {
    setSections(next);
    persistTweak({
      sectionProjects: next.projects,
      sectionExperience: next.experience,
      sectionSkills: next.skills,
      sectionContact: next.contact,
    });
  };
  const handleSetLang = (v) => { setLang(v); persistTweak({ lang: v }); };

  return (
    <div>
      {!introDone && <IntroAnimation onDone={() => setIntroDone(true)} />}

      <Nav
        current={current} onNavigate={scrollTo}
        lang={lang} onLang={handleSetLang}
        theme={theme} onTheme={handleSetTheme}
        sections={sections}
        t={t}
      />

      <Hero
        variant={heroVariant}
        lang={lang}
        t={t}
        onPrimary={() => scrollTo('contacto')}
        onSecondary={() => scrollTo('proyectos')}
        onCV={downloadCV}
      />

      {sections.projects && <ProjectsSection lang={lang} t={t} />}
      {sections.experience && <ExperienceSection lang={lang} t={t} />}
      {sections.skills && <SkillsSection lang={lang} t={t} />}
      {sections.contact && <ContactSection lang={lang} t={t} />}

      <Footer t={t} />

      <TweaksPanel
        visible={editMode}
        onClose={() => setEditMode(false)}
        theme={theme} setTheme={handleSetTheme}
        heroVariant={heroVariant} setHeroVariant={handleSetHero}
        sections={sections} setSections={handleSetSections}
        t={t}
      />
    </div>
  );
}

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