// Shared UI components for 74 LABS
// Use React.* directly to avoid scope collisions across babel scripts

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

// === Count-up — fixed width via ghost text ===
function CountUp({ to, suffix = '', duration = 1800 }) {
  const [val, setVal] = React.useState(to);
  const ref = React.useRef(null);
  const started = React.useRef(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (started.current) return;
    setVal(0);
    const run = () => {
      if (started.current) return;
      started.current = true;
      const start = performance.now();
      const tick = (now) => {
        const t = Math.min(1, (now - start) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        setVal(Math.round(to * eased));
        if (t < 1) requestAnimationFrame(tick);
        else setVal(to);
      };
      requestAnimationFrame(tick);
    };
    // If element is already in view at mount, fire immediately
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) { run(); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) run(); });
    }, { threshold: 0.1 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  const finalStr = Number(to).toLocaleString('en-US') + suffix;
  const liveStr = Number(val).toLocaleString('en-US') + suffix;
  const splitColor = (s) => {
    // suffix chars (anything non-digit, non-comma) get accent color
    return s.split('').map((c, i) => {
      const isSuffix = /[^\d,]/.test(c);
      return <span key={i} style={isSuffix ? { color: 'var(--accent)' } : null}>{c}</span>;
    });
  };
  return (
    <span ref={ref} className="big mono countup">
      <span className="countup-ghost" aria-hidden="true">{finalStr}</span>
      <span className="countup-live">{splitColor(liveStr)}</span>
    </span>
  );
}

// === Nav ===
function Nav({ current = 'home' }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <a className="logo logo-wordmark" href="index.html" aria-label="74LABS — In Crypto We Build">
          <img src="logo.svg" alt="74LABS" className="logo-img" />
          <span className="wm-tag">In Crypto We Build</span>
        </a>
        <div className="nav-links">
          <a href={current === 'home' ? '#products' : 'index.html#products'}>Products</a>
          <a href={current === 'home' ? '#services' : 'index.html#services'}>Services</a>
          <a href={current === 'home' ? '#process' : 'index.html#process'}>Process</a>
          <a href={current === 'home' ? '#contact' : 'index.html#contact'}>Contact</a>
        </div>
        <a className="nav-cta" href={current === 'home' ? '#contact' : 'index.html#contact'}>Let's talk →</a>
      </div>
    </nav>
  );
}

// === Live city time ===
function LiveTime({ tz }) {
  const fmt = () => new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: tz, hour12: false });
  const [t, setT] = React.useState(fmt);
  React.useEffect(() => {
    const id = setInterval(() => setT(fmt()), 1000);
    return () => clearInterval(id);
  }, []);
  return <span className="footer-clock-time">{t}</span>;
}

// === Footer ===
function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div>
            <a className="logo logo-wordmark logo-wordmark-lg" href="index.html" aria-label="74LABS"><img src="logo.svg" alt="74LABS" className="logo-img logo-img-lg" /><span className="wm-tag">In Crypto We Build</span></a>
            <p className="mono" style={{ marginTop: 16, fontSize: 12, color: 'var(--muted)', lineHeight: 1.55, maxWidth: 240 }}>
              Crypto-fintech infrastructure.
            </p>
            <div className="footer-clocks">
              <div className="footer-clock-row"><span className="footer-clock-city">SGT</span><LiveTime tz="Asia/Singapore" /></div>
              <div className="footer-clock-row"><span className="footer-clock-city">BKK</span><LiveTime tz="Asia/Bangkok" /></div>
              <div className="footer-clock-row"><span className="footer-clock-city">MNL</span><LiveTime tz="Asia/Manila" /></div>
            </div>
          </div>
          <div className="footer-cols">
            <div className="footer-col">
              <h4>Products</h4>
              <a href="wallet.html">Wallet Infrastructure</a>
              <a href="exchange.html">Exchange & Trading</a>
              <a href="fintech.html">Fintech & Payment Rails</a>
            </div>
            <div className="footer-col">
              <h4>Services</h4>
              <a href="index.html#service-01">Smart Contracts</a>
              <a href="index.html#service-02">dApp & Web3</a>
              <a href="index.html#service-03">Full-cycle Apps</a>
              <a href="index.html#service-04">Infrastructure</a>
              <a href="index.html#service-05">Consulting</a>
              <a href="index.html#service-06">Integrations</a>
            </div>
          </div>
          <div className="footer-col">
            <h4>Channels</h4>
            <a href="https://x.com/74labs" target="_blank" rel="noopener">X / Twitter ↗</a>
            <a href="https://t.me/labs74" target="_blank" rel="noopener">Telegram ↗</a>
            <a href="https://signal.me/#p/74labs" target="_blank" rel="noopener">Signal ↗</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>74 LABS Pte. Ltd. · © 2026 · Singapore · Bangkok · Manila</span>
          <span>v 4.2.0 · BUILD 2026.04.21</span>
          <span>
            <a href="privacy.html" style={{ color: 'inherit', marginRight: 16 }}>Privacy</a>
            <a href="terms.html" style={{ color: 'inherit' }}>Terms</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

// === Tweaks panel ===
const ACCENTS = {
  electric: { name: 'Electric', val: '#7C5CFF', glow: 'rgba(124, 92, 255, 0.35)', soft: 'rgba(124, 92, 255, 0.08)' },
  lime:     { name: 'Lime',     val: '#C6F24E', glow: 'rgba(198, 242, 78, 0.35)', soft: 'rgba(198, 242, 78, 0.08)' },
  mint:     { name: 'Mint',     val: '#00F0A4', glow: 'rgba(0, 240, 164, 0.35)',  soft: 'rgba(0, 240, 164, 0.08)' },
  mono:     { name: 'Mono',     val: '#E8E8EA', glow: 'rgba(232, 232, 234, 0.25)', soft: 'rgba(232, 232, 234, 0.06)' },
  amber:    { name: 'Amber',    val: '#FFB547', glow: 'rgba(255, 181, 71, 0.35)', soft: 'rgba(255, 181, 71, 0.08)' },
};

function Tweaks({ tweaks, setTweaks }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const handle = (e) => {
      if (e.data?.type === '__activate_edit_mode') setOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', handle);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handle);
  }, []);

  const update = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };

  if (!open) return null;
  return (
    <div className="tweaks open">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h5>Tweaks</h5>
        <button onClick={() => setOpen(false)} style={{ color: 'var(--muted)', fontSize: 16 }}>×</button>
      </div>
      <div className="tweak-row">
        <span className="lbl">Accent</span>
        <div className="tweak-swatches">
          {Object.entries(ACCENTS).map(([k, v]) => (
            <div key={k}
              className={`tweak-swatch ${tweaks.accent === k ? 'active' : ''}`}
              style={{ background: v.val }}
              title={v.name}
              onClick={() => update({ accent: k })} />
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <span className="lbl">Hero Headline</span>
        <div className="tweak-pills">
          {[
            ['build', 'In Crypto We Build'],
            ['ship', 'In Crypto We Ship'],
            ['layer', 'The Layer Beyond Chains'],
          ].map(([k, _]) => (
            <div key={k} className={`tweak-pill ${tweaks.hero === k ? 'active' : ''}`} onClick={() => update({ hero: k })}>
              {k}
            </div>
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <span className="lbl">Background</span>
        <div className="tweak-pills">
          {[['warm', '#0A0A0B'], ['cool', '#08090C'], ['black', '#000000']].map(([k]) => (
            <div key={k} className={`tweak-pill ${tweaks.bg === k ? 'active' : ''}`} onClick={() => update({ bg: k })}>{k}</div>
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <span className="lbl">Grid overlay</span>
        <div className="tweak-pills">
          {[['on', 'on'], ['off', 'off']].map(([k]) => (
            <div key={k} className={`tweak-pill ${tweaks.grid === k ? 'active' : ''}`} onClick={() => update({ grid: k })}>{k}</div>
          ))}
        </div>
      </div>
    </div>
  );
}

// === Theme effect (apply tweaks to :root) ===
function useThemeEffect(tweaks) {
  React.useEffect(() => {
    const root = document.documentElement;
    const a = ACCENTS[tweaks.accent] || ACCENTS.electric;
    root.style.setProperty('--accent', a.val);
    root.style.setProperty('--accent-glow', a.glow);
    root.style.setProperty('--accent-soft', a.soft);
    const bg = tweaks.bg === 'cool' ? '#08090C' : tweaks.bg === 'black' ? '#000000' : '#0A0A0B';
    root.style.setProperty('--bg', bg);
    document.body.style.background = bg;
    const grid = document.querySelector('.bg-grid');
    if (grid) grid.style.display = tweaks.grid === 'off' ? 'none' : 'block';
  }, [tweaks]);
}

// === Hero copy ===
const HERO_COPY = {
  build: { word1: 'In Crypto', word2: 'We Build' },
  ship:  { word1: 'In Crypto', word2: 'We Ship' },
  layer: { word1: 'The Layer', word2: 'Beyond Chains' },
};

Object.assign(window, {
  useReveal, CountUp, Nav, Footer, Tweaks, useThemeEffect, ACCENTS, HERO_COPY,
});
