// Shared building blocks: logo, nav (responsive), footer, buttons, badges.

const { useState: useState_P, useEffect: useEffect_P } = React;

// ── Brand mark + wordmark ──────────────────────────────────────────
function Logo({ size = 44, color = '#FDB022' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
         fill="none" style={{ color, flexShrink: 0 }} aria-hidden="true">
      <path fill="currentColor" fillRule="nonzero" d="M 1.341 0.002 C 1.661 -0.002 1.981 0 2.3 0.01 C 3.766 0.046 4.705 0.121 6.104 0.481 C 8.408 1.07 10.484 2.142 12.129 3.59 C 12.544 3.11 13.182 2.681 13.732 2.319 C 15.293 1.292 16.932 0.682 18.863 0.281 C 19.936 0.071 21.068 0.001 22.168 0.01 C 22.773 0.015 23.847 -0.104 23.945 0.576 C 24.023 1.122 23.995 1.711 23.995 2.263 L 23.996 5.706 L 23.996 13.101 L 23.998 15.67 C 23.998 16.128 23.998 16.586 23.988 17.044 C 23.981 17.372 23.831 17.707 23.431 17.833 C 23.115 17.931 22.782 17.999 22.457 18.075 C 21.274 18.351 20.08 18.614 18.95 19.019 C 18.771 19.083 18.586 19.149 18.395 19.186 C 18.644 19.628 18.77 20.077 18.964 20.524 C 19.413 21.562 19.851 22.666 20.202 23.73 C 19.897 23.996 19.54 23.961 19.108 23.977 C 18.715 23.982 18.395 24.007 18.011 23.934 C 17.731 23.588 17.385 22.575 17.217 22.148 L 16.359 19.99 C 16.149 20.196 15.605 20.438 15.315 20.605 C 14.425 21.118 13.595 21.67 12.746 22.227 C 12.432 22.433 11.822 22.562 11.456 22.375 C 10.909 22.096 10.419 21.67 9.891 21.355 C 9.057 20.807 8.259 20.325 7.348 19.867 C 7.242 20.268 6.96 20.915 6.799 21.316 C 6.562 21.91 6.13 23.488 5.707 23.941 C 5.251 24.002 3.96 24.074 3.615 23.83 C 3.497 23.641 3.88 22.714 3.972 22.462 L 4.8 20.244 C 4.963 19.795 5.094 19.464 5.211 19.001 C 4.548 18.824 3.884 18.62 3.207 18.471 C 2.375 18.289 1.542 18.126 0.72 17.908 C 0.203 17.77 0.037 17.563 0.013 17.117 C -0.008 16.721 0.003 16.325 0.003 15.929 C 0 15.239 0.002 14.549 0.01 13.859 L 0.011 8.525 L 0.01 3.415 C 0.009 2.511 -0.016 1.603 0.023 0.699 C 0.052 0.032 0.722 0.02 1.341 0.002 Z M 5.899 17.277 C 6.029 17.145 6.157 16.719 6.221 16.54 C 6.309 16.207 6.521 15.808 6.611 15.498 C 6.903 14.49 7.29 14.581 8.353 14.856 C 8.562 14.91 8.885 14.975 9.028 15.117 C 9.048 15.157 9.046 15.195 9.03 15.235 C 8.674 16.132 8.448 17.11 8.062 17.994 C 8.492 18.256 9.105 18.528 9.505 18.78 C 10.01 19.099 11.6 19.944 11.88 20.349 C 12.414 19.963 13.064 19.633 13.633 19.283 C 14.27 18.892 14.961 18.56 15.658 18.245 C 15.542 18.058 15.426 17.708 15.343 17.493 C 15.146 16.993 14.937 16.459 14.607 16.005 C 13.324 14.239 10.584 14.022 8.795 12.749 C 7.23 11.637 7.045 9.684 8.105 8.288 C 9.573 6.355 13.126 6.009 15.17 7.494 C 16.279 8.302 16.597 9.577 16.663 10.738 C 16.673 10.906 16.702 11.27 16.562 11.394 C 16.356 11.469 14.709 11.431 14.425 11.416 C 14.368 10.944 14.4 10.481 14.295 10.009 C 14.029 8.806 12.829 8.25 11.397 8.475 C 11.074 8.54 10.874 8.628 10.599 8.778 C 10.309 8.958 10.173 9.108 9.968 9.358 C 9.096 10.939 10.733 11.637 12.226 12.198 C 13.8 12.79 15.566 13.545 16.459 14.816 C 16.936 15.495 17.44 16.626 17.662 17.401 C 18.703 17.049 19.917 16.704 21.005 16.465 C 21.217 16.418 21.59 16.334 21.791 16.314 L 21.792 7.247 L 21.792 3.188 C 21.792 2.731 21.778 2.257 21.786 1.803 C 20.843 1.898 19.929 1.977 19.008 2.179 C 18.584 2.273 18.293 2.386 17.892 2.51 C 16.292 3 14.912 3.883 13.728 4.877 C 13.366 5.181 13.099 5.507 12.619 5.687 C 11.709 6.033 11.115 5.33 10.565 4.876 C 10.284 4.645 9.878 4.384 9.566 4.163 C 8.33 3.287 6.851 2.634 5.296 2.23 C 4.365 1.988 3.293 1.878 2.323 1.807 C 2.345 2.292 2.327 2.821 2.326 3.313 L 2.327 5.805 L 2.329 13.87 C 2.329 14.111 2.314 16.241 2.35 16.303 C 2.884 16.436 3.574 16.567 4.085 16.715 C 4.407 16.808 5.688 17.149 5.899 17.277 Z"></path>
    </svg>
  );
}

function Lockup({ size = 36, fontSize = 22 }) {
  return (
    <a href="/" className="inline-flex items-center gap-2 no-underline" aria-label="Scholarly Affairs home">
      <Logo size={size} color="#FDB022" />
      <span className="font-bold whitespace-nowrap"
            style={{ color: '#6726DB', fontSize, letterSpacing: '-0.05em' }}>Scholarly Affairs</span>
    </a>
  );
}

// ── Pill badge ─────────────────────────────────────────────────────
function Badge({ children, variant = 'lavender', size = 'md', className = '' }) {
  const sizeCls = size === 'lg' ? 'px-7 py-2.5 text-base' : 'px-6 py-2 text-sm';
  const variantCls =
    variant === 'cream' ? 'bg-sa-cream text-sa-purple' :
    variant === 'white' ? 'bg-white text-sa-purple' :
    'bg-sa-lavender-50 text-sa-purple';
  return (
    <span className={`inline-flex items-center justify-center font-bold rounded-sa-pill w-fit ${sizeCls} ${variantCls} ${className}`}>
      {children}
    </span>
  );
}

// ── Material Symbol shorthand ──────────────────────────────────────
function Icon({ name, size = 24, color, className = '', style = {} }) {
  return (
    <span className={`sa-icon ${className}`} aria-hidden="true"
          style={{ fontSize: size, color, lineHeight: 1, ...style }}>{name}</span>
  );
}

// ── Buttons ───────────────────────────────────────────────────────
function Btn({ children, variant = 'primary', icon, onClick, href, type, className = '', style = {}, fullWidth, size = 'md' }) {
  const sizeCls = size === 'lg' ? 'px-7 h-12 text-base' : size === 'sm' ? 'px-4 h-9 text-sm' : 'px-6 h-11 text-[15px]';
  const base = `inline-flex items-center justify-center gap-2 font-bold rounded-sa-pill no-underline cursor-pointer border-0 btn-press ${sizeCls}`;
  const variants = {
    primary: 'bg-sa-yellow-mid hover:bg-sa-yellow-dark text-sa-black',
    purple:  'bg-sa-purple hover:bg-sa-purple-dark text-white',
    ghost:   'bg-transparent border border-sa-purple text-sa-purple hover:bg-sa-lavender-50',
    white:   'bg-white text-sa-purple hover:bg-sa-lavender-50',
  };
  const cls = `${base} ${variants[variant] || variants.primary} ${fullWidth ? 'w-full' : ''} ${className}`;
  const inner = <>{children}{icon ? <Icon name={icon} size={18} /> : null}</>;
  if (href) {
    const isExternal = /^https?:\/\//.test(href);
    return (
      <a
        href={href}
        className={cls}
        style={style}
        onClick={onClick}
        target={isExternal ? '_blank' : undefined}
        rel={isExternal ? 'noopener noreferrer' : undefined}
      >
        {inner}
      </a>
    );
  }
  return <button type={type || 'button'} className={cls} style={style} onClick={onClick}>{inner}</button>;
}

// ── Section header (badge + h2 + sub) ───────────────────────────────
function SectionHead({ badge, badgeVariant = 'lavender', title, sub, align = 'center', titleStyle, className = '' }) {
  return (
    <div className={`flex flex-col gap-5 ${align === 'center' ? 'items-center text-center mx-auto' : 'items-start text-left'} ${className}`}
         style={{ maxWidth: align === 'center' ? 920 : 760 }}>
      {badge ? <Reveal direction="up"><Badge variant={badgeVariant}>{badge}</Badge></Reveal> : null}
      <Reveal direction="up" delay={60}><h2 className="h-section" style={titleStyle}>{title}</h2></Reveal>
      {sub ? <Reveal direction="up" delay={120}><p className="body-lg max-w-3xl">{sub}</p></Reveal> : null}
    </div>
  );
}

// ── Top navigation (responsive with mobile drawer) ─────────────────
function Navigation({ active }) {
  const [open, setOpen] = useState_P(false);
  useEffect_P(() => {
    const close = () => setOpen(false);
    window.addEventListener('popstate', close);
    window.addEventListener('app:navigation', close);
    return () => {
      window.removeEventListener('popstate', close);
      window.removeEventListener('app:navigation', close);
    };
  }, []);
  useEffect_P(() => {
    document.body.style.overflow = open ? 'hidden' : '';
  }, [open]);

  const items = [
    { id: 'home',     label: 'Home',     href: '/' },
    { id: 'about',    label: 'About',    href: '/about' },
    { id: 'services', label: 'Services', href: '/services' },
  ];

  return (
    <header className="sticky top-0 z-50 bg-white border-b border-sa-border">
      <div className="container-wide sec-x flex items-center justify-between" style={{ height: 80 }}>
        <Lockup size={38} fontSize={22} />

        {/* Desktop nav */}
        <nav className="hidden md:flex items-center gap-1">
          {items.map(it => (
            <a key={it.id} href={it.href}
               className={`px-4 py-2 rounded-sa-pill text-[15px] transition-colors ${
                 active === it.id
                   ? 'font-bold text-sa-purple bg-sa-lavender-50'
                   : 'font-medium text-sa-slate-2 hover:bg-sa-lavender-50'
               }`}>{it.label}</a>
          ))}
        </nav>

        <div className="hidden md:block">
          <Btn href="/contact">Get In Touch</Btn>
        </div>

        {/* Mobile menu trigger */}
        <button
          className="md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full bg-sa-lavender-50 text-sa-purple"
          onClick={() => setOpen(true)} aria-label="Open menu">
          <Icon name="menu" size={24} />
        </button>
      </div>

      {/* Mobile drawer */}
      <div className={`mobile-drawer md:hidden ${open ? 'is-open' : ''}`} onClick={() => setOpen(false)}>
        <aside className="mobile-drawer__panel" onClick={(e) => e.stopPropagation()}>
          <div className="flex items-center justify-between">
            <Lockup size={34} fontSize={20} />
            <button
              className="inline-flex items-center justify-center w-9 h-9 rounded-full bg-sa-lavender-50 text-sa-purple"
              onClick={() => setOpen(false)} aria-label="Close menu">
              <Icon name="close" size={22} />
            </button>
          </div>
          <hr className="border-sa-border" />
          <nav className="flex flex-col gap-1">
            {items.map(it => (
              <a key={it.id} href={it.href}
                 className={`block px-4 py-3 rounded-sa-pill text-base ${
                   active === it.id
                     ? 'font-bold text-sa-purple bg-sa-lavender-50'
                     : 'font-medium text-sa-slate-2'
                 }`}>{it.label}</a>
            ))}
          </nav>
          <Btn href="/contact" fullWidth>Get In Touch</Btn>
        </aside>
      </div>
    </header>
  );
}

// ── Social glyphs ──────────────────────────────────────────────────
function FacebookGlyph()  { return <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M13.5 22v-8h2.7l.4-3.2h-3.1V8.7c0-.9.3-1.6 1.6-1.6H17V4.2c-.3 0-1.4-.1-2.7-.1-2.7 0-4.5 1.6-4.5 4.6v2.1H7v3.2h2.8V22h3.7z"/></svg>; }
function InstagramGlyph() { return <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.3" cy="6.7" r="1" fill="currentColor" stroke="none"/></svg>; }
function LinkedInGlyph()  { return <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M4.98 3.5a2.5 2.5 0 1 1 .02 5 2.5 2.5 0 0 1-.02-5zM3 10h4v11H3V10zm7 0h3.8v1.6h.05c.53-1 1.83-2.05 3.77-2.05C21.2 9.55 22 12 22 14.7V21h-4v-5.6c0-1.34-.02-3.07-1.87-3.07-1.87 0-2.16 1.46-2.16 2.97V21h-4V10z"/></svg>; }
function TwitterGlyph()   { return <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M18.3 3H21l-6.55 7.5L22 21h-6.06l-4.74-6.2L5.6 21H3l7-8L2 3h6.18l4.28 5.66L18.3 3zm-1.06 16h1.67L7.86 4.9H6.07L17.24 19z"/></svg>; }

function Footer() {
  const socials = [
    { label: 'Twitter',   glyph: <TwitterGlyph /> },
    { label: 'Facebook',  glyph: <FacebookGlyph /> },
    { label: 'Instagram', glyph: <InstagramGlyph /> },
    { label: 'LinkedIn',  glyph: <LinkedInGlyph /> },
  ];
  const [email, setEmail] = useState_P('');
  const [subscribed, setSub] = useState_P(false);
  const [newsletterSubmitting, setNewsletterSubmitting] = useState_P(false);
  const [newsletterStatus, setNewsletterStatus] = useState_P(null);

  const onNewsletterSubmit = async (event) => {
    event.preventDefault();
    if (newsletterSubmitting) return;

    const cleanEmail = email.trim();
    if (!cleanEmail || !/^\S+@\S+\.\S+$/.test(cleanEmail)) {
      setNewsletterStatus({ type: 'error', message: 'Enter a valid email address.' });
      return;
    }

    setNewsletterSubmitting(true);
    setNewsletterStatus(null);
    setSub(false);

    try {
      const response = await fetch('/api/newsletter', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: cleanEmail,
          sourcePage: window.location.pathname || '/',
        }),
      });
      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data.ok) {
        setNewsletterStatus({
          type: 'error',
          message: data.message || 'We could not subscribe you right now. Please try again.',
        });
        return;
      }

      setSub(true);
      setEmail('');
      setNewsletterStatus({
        type: 'success',
        message: data.message || 'Thanks, you are subscribed.',
      });
      setTimeout(() => {
        setSub(false);
        setNewsletterStatus(null);
      }, 3000);
    } catch (error) {
      setNewsletterStatus({
        type: 'error',
        message: 'We could not subscribe you right now. Please try again.',
      });
    } finally {
      setNewsletterSubmitting(false);
    }
  };

  return (
    <footer className="bg-white border-t border-sa-border">
      <div className="container-wide sec-x py-12 md:py-14">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-10 md:gap-16">
          <div>
            <Lockup size={36} fontSize={22} />
            <p className="mt-3 text-sm text-sa-slate-2">
              info@scholarlyaffairs.com&nbsp;&nbsp;|&nbsp;&nbsp;+44 7392 559481 (UK)
            </p>
            <div className="flex gap-3 mt-5">
              {socials.map(s => (
                <a key={s.label} href="#" aria-label={s.label}
                   className="w-9 h-9 rounded-full bg-sa-yellow-mid text-sa-black inline-flex items-center justify-center transition-transform hover:scale-110">
                  {s.glyph}
                </a>
              ))}
            </div>
          </div>
          <div>
            <h6 className="font-bold text-base text-sa-ink mb-4">Menu</h6>
            <ul className="m-0 p-0 list-none flex flex-col gap-3">
              {[
                { label: 'About Us',   href: '/about' },
                { label: 'Services',   href: '/services' },
                { label: 'Help Center', href: '/contact' },
              ].map(l => (
                <li key={l.label}>
                  <a href={l.href} className="text-[15px] text-sa-slate-2 hover:text-sa-purple no-underline transition-colors">{l.label}</a>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <h6 className="font-bold text-base text-sa-ink mb-2">Stay in the loop!</h6>
            <p className="text-sm text-sa-slate-2 mb-4">Subscribe to our newsletter for course updates, expert tips, and special offers.</p>
            <form
              className="relative flex"
              onSubmit={onNewsletterSubmit}>
              <input
                className="sa-input"
                placeholder="Enter your email"
                style={{ paddingRight: 116 }}
                value={email} onChange={e => { setEmail(e.target.value); setNewsletterStatus(null); }}
                type="email"
                aria-label="Email address"
                aria-invalid={newsletterStatus?.type === 'error'}
              />
              <button
                type="submit"
                disabled={newsletterSubmitting}
                className="footer-newsletter-submit absolute top-1 right-1 bottom-1 px-4 rounded-sa-pill bg-sa-yellow-mid hover:bg-sa-yellow-dark text-sa-black font-bold text-sm transition-colors">
                {newsletterSubmitting ? 'Sending...' : subscribed ? '✓ Subscribed' : 'Subscribe'}
              </button>
            </form>
            {newsletterStatus ? (
              <p className={`footer-newsletter-status is-${newsletterStatus.type}`} role="status" aria-live="polite">
                {newsletterStatus.message}
              </p>
            ) : null}
          </div>
        </div>

        <hr className="my-8 border-sa-border" />

        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
          <p className="text-sm text-sa-slate-2 m-0">© 2026 Scholarly Affairs Ltd is registered in England and Wales (Company number 16347069)</p>
          <div className="flex gap-5">
            <a href="#" className="text-sm text-sa-slate-2 hover:text-sa-purple no-underline">Terms &amp; Conditions</a>
            <a href="#" className="text-sm text-sa-slate-2 hover:text-sa-purple no-underline">Privacy Policy</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Logo, Lockup, Badge, Icon, Btn, SectionHead, Navigation, Footer,
  FacebookGlyph, InstagramGlyph, LinkedInGlyph, TwitterGlyph,
});
