/* =====================================================================
   Future Consulting — shared React shell
   - I18nProvider / useI18n / useT hook
   - useReveal IntersectionObserver hook
   - <Logo />, <Nav />, <Footer />, <LanguageToggle />
   - <ArrowIcon />, <PlusIcon />, etc — minimal Lucide-style strokes
   ===================================================================== */

const { useState, useEffect, useRef, useContext, createContext, useCallback, useMemo } = React;

/* ---------- i18n ---------- */
const I18nContext = createContext({ lang: 'hu', t: window.FCS_I18N.hu, setLang: () => {} });

function I18nProvider({ children }) {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem('fcs-lang') || 'hu'; } catch { return 'hu'; }
  });
  useEffect(() => {
    try { localStorage.setItem('fcs-lang', lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);
  const value = useMemo(() => ({ lang, t: window.FCS_I18N[lang], setLang }), [lang]);
  return React.createElement(I18nContext.Provider, { value }, children);
}
function useI18n() { return useContext(I18nContext); }

/* ---------- Reveal-on-scroll ---------- */
function useReveal(options = {}) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            el.classList.add('in');
            obs.unobserve(el);
          }
        });
      },
      { threshold: 0.15, rootMargin: '0px 0px -10% 0px', ...options }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}

/* ---------- Icons (Lucide-style, 1.75 stroke) ---------- */
const Icon = ({ children, size = 18, className = '', style = {} }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={className} style={style} aria-hidden="true">
    {children}
  </svg>
);
const ArrowRight = (p) => <Icon {...p}><path d="M5 12h14M13 5l7 7-7 7"/></Icon>;
const ArrowUpRight = (p) => <Icon {...p}><path d="M7 17L17 7M8 7h9v9"/></Icon>;
const Plus = (p) => <Icon {...p}><path d="M12 5v14M5 12h14"/></Icon>;
const Check = (p) => <Icon {...p}><path d="M20 6L9 17l-5-5"/></Icon>;
const Spark = (p) => <Icon {...p}><path d="M12 2v4M12 18v4M2 12h4M18 12h4M5 5l3 3M16 16l3 3M5 19l3-3M16 8l3-3"/></Icon>;
const Network = (p) => <Icon {...p}><circle cx="12" cy="12" r="2"/><circle cx="4" cy="6" r="2"/><circle cx="20" cy="6" r="2"/><circle cx="4" cy="18" r="2"/><circle cx="20" cy="18" r="2"/><path d="M6 6l4.5 4.5M18 6l-4.5 4.5M6 18l4.5-4.5M18 18l-4.5-4.5"/></Icon>;
const Server = (p) => <Icon {...p}><rect x="3" y="3" width="18" height="7" rx="1.5"/><rect x="3" y="14" width="18" height="7" rx="1.5"/><path d="M7 6.5h.01M7 17.5h.01"/></Icon>;
const Monitor = (p) => <Icon {...p}><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></Icon>;
const Activity = (p) => <Icon {...p}><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></Icon>;
const Layers = (p) => <Icon {...p}><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></Icon>;
const Compass = (p) => <Icon {...p}><circle cx="12" cy="12" r="10"/><path d="M16.24 7.76l-2.12 6.36-6.36 2.12 2.12-6.36 6.36-2.12z"/></Icon>;
const Globe = (p) => <Icon {...p}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2c2.5 3 4 7 4 10s-1.5 7-4 10c-2.5-3-4-7-4-10s1.5-7 4-10z"/></Icon>;
const Menu = (p) => <Icon {...p}><path d="M4 6h16M4 12h16M4 18h16"/></Icon>;
const X = (p) => <Icon {...p}><path d="M18 6L6 18M6 6l12 12"/></Icon>;

window.FCSIcons = { Icon, ArrowRight, ArrowUpRight, Plus, Check, Spark, Network, Server, Monitor, Activity, Layers, Compass, Globe, Menu, X };

/* ---------- Logo (mark only — orbital wing reproduction) ---------- */
function LogoMark({ size = 36 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="lm-g" x1="0" y1="0" x2="64" y2="64">
          <stop offset="0" stopColor="#A8F0D4"/>
          <stop offset="1" stopColor="#4FC9A1"/>
        </linearGradient>
      </defs>
      {/* Outer orbital ellipse, tilted */}
      <g transform="translate(32 32) rotate(-22)">
        <ellipse cx="0" cy="0" rx="28" ry="14" stroke="url(#lm-g)" strokeWidth="2.4" fill="none" opacity="0.95"/>
        <ellipse cx="0" cy="0" rx="22" ry="9" stroke="url(#lm-g)" strokeWidth="1.6" fill="none" opacity="0.55"/>
      </g>
      {/* Inner X (the mark's heart) */}
      <g transform="translate(32 32)">
        <path d="M-9 -9 L9 9 M9 -9 L-9 9" stroke="url(#lm-g)" strokeWidth="3" strokeLinecap="round"/>
      </g>
      {/* Orbiting node */}
      <circle cx="56" cy="20" r="2.4" fill="#A8F0D4"/>
    </svg>
  );
}

/* ---------- Logo (full lockup) ---------- */
function LogoLockup({ markSize = 28 }) {
  return (
    <a href="index.html" className="logo-lockup" aria-label="Future Consulting">
      <LogoMark size={markSize}/>
      <span className="logo-word">
        <strong>future</strong>consulting
      </span>
    </a>
  );
}

/* ---------- Language toggle ---------- */
function LanguageToggle() {
  const { lang, setLang } = useI18n();
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      <button onClick={() => setLang('hu')} className={lang === 'hu' ? 'on' : ''} aria-pressed={lang === 'hu'}>HU</button>
      <span className="lang-sep">·</span>
      <button onClick={() => setLang('en')} className={lang === 'en' ? 'on' : ''} aria-pressed={lang === 'en'}>EN</button>
    </div>
  );
}

/* ---------- Nav ---------- */
function Nav({ active = 'home' }) {
  const { t } = useI18n();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const items = [
    { id: 'services', label: t.nav.services, href: 'services.html' },
    { id: 'fusion', label: t.nav.fusion, href: 'fusion.html' },
    { id: 'cases', label: t.nav.cases, href: 'cases.html' },
    { id: 'contact', label: t.nav.contact, href: 'kapcsolat.html' },
  ];
  return (
    <header className={"nav " + (scrolled ? 'nav-scrolled' : '')}>
      <div className="topbar">
        <div className="container topbar-inner">
          <span className="topbar-item">
            <span className="topbar-dot">●</span> {t.topbar.address}
          </span>
          <a className="topbar-item topbar-link" href={"mailto:" + t.topbar.email}>
            {t.topbar.email}
          </a>
        </div>
      </div>
      <div className="container nav-inner">
        <LogoLockup markSize={28}/>
        <nav className="nav-links" aria-label="Primary">
          {items.map((it) => (
            <a key={it.id} href={it.href} className={active === it.id ? 'on' : ''}>
              {it.label}
            </a>
          ))}
        </nav>
        <div className="nav-right">
          <LanguageToggle/>
          <a href="kapcsolat.html" className="btn btn-primary btn-sm nav-cta">
            {t.nav.cta}
            <ArrowRight size={14}/>
          </a>
          <button className="nav-burger" onClick={() => setOpen((v) => !v)} aria-label="Menu">
            {open ? <X size={20}/> : <Menu size={20}/>}
          </button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile">
          {items.map((it) => (
            <a key={it.id} href={it.href} onClick={() => setOpen(false)}>{it.label}</a>
          ))}
          <a href="kapcsolat.html" className="btn btn-primary nav-mobile-cta" onClick={() => setOpen(false)}>
            {t.nav.cta}<ArrowRight size={14}/>
          </a>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const { t } = useI18n();
  const sections = t.footer.sections;
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div className="footer-top">
          <div className="footer-brand">
            <LogoLockup markSize={32}/>
            <p className="footer-tag">{t.footer.tag}</p>
            <div className="footer-meta">
              <span className="meta">{t.footer.address}</span>
              <span className="meta">info@futureconsulting.hu</span>
            </div>
          </div>
          <div className="footer-cols">
            {Object.entries(sections).map(([key, sec]) => (
              <div key={key} className="footer-col">
                <h5 className="footer-col-title">{sec.title}</h5>
                <ul>
                  {sec.links.map((l) => {
                    const label = typeof l === 'string' ? l : l.label;
                    const href = typeof l === 'string' ? '#' : (l.href || '#');
                    return <li key={label}><a href={href}>{label}</a></li>;
                  })}
                </ul>
              </div>
            ))}
          </div>
        </div>
        <div className="footer-bottom">
          <span className="meta">{t.footer.copy}</span>
          <span className="meta mono" style={{letterSpacing:'0.1em', textTransform:'uppercase'}}>FCS · v2026.05</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Cookie banner ---------- */
function CookieBanner() {
  const { t } = useI18n();
  const cb = t.cookies_banner;
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    try {
      const consent = localStorage.getItem('fcs-consent');
      if (!consent) setTimeout(() => setVisible(true), 600);
    } catch {}
  }, []);

  const setConsent = (level) => {
    try {
      localStorage.setItem('fcs-consent', JSON.stringify({
        level: level, // 'all' | 'necessary'
        ts: new Date().toISOString(),
      }));
    } catch {}
    setVisible(false);
  };

  if (!visible || !cb) return null;
  return (
    <div className="cookie-banner" role="dialog" aria-label={cb.title}>
      <div className="cookie-banner-inner">
        <div className="cookie-banner-text">
          <div className="cookie-banner-title">{cb.title}</div>
          <p className="cookie-banner-desc">
            {cb.desc} <a href={cb.moreLink.href} className="cookie-banner-link">{cb.moreLink.label}</a>
          </p>
        </div>
        <div className="cookie-banner-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => setConsent('necessary')}>
            {cb.acceptNecessary}
          </button>
          <button className="btn btn-primary btn-sm" onClick={() => setConsent('all')}>
            {cb.acceptAll}
          </button>
        </div>
      </div>
    </div>
  );
}

/* Export to window so other Babel scripts can use them */
Object.assign(window, {
  I18nProvider, useI18n, useReveal,
  LogoMark, LogoLockup, LanguageToggle, Nav, Footer, CookieBanner,
  ArrowRight, ArrowUpRight, Plus, Check, Spark, Network, Server, Monitor, Activity, Layers, Compass, Globe, Menu, X, Icon,
});
