// keni-core.jsx — KeNi Solutions brand core.
// Premium dark, soft warm accents. Calm, intelligent, human-centered.
// Tokens, logotype, UpStride product mark, nav, footer.
// Depends on scroll-anim.jsx (Reveal, etc.) loaded earlier.

// Midnight & Copper — KeNi Solutions brand system.
const KENI = {
  bg: '#0e1220',       // midnight
  bg2: '#0a0d18',      // deeper midnight (raised/alt)
  panel: '#161b2b',    // cards
  panel2: '#1f2638',   // inner cards
  cream: '#f4f1ec',    // primary light (paper)
  ink: '#f6f8fc',      // headings
  ink2: '#c2cad7',     // body
  muted: '#8d98b0',    // captions
  line: '#222a3e',     // hairlines
  line2: '#1a2032',
  saffron: '#c07c49',  // primary copper accent
  saffron2: '#d68a55', // bright copper highlight
  amber: '#cf8b52',    // warm copper alt
  jade: '#6cc4a0',     // calm green (progress / positive)
  rose: '#d98a6e',     // warm terracotta (people / care)
  sky: '#8aa9da',      // calm blue (clarity / data)
};

const kDisplay = `'Archivo', 'Inter Tight', -apple-system, system-ui, sans-serif`;
const kSans = `'Hanken Grotesk', -apple-system, system-ui, sans-serif`;
const kMono = `'IBM Plex Mono', 'JetBrains Mono', ui-monospace, monospace`;
const kSerif = `'Newsreader', 'Source Serif Pro', Georgia, serif`;

// ============ Small label / eyebrow ============
function KTag({ children, color = KENI.saffron, align = 'left' }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      flexDirection: align === 'right' ? 'row-reverse' : 'row',
      fontFamily: kMono, fontSize: 11, color, textTransform: 'uppercase',
      letterSpacing: 2.2, padding: '4px 0',
    }}>
      <span style={{ width: 22, height: 1, background: color, display: 'inline-block' }}></span>
      {children}
    </span>
  );
}

// ============ KeNi Solutions logotype (squircle mark + wordmark) ============
function KLogo({ light = true, compact = false }) {
  const c = light ? '#ffffff' : KENI.bg;
  const sub = light ? KENI.muted : 'rgba(0,0,0,0.5)';
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
      {/* Midnight & Copper squircle — primary brand mark (provided PNG) */}
      <img src="assets/logo.png" width="27" height="27" alt="KeNi Solutions"
        style={{ display: 'block', flexShrink: 0, borderRadius: 7 }} />
      <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 9 }}>
        <span style={{ fontFamily: kDisplay, fontSize: 21, color: c, letterSpacing: -0.6, fontWeight: 800 }}>KeNi</span>
        {!compact && (
          <span style={{ fontFamily: kMono, fontSize: 10, color: sub, letterSpacing: 3, textTransform: 'uppercase', position: 'relative', top: -1 }}>
            Solutions
          </span>
        )}
      </span>
    </span>
  );
}

// ============ UpStride product mark (uses uploaded logo) ============
function UpStrideMark({ height = 30, withWord = false }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
      <img src={(window.__resources && window.__resources.upstrideIcon) || "uploads/icon.png"} alt="UpStride" style={{ height, width: 'auto', display: 'block' }} />
      {withWord && (
        <span style={{ fontFamily: kSans, fontSize: 15, fontWeight: 600, color: KENI.ink, letterSpacing: 0.2 }}>UpStride</span>
      )}
    </span>
  );
}

// ============ Nav ============
function KNav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive] = React.useState(null);
  const navRef = React.useRef(null);
  const linkRefs = React.useRef({});
  const clickLock = React.useRef(0);
  const [pill, setPill] = React.useState({ left: 0, width: 0, opacity: 0 });
  const link = { color: KENI.ink2, textDecoration: 'none', fontSize: 13.5, fontFamily: kSans, letterSpacing: 0.1 };
  const items = [
    ['philosophy', 'Philosophy'],
    ['products', 'Products'],
    ['capabilities', 'Capabilities'],
    ['outcomes', 'Outcomes'],
    ['vision', 'Vision'],
  ];

  React.useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onS, { passive: true });
    return () => window.removeEventListener('scroll', onS);
  }, []);

  // Scroll-spy: the active section is the furthest-down one whose top has
  // crossed a line ~30% down the viewport. Clicking briefly locks the result
  // so the highlight commits to the clicked item during the smooth scroll.
  React.useEffect(() => {
    const ids = items.map((i) => i[0]);
    const compute = () => {
      if (Date.now() < clickLock.current) return;
      const line = window.innerHeight * 0.3;
      let current = null;
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= line) current = id;
      }
      setActive(current);
    };
    compute();
    window.addEventListener('scroll', compute, { passive: true });
    window.addEventListener('resize', compute);
    return () => {
      window.removeEventListener('scroll', compute);
      window.removeEventListener('resize', compute);
    };
  }, []);

  // Slide + fade the highlight pill onto the active link.
  const placePill = React.useCallback(() => {
    const el = active && linkRefs.current[active];
    if (!el) { setPill((p) => ({ ...p, opacity: 0 })); return; }
    setPill({ left: el.offsetLeft, width: el.offsetWidth, opacity: 1 });
  }, [active]);
  React.useLayoutEffect(() => { placePill(); }, [placePill]);
  React.useEffect(() => {
    window.addEventListener('resize', placePill);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(placePill);
    return () => window.removeEventListener('resize', placePill);
  }, [placePill]);
  return (
    <header className="keni-nav" style={{
      display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center',
      padding: '18px 48px',
      borderBottom: `1px solid ${scrolled ? KENI.line : 'transparent'}`,
      background: scrolled ? 'rgba(10,9,8,0.82)' : 'transparent',
      backdropFilter: scrolled ? 'blur(16px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(16px)' : 'none',
      position: 'sticky', top: 0, zIndex: 50, transition: 'background 0.3s, border 0.3s',
    }}>
      <a href="#top" style={{ textDecoration: 'none', justifySelf: 'start' }}><KLogo /></a>
      <nav ref={navRef} className="keni-nav-links" style={{ position: 'relative', display: 'flex', gap: 6, justifyContent: 'center' }}>
        <span aria-hidden style={{
          position: 'absolute', top: '50%', transform: 'translateY(-50%)',
          left: pill.left, width: pill.width, height: 32, borderRadius: 999,
          background: `${KENI.saffron}1c`, border: `1px solid ${KENI.saffron}3a`,
          opacity: pill.opacity, pointerEvents: 'none', zIndex: 0,
          transition: 'left 0.45s cubic-bezier(.4,.0,.2,1), width 0.45s cubic-bezier(.4,.0,.2,1), opacity 0.4s ease',
        }}></span>
        {items.map(([id, label]) => {
          const isActive = active === id;
          return (
            <a key={id} ref={el => { linkRefs.current[id] = el; }} href={`#${id}`}
              onClick={() => { clickLock.current = Date.now() + 800; setActive(id); }}
              style={{
                ...link, position: 'relative', zIndex: 1, padding: '7px 14px', borderRadius: 999,
                color: isActive ? KENI.cream : KENI.ink2, fontWeight: isActive ? 500 : 400,
                transition: 'color 0.35s ease',
              }}
              onMouseEnter={e => { if (!isActive) e.currentTarget.style.color = KENI.cream; }}
              onMouseLeave={e => { if (!isActive) e.currentTarget.style.color = KENI.ink2; }}
            >{label}</a>
          );
        })}
      </nav>
      <div className="keni-nav-cta" style={{ display: 'flex', gap: 10, alignItems: 'center', justifyContent: 'flex-end' }}>
        <a href="#vision" style={{ ...link, color: KENI.cream }}
          onMouseEnter={e => e.currentTarget.style.color = KENI.saffron}
          onMouseLeave={e => e.currentTarget.style.color = KENI.cream}
        >View vision</a>
        <a href="#contact" style={{
          fontFamily: kSans, fontSize: 13.5, color: KENI.bg, fontWeight: 600,
          background: KENI.cream, padding: '10px 18px', borderRadius: 999, textDecoration: 'none',
          display: 'inline-flex', alignItems: 'center', gap: 7, transition: 'transform 0.2s',
        }}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
        >Early access <span style={{ opacity: 0.5 }}>→</span></a>
      </div>
    </header>
  );
}

// ============ Section heading helper ============
function KSectionHead({ kicker, kickerColor = KENI.saffron, title, intro, align = 'left', maxWidth = 720 }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === 'center' ? maxWidth : 'none', margin: align === 'center' ? '0 auto' : 0 }}>
      <Reveal><KTag color={kickerColor} align={align === 'right' ? 'right' : 'left'}>{kicker}</KTag></Reveal>
      <Reveal delay={0.08}>
        <h2 style={{
          fontFamily: kDisplay, fontWeight: 600, color: KENI.ink, margin: '20px 0 0',
          fontSize: 'clamp(38px, 5vw, 68px)', lineHeight: 1.02, letterSpacing: -1.8,
        }}>{title}</h2>
      </Reveal>
      {intro && (
        <Reveal delay={0.16}>
          <p style={{
            fontFamily: kSans, fontSize: 18, lineHeight: 1.6, color: KENI.ink2,
            margin: align === 'center' ? '26px auto 0' : '26px 0 0', maxWidth: 620,
          }}>{intro}</p>
        </Reveal>
      )}
    </div>
  );
}

// ============ Footer ============
function KFooter() {
  const cols = [
    ['Products', ['UpStride', 'Ecosystem roadmap', 'Early access', 'Changelog']],
    ['Company', ['Philosophy', 'Vision', 'Founder note', 'Journal']],
    ['Build', ['Careers', 'For partners', 'Security', 'Status']],
    ['Legal', ['Privacy', 'Terms', 'DPDP notice', 'Responsible AI']],
  ];
  return (
    <footer style={{ padding: '72px 48px 36px', background: KENI.bg, borderTop: `1px solid ${KENI.line}` }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div className="keni-footer-grid" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr', gap: 36, marginBottom: 56 }}>
          <div>
            <KLogo />
            <p style={{ fontFamily: kDisplay, fontStyle: 'italic', fontFamily: window.kSerif, fontSize: 22, color: KENI.ink2, margin: '22px 0 0', lineHeight: 1.4, maxWidth: 340 }}>
              Intelligent systems that make complex work feel simpler, clearer, and more human.
            </p>
            <div style={{ marginTop: 28, fontFamily: kMono, fontSize: 10.5, color: KENI.muted, letterSpacing: 1.5, lineHeight: 1.9, textTransform: 'uppercase' }}>
              KeNi Solutions · Hyderabad, India<br />
              hello@kenisolutions.com
            </div>
          </div>
          {cols.map(([h, items]) => (
            <div key={h}>
              <div style={{ fontFamily: kMono, fontSize: 10, color: KENI.muted, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>{h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
                {items.map(i => (
                  <li key={i}>
                    <a href="#" style={{ fontFamily: kSans, fontSize: 13.5, color: KENI.ink2, textDecoration: 'none', transition: 'color 0.2s' }}
                      onMouseEnter={e => e.currentTarget.style.color = KENI.cream}
                      onMouseLeave={e => e.currentTarget.style.color = KENI.ink2}
                    >{i}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          paddingTop: 24, borderTop: `1px solid ${KENI.line}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12,
          fontFamily: kMono, fontSize: 10.5, color: KENI.muted, letterSpacing: 1.5, textTransform: 'uppercase',
        }}>
          <div>© 2026 KeNi Solutions · A product ecosystem company</div>
          <div>DPDP Act 2023 · Built with care in India</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  KENI, kDisplay, kSans, kMono, kSerif,
  KTag, KLogo, UpStrideMark, KNav, KSectionHead, KFooter,
});
