/* ============================================================
   SAYRU — shared.jsx
   i18n provider, brand chrome (topbar, header, footer),
   icons, and reusable primitives. Exported to window.
   ============================================================ */
const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

/* ---------------- i18n ---------------- */
const LangCtx = createContext(null);
const VALID_LANGS = ['tr', 'en', 'az'];
function initialLang() {
  try {
    const u = new URLSearchParams(location.search).get('lang');
    if (u && VALID_LANGS.includes(u.toLowerCase())) return u.toLowerCase();
  } catch (e) {}
  const stored = localStorage.getItem('sayru_lang');
  return VALID_LANGS.includes(stored) ? stored : 'tr';
}
function LangProvider({ children }) {
  const [lang, setLangState] = useState(initialLang);
  const [liveTick, setLiveTick] = useState(0);
  useEffect(() => {
    const h = () => setLiveTick(t => t + 1); // real-time refresh from CMS bridge
    const timers = [
      setTimeout(h, 0),
      setTimeout(h, 250),
      setTimeout(h, 1500),
    ];
    window.addEventListener('sayru-live-update', h);
    if (window.__SAYRU_CMS_READY && typeof window.__SAYRU_CMS_READY.then === 'function') {
      window.__SAYRU_CMS_READY.then(h).catch(() => {});
    } else if (window.__SAYRU_CMS_STATUS && window.__SAYRU_CMS_STATUS.ready) {
      setTimeout(h, 0);
    }
    return () => {
      timers.forEach(clearTimeout);
      window.removeEventListener('sayru-live-update', h);
    };
  }, []);
  const setLang = (l) => {
    localStorage.setItem('sayru_lang', l);
    setLangState(l);
    try {
      const url = new URL(location.href);
      url.searchParams.set('lang', l);
      history.replaceState(null, '', url);
    } catch (e) {}
    if (typeof window.__SAYRU_LOAD_PUBLIC_LANG === 'function') {
      window.__SAYRU_LOAD_PUBLIC_LANG(l);
    }
  };
  useEffect(() => {
    document.documentElement.lang = lang;
    localStorage.setItem('sayru_lang', lang);
    // keep URL in sync on first load (shareable links)
    try {
      const url = new URL(location.href);
      if (url.searchParams.get('lang') !== lang) { url.searchParams.set('lang', lang); history.replaceState(null, '', url); }
    } catch (e) {}
  }, [lang]);
  const t = useCallback((key) => {
    const D = window.I18N;
    return (D[lang] && D[lang][key]) || D.tr[key] || key;
  }, [lang, liveTick]);
  return <LangCtx.Provider value={{ lang, setLang, t, liveTick }}>{children}</LangCtx.Provider>;
}
const useT = () => useContext(LangCtx);

/* ---------------- live contact info (CMS-driven, with defaults) ---------------- */
const contactInfo = () => Object.assign(
  { phone: '+90 541 719 04 01', email: 'info@sayru.com.tr', whatsapp: '905417190401' },
  window.__SAYRU_CONTACT || {}
);
const telHref = (p) => 'tel:' + String(p).replace(/[^0-9+]/g, '');
const waHref = () => 'https://wa.me/' + String(contactInfo().whatsapp).replace(/[^0-9]/g, '');

/* ---------------- util: newline → <br> ---------------- */
function nl2br(s) {
  return String(s).split('\n').map((line, i, a) => (
    <React.Fragment key={i}>{line}{i < a.length - 1 && <br />}</React.Fragment>
  ));
}

/* ---------------- section scroll navigation ---------------- */
function isIndexPage(pathname) {
  const file = String(pathname || '').split('/').pop();
  return file === '' || file === 'index.html';
}

function scrollToHashTarget(hash, behavior = 'smooth') {
  if (!hash || hash === '#') return false;
  const id = decodeURIComponent(String(hash).replace(/^#/, ''));
  const target = document.getElementById(id);
  if (!target) return false;

  const header = document.querySelector('.hdr');
  const headerOffset = (header ? header.getBoundingClientRect().height : 0) + 14;
  const top = target.getBoundingClientRect().top + window.pageYOffset - headerOffset;

  window.scrollTo({
    top: Math.max(0, top),
    behavior,
  });
  return true;
}

function retryScrollToHash(hash, behavior = 'smooth') {
  [0, 80, 220, 500, 900].forEach((delay) => {
    setTimeout(() => scrollToHashTarget(hash, behavior), delay);
  });
}

function useSectionScrollNavigation() {
  useEffect(() => {
    const onClick = (event) => {
      const link = event.target && event.target.closest ? event.target.closest('a[href]') : null;
      if (!link) return;

      const href = link.getAttribute('href') || '';
      if (!href.includes('#')) return;

      let url;
      try { url = new URL(href, window.location.href); } catch (e) { return; }
      if (url.origin !== window.location.origin || !url.hash) return;

      const currentIsIndex = isIndexPage(window.location.pathname);
      const targetIsIndex = isIndexPage(url.pathname);
      if (!currentIsIndex || !targetIsIndex) return;

      event.preventDefault();
      const nextUrl = window.location.pathname + window.location.search + url.hash;
      history.pushState(null, '', nextUrl);
      retryScrollToHash(url.hash, 'smooth');
    };

    const onHashChange = () => {
      if (isIndexPage(window.location.pathname)) retryScrollToHash(window.location.hash, 'smooth');
    };

    document.addEventListener('click', onClick);
    window.addEventListener('hashchange', onHashChange);

    if (isIndexPage(window.location.pathname) && window.location.hash) {
      retryScrollToHash(window.location.hash, 'auto');
    }

    return () => {
      document.removeEventListener('click', onClick);
      window.removeEventListener('hashchange', onHashChange);
    };
  }, []);
}

/* ---------------- reveal on scroll (bulletproof: synchronous scroll-driven) ---------------- */
function useReveal() {
  useEffect(() => {
    let last = 0;
    const reveal = () => {
      const vh = window.innerHeight || 800;
      document.querySelectorAll('.reveal:not(.in)').forEach((e) => {
        if (e.getBoundingClientRect().top < vh * 0.92) e.classList.add('in');
      });
    };
    const onScroll = () => {
      const now = Date.now();
      if (now - last < 60) return;
      last = now;
      reveal();
    };
    reveal();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    const t1 = setTimeout(reveal, 250);
    const safety = setTimeout(() => document.querySelectorAll('.reveal').forEach(e => e.classList.add('in')), 3500);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      clearTimeout(t1); clearTimeout(safety);
    };
  }, []);
}

/* ---------------- deferred mount (paint text first, then visuals) ---------------- */
function useDeferredMount() {
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const cb = () => setReady(true);
    if (typeof window.requestIdleCallback === 'function') {
      const id = window.requestIdleCallback(cb, { timeout: 700 });
      return () => { if (window.cancelIdleCallback) window.cancelIdleCallback(id); };
    }
    const id = setTimeout(cb, 120);
    return () => clearTimeout(id);
  }, []);
  return ready;
}

/* ---------------- icons ---------------- */
function Icon({ name, size = 24, stroke = 1.6 }) {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
    strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    // Sayru-Yön — direction / flow / service desk
    yon: <g><circle cx="12" cy="12" r="9"/><path d="M12 7.5l3.2 8.8-3.2-2.2-3.2 2.2z"/></g>,
    // Sayru-Göz — monitoring eye + pulse
    goz: <g><path d="M2.5 12S5.5 6 12 6s9.5 6 9.5 6-3 6-9.5 6-9.5-6-9.5-6z"/><path d="M9 12.4l1.6 1.8 2-3 1.4 1.7H17"/></g>,
    // Sayru-İz — log trace / stacked records
    iz: <g><path d="M4 6h11M4 10h16M4 14h9M4 18h13"/><circle cx="19" cy="14" r="1.4"/></g>,
    // Sayru-Dem — audit shield + check
    dem: <g><path d="M12 3l7 2.5v5c0 5-3.3 8-7 9.5-3.7-1.5-7-4.5-7-9.5v-5z"/><path d="M9 12l2.2 2.2L15.4 10"/></g>,
    arrow: <path d="M5 12h14M13 6l6 6-6 6"/>,
    chevron: <path d="M6 9l6 6 6-6"/>,
    phone: <path d="M5 4h3l1.5 4.5L7.8 10a12 12 0 005 5l1.5-1.7L19 15v3a2 2 0 01-2.2 2A15 15 0 014 7.2 2 2 0 015 4z"/>,
    mail: <g><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M4 7l8 6 8-6"/></g>,
    pin: <g><path d="M12 21s7-5.7 7-11a7 7 0 10-14 0c0 5.3 7 11 7 11z"/><circle cx="12" cy="10" r="2.6"/></g>,
    support: <g><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="2.4"/><path d="M12 3.5v3M12 17.5v3M3.5 12h3M17.5 12h3"/></g>,
    login: <g><path d="M14 4h4a2 2 0 012 2v12a2 2 0 01-2 2h-4"/><path d="M10 8l4 4-4 4M14 12H3"/></g>,
    check: <path d="M5 12.5l4.5 4.5L19 6.5"/>,
    plus: <path d="M12 5v14M5 12h14"/>,
    wa: <path d="M12 3a9 9 0 00-7.7 13.6L3 21l4.6-1.2A9 9 0 1012 3z"/>,
    spark: <path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M18 6l-2.5 2.5M8.5 15.5L6 18"/>,
    grid: <g><rect x="4" y="4" width="7" height="7" rx="1"/><rect x="13" y="4" width="7" height="7" rx="1"/><rect x="4" y="13" width="7" height="7" rx="1"/><rect x="13" y="13" width="7" height="7" rx="1"/></g>,
  };
  return <svg {...p} aria-hidden="true">{paths[name] || null}</svg>;
}

const SERVICES = [
  { id: 'yon', icon: 'yon', href: 'Sayru-Yon.html' },
  { id: 'goz', icon: 'goz', href: 'Sayru-Goz.html' },
  { id: 'iz',  icon: 'iz',  href: 'Sayru-Iz.html' },
  { id: 'dem', icon: 'dem', href: 'Sayru-Dem.html' },
];

/* ---------------- Logo ---------------- */
function Logo({ variant = 'color', height = 38 }) {
  const custom = (typeof window !== 'undefined' && window.__SAYRU_LOGO) || {};
  const src = variant === 'white'
    ? (custom.white || 'assets/sayru-logo-white.png')
    : (custom.color || 'assets/sayru-logo.png');
  const scale = (variant === 'white' ? custom.scaleWhite : custom.scale) || 1;
  const href = custom.link || 'index.html';
  return <a href={href} className="logo" aria-label="SAYRU"><img src={src} alt="SAYRU" style={{ height: Math.round(height * scale) }} /></a>;
}

/* ---------------- Topbar ---------------- */
const LANGS = [['tr', 'TR'], ['en', 'EN'], ['az', 'AZ']];
function Topbar() {
  const { t, lang, setLang } = useT();
  return (
    <div className="topbar">
      <div className="wrap topbar__in">
        <div className="topbar__contact">
          <a href={'mailto:' + contactInfo().email} className="topbar__item"><Icon name="mail" size={14} /> {contactInfo().email}</a>
        </div>
        <div className="topbar__right">
          <div className="langsw" role="group" aria-label={t('top.lang')}>
            {LANGS.map(([code, label]) => (
              <button key={code} className={'langsw__b' + (lang === code ? ' on' : '')}
                onClick={() => setLang(code)}>{label}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Header / Nav ---------------- */
function Header({ active }) {
  const { t } = useT();
  const [scrolled, setScrolled] = useState(false);
  const [mega, setMega] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const megaTimer = useRef(null);
  useSectionScrollNavigation();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = drawer ? 'hidden' : '';
  }, [drawer]);

  const openMega = () => { clearTimeout(megaTimer.current); setMega(true); };
  const closeMega = () => { megaTimer.current = setTimeout(() => setMega(false), 140); };
  const homeAnchor = (hash) => active === 'home' ? hash : 'index.html' + hash;

  const navItems = [
    ['nav.home', 'index.html', 'home'],
    ['nav.about', 'Hakkimizda.html', 'about'],
    ['nav.services', '#', 'services'],
    ['nav.references', homeAnchor('#referanslar'), 'references'],
    ['nav.contact', homeAnchor('#iletisim'), 'contact'],
  ];

  return (
    <>
      <header className={'hdr' + (scrolled ? ' hdr--scrolled' : '')}>
        <div className="wrap hdr__in">
          <Logo height={scrolled ? 34 : 40} />
          <nav className="nav" aria-label="Ana menü">
            {navItems.map(([key, href, id]) => (
              id === 'services' ? (
                <div key={id} className="nav__drop" onMouseEnter={openMega} onMouseLeave={closeMega}>
                  <button className={'nav__link' + (active === 'services' ? ' on' : '') + (mega ? ' open' : '')}
                    aria-expanded={mega} onClick={() => setMega(v => !v)}>
                    {t(key)} <Icon name="chevron" size={15} />
                  </button>
                </div>
              ) : (
                <a key={id} href={href} className={'nav__link' + (active === id ? ' on' : '')}>{t(key)}</a>
              )
            ))}
          </nav>
          <div className="hdr__actions">
            <a href={homeAnchor('#iletisim')} className="btn btn--primary hdr__cta">{t('nav.cta')} <span className="ar"><Icon name="arrow" size={16} /></span></a>
            <button className="burger" aria-label="Menü" onClick={() => setDrawer(true)}>
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>

        {/* Mega menu */}
        <div className={'mega' + (mega ? ' mega--on' : '')} onMouseEnter={openMega} onMouseLeave={closeMega}>
          <div className="wrap mega__in">
            <div className="mega__head">
              <div>
                <div className="kicker">{t('nav.servicesAll')}</div>
                <p className="mega__note">{t('nav.servicesNote')}</p>
              </div>
              <a href={homeAnchor('#hizmetler')} className="mega__all">{t('nav.servicesAll')} <Icon name="arrow" size={15} /></a>
            </div>
            <div className="mega__grid">
              {SERVICES.map(s => (
                <a key={s.id} href={s.href} className="megacard">
                  <span className="megacard__ic"><Icon name={s.icon} size={22} /></span>
                  <span className="megacard__body">
                    <span className="megacard__name">{t('svc.' + s.id + '.name')}</span>
                    <span className="megacard__area">{t('svc.' + s.id + '.area')} · {t('svc.' + s.id + '.tool')}</span>
                    <span className="megacard__tag">{t('svc.' + s.id + '.tag')}</span>
                  </span>
                </a>
              ))}
            </div>
          </div>
        </div>
      </header>

      {/* Mobile drawer */}
      <div className={'drawer' + (drawer ? ' drawer--on' : '')}>
        <div className="drawer__scrim" onClick={() => setDrawer(false)}></div>
        <aside className="drawer__panel">
          <div className="drawer__top">
            <Logo height={34} />
            <button className="drawer__x" aria-label="Kapat" onClick={() => setDrawer(false)}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          </div>
          <nav className="drawer__nav">
            <a href="index.html" onClick={() => setDrawer(false)}>{t('nav.home')}</a>
            <a href="Hakkimizda.html" onClick={() => setDrawer(false)}>{t('nav.about')}</a>
            <div className="drawer__group">
              <div className="drawer__glabel">{t('nav.services')}</div>
              {SERVICES.map(s => (
                <a key={s.id} href={s.href} className="drawer__sub" onClick={() => setDrawer(false)}>
                  <Icon name={s.icon} size={18} /> {t('svc.' + s.id + '.name')} <span>{t('svc.' + s.id + '.area')}</span>
                </a>
              ))}
            </div>
            <a href={homeAnchor('#referanslar')} onClick={() => setDrawer(false)}>{t('nav.references')}</a>
            <a href={homeAnchor('#iletisim')} onClick={() => setDrawer(false)}>{t('nav.contact')}</a>
          </nav>
          <a href={homeAnchor('#iletisim')} className="btn btn--primary drawer__cta" onClick={() => setDrawer(false)}>{t('nav.cta')} <span className="ar"><Icon name="arrow" size={16} /></span></a>
        </aside>
      </div>
    </>
  );
}

/* ---------------- Footer ---------------- */
function ScrollTop() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 400);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const toTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });
  return (
    <button
      type="button"
      className={'scrolltop' + (show ? ' is-visible' : '')}
      onClick={toTop}
      aria-label="Yukarı çık"
      aria-hidden={!show}
      tabIndex={show ? 0 : -1}
    >
      <span className="scrolltop__ic" style={{ transform: 'rotate(180deg)' }}><Icon name="chevron" size={20} /></span>
    </button>
  );
}

function Footer() {
  const { t } = useT();
  const [subscribed, setSubscribed] = useState(false);
  return (
    <footer className="footer">
      <ScrollTop />
      <div className="footer__glow"></div>
      <div className="wrap footer__in">
        <div className="footer__brand">
          <Logo variant="white" height={42} />
          <p className="footer__tag">{t('foot.tagline')}</p>
          <div className="footer__slogan mono">{nl2br(t('foot.slogan'))}</div>
        </div>

        <div className="footer__col">
          <h4>{t('foot.corp')}</h4>
          <a href="Hakkimizda.html">{t('foot.corp.about')}</a>
          <a href="gizlilik-politikasi.html">{t('foot.corp.privacy')}</a>
          <a href="bilgi-guvenligi-politikasi.html">{t('foot.corp.infosec')}</a>
          <a href="kvkk.html">{t('foot.corp.kvkk')}</a>
        </div>

        <div className="footer__col">
          <h4>{t('foot.cons')}</h4>
          <a href="Sayru-Yon.html">{t('foot.cons.glpi')}</a>
          <a href="index.html#hizmetler">{t('foot.cons.zabbix')}</a>
          <a href="index.html#hizmetler">{t('foot.cons.siem')}</a>
          <a href="index.html#hizmetler">{t('foot.cons.audit')}</a>
        </div>

        <div className="footer__col">
          <h4>{t('foot.contact')}</h4>
          <a href="https://maps.google.com" className="footer__ic"><Icon name="pin" size={16} /> <span>{'Bayrakl\u0131 / \u0130zmir'}</span></a>
          <a href={'mailto:' + contactInfo().email} className="footer__ic"><Icon name="mail" size={16} /> <span>{contactInfo().email}</span></a>
        </div>

        <div className="footer__col footer__news">
          <h4>{t('foot.news')}</h4>
          <p>{t('foot.news.d')}</p>
          {subscribed ? (
            <div className="footer__subok"><Icon name="check" size={16} /> {t('contact.f.sent')}</div>
          ) : (
            <form className="footer__form" onSubmit={(e) => { e.preventDefault(); setSubscribed(true); }}>
              <input type="email" required placeholder={t('foot.news.ph')} aria-label={t('foot.news.ph')} />
              <button type="submit" className="btn btn--cyan">{t('foot.news.btn')}</button>
            </form>
          )}
        </div>
      </div>

      <div className="wrap footer__bottom">
        <span>© {new Date().getFullYear()} Sayru Teknoloji Danışmanlık Tic. Ltd. Şti. — {t('foot.rights')}</span>
        <a className="footer__dev" href="https://www.pinartopuz.dev" target="_blank" rel="noopener noreferrer">
          <span>Developed by</span>
          <b>Pınar Topuz</b>
          <Icon name="arrow" size={14} />
        </a>
        <span className="mono footer__tax">Bornova V.D. · 7571089599</span>
      </div>
    </footer>
  );
}

/* ---------------- Image placeholder (labeled) ---------------- */
function ImgPlaceholder({ label, ratio = '16 / 10', className = '', style = {} }) {
  return <div className={'imgph ' + className} style={{ aspectRatio: ratio, ...style }}>{label}</div>;
}

/* ---------------- CMS-assignable image ---------------- */
function CmsImage({ slot, className = '', placeholder = '', shape = 'rounded', radius = '14' }) {
  const imgs = (typeof window !== 'undefined' && window.__SAYRU_IMAGES) || {};
  const a = imgs[slot];
  const ready = useDeferredMount();
  // Yazılar önce boyansın; görsel ekran/idle hazır olduğunda yüklensin.
  if (a && ready) {
    return (
      <div className={'cms-img cms-img--in ' + className}>
        <img src={a.url} alt={a.name || placeholder} loading="lazy" decoding="async" />
      </div>
    );
  }
  const rounded = shape === 'circle' ? '999px' : (String(radius).match(/[a-z%]/i) ? String(radius) : String(radius || 14) + 'px');
  return <ImgPlaceholder label={placeholder || String(slot)} className={className} style={{ borderRadius: rounded }} />;
}

/* expose to other scripts */
Object.assign(window, {
  LangProvider, useT, useReveal, useDeferredMount, Icon, Logo, Topbar, Header, Footer, ScrollTop, ImgPlaceholder, CmsImage, SERVICES, LANGS, nl2br,
  contactInfo, telHref, waHref, scrollToHashTarget, retryScrollToHash,
});
