/* SFS website UI kit — shared chrome: top utility bar, header + mega-menu, footer.
   Consumes design-system primitives from window.SFSDesignSystem_95f437. */
const DS = window.SFSDesignSystem_95f437;
const { Button, ArrowLink, IconButton, SectionLabel } = DS;

/* ---------- inline line icons (2px stroke, currentColor) ---------- */
const Ico = {
  chevron: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" {...p}><path d="M6 9l6 6 6-6"/></svg>,
  search: (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>,
  up: (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.2" {...p}><path d="M12 19V5M5 12l7-7 7 7"/></svg>,
  arrow: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  linkedin: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" {...p}><path d="M6.94 5a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM3 8.5h3.9V21H3V8.5Zm6.5 0h3.7v1.7h.05c.52-.93 1.8-1.9 3.7-1.9 3.96 0 4.7 2.4 4.7 5.5V21h-3.9v-5.6c0-1.33-.02-3.05-1.9-3.05-1.9 0-2.2 1.45-2.2 2.95V21H9.5V8.5Z"/></svg>,
  youtube: (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" {...p}><path d="M23 12s0-3.2-.4-4.7a2.5 2.5 0 0 0-1.7-1.7C19.4 5.2 12 5.2 12 5.2s-7.4 0-8.9.4A2.5 2.5 0 0 0 1.4 7.3C1 8.8 1 12 1 12s0 3.2.4 4.7a2.5 2.5 0 0 0 1.7 1.7c1.5.4 8.9.4 8.9.4s7.4 0 8.9-.4a2.5 2.5 0 0 0 1.7-1.7C23 15.2 23 12 23 12ZM9.8 15.3V8.7l5.7 3.3-5.7 3.3Z"/></svg>,
  instagram: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1.1" fill="currentColor" stroke="none"/></svg>,
};

const UTILITY = [
  { label: 'SFS Global', href: 'https://www.sfs.com', external: true },
  { label: 'Sustainability', page: 'sustainability' },
  { label: 'Certifications', page: 'certifications' },
  { label: 'Career', page: 'careers' },
  { label: 'Customers', page: 'customers' },
  { label: 'Downloads', page: 'downloads' },
];

/* Top-level nav — matches the SFS sitemap. caret => has a mega-menu (key in MENUS). */
const NAV = [
  { key: 'company', label: 'Company', caret: true },
  { key: 'products', label: 'Products', caret: true },
  { key: 'applications', label: 'Applications', caret: true },
  { key: 'technologies', label: 'Technologies', caret: true },
  { key: 'capabilities', label: 'Capabilities', caret: true },
  { key: 'customers', label: 'Customers', caret: true },
  { key: 'careers', label: 'Careers', caret: false, go: 'careers' },
  { key: 'contact', label: 'Contact', caret: false, go: 'contact' },
];

/* Products mega — image tiles (dark). */
const PRODUCT_TILES = [
  { name: 'Engine Components', img: window.SFS_ASSET('../assets/ind-engine.jpg'), go: 'product:engine' },
  { name: 'Turbocharger Components', img: window.SFS_ASSET('../assets/ind-turbo.jpg'), go: 'product:turbocharger' },
  { name: 'Fuel System Components', img: window.SFS_ASSET('../assets/ind/fuel-banner.jpg'), go: 'product:fuel' },
  { name: 'Fluid Power Components', img: window.SFS_ASSET('../assets/infra/fp0.jpg'), go: 'product:fluid' },
  { name: 'Aerospace Components', img: window.SFS_ASSET('../assets/aerospace-banner.jpg'), go: 'aerospace' },
  { name: 'Safety Components', img: window.SFS_ASSET('../assets/ind/safety-banner.jpg'), go: 'product:safety' },
];

/* Column-style menus: array of columns, each { head, links:[{t,go}] }. */
const MENUS = {
  company: [
    { head: 'About', links: [
      { t: 'About Us', go: 'company' },
      { t: "Chairman's Desk", go: 'chairman' },
      { t: 'Leadership', go: 'leadership' },
      { t: 'Milestones', go: 'milestones' },
    ] },
    { head: 'Recognition', links: [
      { t: 'Certifications', go: 'certifications' },
      { t: 'Awards and Achievements', go: 'awards' },
    ] },
    { head: 'Responsibility', links: [
      { t: 'Corporate Social Responsibility', go: 'csr' },
      { t: 'Sustainability', go: 'sustainability' },
    ] },
  ],
  applications: [
    { head: 'Automotive Components', links: [
      { t: 'Engine', go: 'product:engine' },
      { t: 'Turbochargers', go: 'product:turbocharger' },
      { t: 'Fuel Systems', go: 'product:fuel' },
      { t: 'Safety', go: 'product:safety' },
    ] },
    { head: 'Industrial Components', links: [
      { t: 'Fluid Power', go: 'product:fluid' },
      { t: 'Off Highway Engines', go: 'industry:highway' },
      { t: 'Aerospace', go: 'aerospace' },
      { t: 'Emission', go: 'industry:emission' },
    ] },
    { head: 'Riveting', links: [
      { t: 'Automotive', go: 'applications' },
      { t: 'Electronics', go: 'applications' },
      { t: 'Engineering Industry', go: 'applications' },
      { t: 'Solar', go: 'applications' },
      { t: 'Elevators', go: 'applications' },
    ] },
  ],
  technologies: [
    { head: 'Technologies', links: [
      { t: 'Precision Machining', go: 'tech:precision' },
      { t: 'Cold Forming', go: 'tech:coldforming' },
      { t: 'Matched Assembly', go: 'tech:matched' },
    ] },
  ],
  capabilities: [
    { head: 'Capabilities', links: [
      { t: 'Integrated Manufacturing', go: 'capabilities#integrated' },
      { t: 'Metrology', go: 'capabilities#metrology' },
      { t: 'Special Processes', go: 'capabilities#special' },
    ] },
    { head: 'Facilities', links: [
      { t: 'Infrastructure', go: 'infrastructure' },
    ] },
  ],
  customers: [
    { head: 'Customers', links: [
      { t: 'Customers', go: 'customers' },
      { t: 'Terms & Conditions — Sales and Delivery', go: 'terms:sales' },
      { t: 'Terms & Conditions — Purchasing', go: 'terms:purchasing' },
    ] },
  ],
};

function TopBar({ onNavigate }) {
  return (
    <div className="sfs-topbar">
      <div className="sfs-shell sfs-topbar__row">
        <nav className="sfs-topbar__links">
          {UTILITY.map((u) => u.external
            ? <a key={u.label} href={u.href} target="_blank" rel="noopener noreferrer" className="sfs-topbar__link">{u.label}</a>
            : <a key={u.label} href="#" className="sfs-topbar__link" onClick={(e) => { e.preventDefault(); onNavigate(u.page); }}>{u.label}</a>)}
        </nav>
        <div className="sfs-topbar__lang"><span className="muted">DE</span> <span className="sep">|</span> <b>EN</b></div>
      </div>
    </div>
  );
}

function MegaMenu({ which, onNavigate }) {
  if (which === 'products') {
    return (
      <div className="sfs-mega sfs-mega--dark">
        <div className="sfs-shell">
          <div className="sfs-mega__tiles">
            {PRODUCT_TILES.map((it) => (
              <a key={it.name} href="#" className="sfs-tile" onClick={(e) => { e.preventDefault(); onNavigate(it.go); }}>
                <span className="sfs-tile__name">{it.name}</span>
                <span className="sfs-tile__frame"><img src={it.img} alt={it.name} /></span>
              </a>
            ))}
          </div>
        </div>
      </div>
    );
  }
  const cols = MENUS[which];
  if (!cols) return null;
  return (
    <div className="sfs-mega">
      <div className="sfs-shell sfs-mega__pad">
        <div className="sfs-mega__cols">
          {cols.map((c) => (
            <div key={c.head} className="sfs-mega__col">
              <SectionLabel as="div">{c.head}</SectionLabel>
              <div className="sfs-mega__list">
                {c.links.map((l) => (
                  <a key={l.t} href="#" className="sfs-mega__link" onClick={(e) => { e.preventDefault(); onNavigate(l.go); }}>
                    {l.t} {Ico.arrow({ width: 15, height: 15, style: { verticalAlign: 'middle' } })}
                  </a>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Header({ page, onNavigate }) {
  const [open, setOpen] = React.useState(null);
  const toggle = (n) => { if (!n.caret) { onNavigate(n.go); setOpen(null); return; } setOpen(open === n.key ? null : n.key); };
  return (
    <header className="sfs-header" onMouseLeave={() => setOpen(null)}>
      <div className="sfs-shell sfs-header__row">
        <a href="#" className="sfs-logo" onClick={(e) => { e.preventDefault(); onNavigate('home'); setOpen(null); }}>
          <img src={window.SFS_ASSET("../assets/sfs-logo.svg")} alt="SFS" />
        </a>
        <nav className="sfs-nav">
          {NAV.map((n) => (
            <button key={n.key}
              className={'sfs-nav__item' + (open === n.key ? ' is-open' : '')}
              onClick={() => toggle(n)}>
              {n.label}{n.caret && <Ico.chevron className={'sfs-nav__caret' + (open === n.key ? ' flip' : '')} />}
            </button>
          ))}
        </nav>
        <button className="sfs-search" onClick={() => onNavigate('home')}>{Ico.search()}<span>Search</span></button>
      </div>
      {open && <MegaMenu which={open} onNavigate={(p) => { onNavigate(p); setOpen(null); }} />}
    </header>
  );
}

function Footer({ onNavigate }) {
  return (
    <footer className="sfs-footer">
      <div className="sfs-shell sfs-footer__main">
        <div className="sfs-footer__inq">
          <p className="sfs-footer__co">SFS Group India Private Limited</p>
          <p className="sfs-footer__co-sub">(formerly known as Indo Schöttle Auto Parts Private Limited)</p>
          <p className="sfs-footer__cta">Still looking for something? Get in touch.</p>
          <p className="sfs-footer__contact">
            Call: <a href="tel:+912032540050">(91) 20-32540050 / 51 / 52</a>
            <span className="sfs-footer__sep">·</span>
            Email: <a href="mailto:info@sfsgroupind.com">info@sfsgroupind.com</a>
          </p>
          <a href="#" className="sfs-arrow-link on-dark" onClick={(e) => { e.preventDefault(); onNavigate('contact'); }}>Contact</a>
        </div>
        <div className="sfs-footer__right">
          <div className="sfs-footer__social">
            <a href="#" aria-label="LinkedIn">{Ico.linkedin()}</a>
            <a href="#" aria-label="YouTube">{Ico.youtube()}</a>
            <a href="#" aria-label="Instagram">{Ico.instagram()}</a>
          </div>
          <h4>Mailing List</h4>
          <p className="sfs-footer__sub">Stay informed</p>
          <Button onDark>Subscribe mailing list</Button>
        </div>
      </div>
      <div className="sfs-footer__bar">
        <div className="sfs-shell sfs-footer__barrow">
          <nav className="sfs-footer__legal">
            <a href="#">Imprint</a><a href="#">Disclaimer</a><a href="#">Data Privacy</a><a href="#">Sitemap</a><a href="#">Cookie Declaration</a>
          </nav>
          <div className="sfs-footer__barright">
            <span className="sfs-footer__member">A member of <img src={window.SFS_ASSET("../assets/sfs-logo-white.svg")} alt="SFS" /></span>
            <span className="sfs-footer__copy">© 2026 SFS Group – all rights reserved.</span>
          </div>
        </div>
      </div>
      <button className="sfs-totop" aria-label="Back to top" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>{Ico.up()}</button>
    </footer>
  );
}

Object.assign(window, { SFSChrome: { TopBar, Header, Footer, Ico } });

/* Glowing scroll progress for the milestone timeline.
   Positions a single red fill over the centre rail and fills it from the
   first dot to the last as the user scrolls. Returns a cleanup fn. */
window.SFSTimelineProgress = function (root) {
  if (!root) return function () {};
  const rails = [...root.querySelectorAll('.sfs-tl__rail')];
  const dots = [...root.querySelectorAll('.sfs-tl__dot')];
  if (rails.length < 2) return function () {};
  let fill = root.querySelector('.sfs-timeline__fill');
  if (!fill) { fill = document.createElement('div'); fill.className = 'sfs-timeline__fill'; root.appendChild(fill); }
  let firstY = 0, lastY = 0, total = 0;
  function layout() {
    const rb = root.getBoundingClientRect();
    const railRect = rails[0].getBoundingClientRect();
    const x = railRect.left - rb.left + railRect.width / 2;
    const d0 = dots[0].getBoundingClientRect();
    const dN = dots[dots.length - 1].getBoundingClientRect();
    firstY = d0.top - rb.top + d0.height / 2;
    lastY = dN.top - rb.top + dN.height / 2;
    total = Math.max(1, lastY - firstY);
    fill.style.left = x + 'px';
    fill.style.top = firstY + 'px';
  }
  function update() {
    const rb = root.getBoundingClientRect();
    const trigger = window.innerHeight * 0.55;        // line ~55% down the viewport
    // fill snaps from dot to dot: it ends at the furthest dot the trigger has passed
    let reachedY = firstY;
    dots.forEach((dot) => {
      const dr = dot.getBoundingClientRect();
      const dy = dr.top - rb.top + dr.height / 2;
      const isReached = (rb.top + dy) <= trigger;
      dot.classList.toggle('is-reached', isReached);
      if (isReached && dy > reachedY) reachedY = dy;
    });
    fill.style.height = Math.max(0, reachedY - firstY) + 'px';
  }
  function onScroll() { update(); }
  function onResize() { layout(); update(); }
  layout(); update();
  window.addEventListener('scroll', onScroll, { passive: true });
  window.addEventListener('resize', onResize);
  const imgs = root.querySelectorAll('img');
  imgs.forEach((im) => im.addEventListener('load', onResize));
  return function () {
    window.removeEventListener('scroll', onScroll);
    window.removeEventListener('resize', onResize);
  };
};
