/* global React */
// Shared primitives: Logo, Nav, Footer, Reveal, etc.

const { useState, useEffect, useRef, useCallback } = React;

// ---- Icons ----
const ArrowRight = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
    <line x1="4" y1="12" x2="20" y2="12" />
    <polyline points="14,6 20,12 14,18" />
  </svg>
);

// ---- Logo mark ----
const LogoMark = ({ dark }) => (
  <span className="nav-logo">
    <img
      src={dark ? '/tresor-capital/site/logo-white.png' : '/tresor-capital/site/logo-blue.png'}
      alt="Tresor Capital"
      className="nav-logo-img"
    />
  </span>
);

// ---- Scroll-reveal hook ----
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.15, rootMargin: '0px 0px -40px 0px' }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ---- Animated counter ----
function Counter({ to, duration = 1800, prefix = '', suffix = '' }) {
  const [v, setV] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const p = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setV(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{prefix}{v.toLocaleString('nl-NL')}{suffix}</span>;
}

// ---- Nav ----
function Nav({ route, setRoute, lang, setLang, openLogin, onDark }) {
  const t = window.COPY[lang].nav;
  const items = [
    { k: 'home', label: t.home },
    { k: 'offering', label: t.offering },
    { k: 'about', label: t.about },
    { k: 'news', label: t.news },
    { k: 'contact', label: t.contact },
  ];
  return (
    <nav className={"nav" + (onDark ? ' on-dark' : '')}>
      <div className="nav-inner">
        <a onClick={() => setRoute('home')} style={{cursor:'pointer'}}>
          <LogoMark dark={onDark} />
        </a>
        <div className="nav-links">
          {items.map((i) => (
            <a key={i.k} className={"nav-link" + (route === i.k ? ' active' : '')} onClick={() => setRoute(i.k)}>
              {i.label}
            </a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-toggle">
            <button className={lang === 'nl' ? 'on' : ''} onClick={() => setLang('nl')}>NL</button>
            <span className="sep">/</span>
            <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <button className="nav-cta" onClick={openLogin}>{t.login}</button>
        </div>
      </div>
    </nav>
  );
}

// ---- Footer ----
function Footer({ lang, setRoute }) {
  const t = window.COPY[lang];
  const year = 2026;
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-col">
            <img src="/tresor-capital/site/logo-blue.png" alt="Tresor Capital" style={{ width: 240, height: 'auto', marginBottom: 28, display: 'block', filter: 'brightness(0) invert(1)' }} />
            <p style={{ maxWidth: 300, fontSize: 15, lineHeight: 1.6 }}>{t.footer.tagline}</p>
          </div>
          <div className="foot-col">
            <span className="caps">{t.footer.nav_label}</span>
            <ul>
              <li><a onClick={() => setRoute('home')} style={{cursor:'pointer'}}>{t.nav.home}</a></li>
              <li><a onClick={() => setRoute('offering')} style={{cursor:'pointer'}}>{t.nav.offering}</a></li>
              <li><a onClick={() => setRoute('about')} style={{cursor:'pointer'}}>{t.nav.about}</a></li>
              <li><a onClick={() => setRoute('news')} style={{cursor:'pointer'}}>{t.nav.news}</a></li>
              <li><a onClick={() => setRoute('contact')} style={{cursor:'pointer'}}>{t.nav.contact}</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <span className="caps">{t.footer.office_label}</span>
            <ul>
              {t.contact.address.map((l, i) => <li key={i}>{l}</li>)}
              <li style={{ marginTop: 14 }}>{t.contact.email}</li>
              <li>{t.contact.phone}</li>
            </ul>
          </div>
          <div className="foot-col">
            <span className="caps">{t.footer.news_label}</span>
            <p style={{ fontSize: 14, marginBottom: 20, lineHeight: 1.6 }}>{t.footer.news_body}</p>
            <form className="news-form" onSubmit={(e) => { e.preventDefault(); }}>
              <input type="email" placeholder={t.news.email_ph} />
              <button type="submit">{t.news.subscribe} →</button>
            </form>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© {year} — {t.footer.rights}</span>
          <span style={{ display: 'flex', gap: 28 }}>
            <a style={{cursor:'pointer'}}>{t.footer.disclaimer}</a>
            <a style={{cursor:'pointer'}}>{t.footer.oversight}</a>
            <a style={{cursor:'pointer'}}>{t.footer.privacy}</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---- Login modal ----
function LoginModal({ open, onClose, lang }) {
  const t = window.COPY[lang].login_modal;
  useEffect(() => {
    document.body.classList.toggle('locked', open);
  }, [open]);
  return (
    <div className={"modal-backdrop" + (open ? ' open' : '')} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>×</button>
        <img src="/tresor-capital/site/tc-icon.png" alt="" style={{ width: 56, height: 56, marginBottom: 24, display: 'block' }} />
        <div className="eyebrow" style={{ marginBottom: 20 }}>Tresor Capital</div>
        <h2 className="serif" style={{ fontSize: 40, marginBottom: 10 }}>{t.title}</h2>
        <p style={{ color: 'var(--muted)', marginBottom: 32 }}>{t.sub}</p>
        <form onSubmit={(e) => e.preventDefault()}>
          <Field label={t.email} type="email" />
          <Field label={t.password} type="password" />
          <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}>
            {t.submit} <ArrowRight />
          </button>
          <a style={{ display: 'block', marginTop: 18, fontSize: 13, color: 'var(--muted)', textAlign: 'center', cursor:'pointer' }}>
            {t.forgot}
          </a>
        </form>
      </div>
    </div>
  );
}

function Field({ label, type = 'text' }) {
  return (
    <label style={{ display: 'block', marginBottom: 20 }}>
      <span style={{
        display: 'block',
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'var(--muted)', marginBottom: 8,
      }}>{label}</span>
      <input type={type} style={{
        width: '100%', padding: '12px 0',
        border: 'none', borderBottom: '1px solid var(--rule-strong)',
        background: 'transparent', font: 'inherit', fontSize: 15, outline: 'none',
        color: 'var(--navy)',
      }} onFocus={(e) => e.target.style.borderColor = 'var(--accent)'}
         onBlur={(e) => e.target.style.borderColor = 'var(--rule-strong)'} />
    </label>
  );
}

// ---- Tweaks panel ----
function TweaksPanel() {
  const [active, setActive] = useState(false);
  const [accent, setAccent] = useState('#B8962E');
  const swatches = [
    { hex: '#B8962E', name: 'Gold' },
    { hex: '#9C6B3A', name: 'Copper' },
    { hex: '#4A7359', name: 'Moss' },
    { hex: '#8A3E3E', name: 'Claret' },
    { hex: '#3D5A80', name: 'Slate' },
    { hex: '#1C2B4B', name: 'Navy' },
  ];
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setActive(true);
      if (e.data?.type === '__deactivate_edit_mode') setActive(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);
  useEffect(() => {
    document.documentElement.style.setProperty('--accent', accent);
  }, [accent]);
  if (!active) return null;
  const current = swatches.find((s) => s.hex === accent) || swatches[0];
  return (
    <div className="tweaks-panel show">
      <div className="tweaks-title">Tweaks — Accent</div>
      <div className="swatches">
        {swatches.map((s) => (
          <button
            key={s.hex}
            className={"swatch" + (s.hex === accent ? ' on' : '')}
            style={{ background: s.hex }}
            title={s.name}
            onClick={() => setAccent(s.hex)}
          />
        ))}
      </div>
      <div className="tweaks-label">{current.name} — {current.hex}</div>
    </div>
  );
}

window.Tresor = {
  ArrowRight, LogoMark, useReveal, Counter,
  Nav, Footer, LoginModal, TweaksPanel, Field,
};
