// components-ui.jsx — small shared UI elements (Nav, Button, Sticker, Eyebrow)

function Button({ variant = 'primary', children, icon = '→', href, onClick, size = 'md', className = '' }) {
  const El = href ? 'a' : 'button';
  const cls = `btn btn--${variant}${size === 'sm' ? ' btn--sm' : ''} ${className}`;
  return (
    <El className={cls} href={href} onClick={onClick}>
      <span>{children}</span>
      {icon && <span className="btn__arrow" aria-hidden="true">{icon}</span>}
    </El>
  );
}

function Eyebrow({ children, className = '', style }) {
  return <div className={`eyebrow-dot ${className}`} style={style}>{children}</div>;
}

/* Sticker badge — inline-flex italic pill with 2px ink border (used in hero) */
function Sticker({ variant = 'peach', rotate = -3, children, style, className = '' }) {
  const bgMap = {
    peach: 'var(--peach-100)',
    lilac: 'var(--lilac)',
    mint: 'var(--mint)',
    butter: 'var(--butter)',
    paper: 'var(--paper)',
  };
  return (
    <span className={className} style={{
      display: 'inline-flex', alignItems: 'center',
      fontFamily: 'var(--font-serif)', fontStyle: 'italic',
      fontSize: 17, lineHeight: 1,
      padding: '10px 18px',
      background: bgMap[variant],
      color: 'var(--ink)',
      border: '2px solid var(--ink)',
      borderRadius: 999,
      transform: `rotate(${rotate}deg)`,
      whiteSpace: 'nowrap',
      ...style,
    }}>{children}</span>
  );
}

const BRAND_WORDMARK_SRC = 'assets/logo/amorce-wordmark.svg';

/* Wordmark inlined from the design-system file so the symbol can be animated on its own */
function BrandLogo({ href, height = 34 }) {
  const holderRef = useRef(null);
  const [inline, setInline] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch(BRAND_WORDMARK_SRC)
      .then(r => (r.ok ? r.text() : Promise.reject(r.status)))
      .then(text => {
        if (cancelled || !holderRef.current) return;
        const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
        const svg = doc.documentElement;
        const symbol = svg.querySelector(':scope > g');
        if (svg.nodeName !== 'svg' || !symbol || symbol.children.length < 3) return;
        svg.querySelectorAll('metadata, title').forEach(n => n.remove());
        const [shadow, ...parts] = Array.from(symbol.children);
        shadow.setAttribute('class', 'brand-shadow');
        const disc = doc.createElementNS('http://www.w3.org/2000/svg', 'g');
        disc.setAttribute('class', 'brand-disc');
        parts.forEach(n => disc.appendChild(n));
        symbol.appendChild(disc);
        disc.querySelectorAll('path').forEach((p, i) => p.setAttribute('class', `brand-contour brand-contour--${i}`));
        const summit = disc.querySelector('circle:last-of-type');
        if (summit) summit.setAttribute('class', 'brand-summit');
        svg.removeAttribute('role');
        svg.setAttribute('aria-hidden', 'true');
        svg.setAttribute('focusable', 'false');
        svg.style.height = `${height}px`;
        svg.style.width = 'auto';
        holderRef.current.appendChild(document.importNode(svg, true));
        setInline(true);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, [height]);

  return (
    <a href={href} className={`brand-logo${inline ? ' is-inline' : ''}`} aria-label="Amorce, retour à l'accueil">
      <span ref={holderRef} className="brand-logo__svg"></span>
      {!inline && <img src={BRAND_WORDMARK_SRC} alt="" style={{ height }} />}
    </a>
  );
}

/* Fixed-top nav — becomes opaque on scroll */
function TopNav({ links: customLinks, homeHref = '#top' }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const defaultLinks = [
    ['Méthode', '#methode'],
    ['Expertise', '#expertise'],
    ['Crédos', '#credos'],
    ['À propos', '#about'],
    ['Blog', 'blog.html'],
  ];

  const links = customLinks || defaultLinks;

  const rdvHref = homeHref.startsWith('#') ? '#rdv' : `${homeHref}#rdv`;

  return (
    <>
    <a className="skip-link" href="#contenu">Aller au contenu</a>
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 40,
      height: 72,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 clamp(20px, 4vw, 48px)',
      background: scrolled ? 'rgba(255,253,247,0.82)' : 'transparent',
      backdropFilter: scrolled ? 'blur(12px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(12px)' : 'none',
      borderBottom: scrolled ? '1px solid var(--chalk)' : '1px solid transparent',
      transition: 'background 240ms var(--ease-out), border-color 240ms var(--ease-out)',
    }}>
      <BrandLogo href={homeHref} height={42} />
      <div className="nav-links-desktop" style={{ display: 'flex', gap: 32, alignItems: 'center' }}>
        {links.map(([lbl, href]) => (
          <a key={href} href={href} style={{
            fontFamily: 'var(--font-tight)', fontSize: 13, fontWeight: 500,
            color: 'var(--fg-2)', textDecoration: 'none',
            letterSpacing: '-0.005em',
          }}>{lbl}</a>
        ))}
      </div>
      <Button variant="accent" size="sm" href={rdvHref}>Prendre rendez-vous</Button>
    </nav>
    </>
  );
}

Object.assign(window, { Button, Eyebrow, Sticker, TopNav });
