/* Bruno Nardi — shared site chrome: theme, header, footer, contact, socials.
   Exposes components on window for both pages to consume. */

const { Button, IconButton, Avatar, Badge, Card } = window.BrunoDevDesignSystem_8422e8;
const { Icon } = window.BDIcons;

const LINKS = {
  demo: 'https://app.devdemo.brunonardi.io',
  arena: 'https://botarena.brunonardi.io',
  github: 'https://github.com/Bruno-N',
  linkedin: 'https://www.linkedin.com/in/bruno-snardi',
  email: 'contact@brunonardi.io',
};

/* ---- Theme: follow the OS preference, allow a persisted toggle --------- */
function applyTheme(t) {
  document.documentElement.setAttribute('data-theme', t);
  try { localStorage.setItem('bruno-theme', t); } catch (e) {}
}
function useTheme() {
  const read = () => document.documentElement.getAttribute('data-theme') || 'dark';
  const [theme, setTheme] = React.useState(read);
  React.useEffect(() => {
    // react to OS changes only when the user hasn't explicitly chosen
    const mq = window.matchMedia('(prefers-color-scheme: light)');
    const onChange = (e) => {
      let saved = null;
      try { saved = localStorage.getItem('bruno-theme'); } catch (err) {}
      if (!saved) { const t = e.matches ? 'light' : 'dark'; applyTheme(t); setTheme(t); }
    };
    mq.addEventListener?.('change', onChange);
    return () => mq.removeEventListener?.('change', onChange);
  }, []);
  const toggle = () => { const next = theme === 'dark' ? 'light' : 'dark'; applyTheme(next); setTheme(next); };
  return [theme, toggle];
}

/* ---- Studio-grid backdrop --------------------------------------------- */
function Backdrop() {
  return <div className="bd-backdrop" aria-hidden="true" />;
}

/* ---- Header ----------------------------------------------------------- */
const NAV = [
  { label: 'Home', href: '/', key: 'home' },
  { label: 'Experience', href: '/experience', key: 'experience' },
  { label: 'Stack', href: '/#stack', key: 'stack' },
  { label: 'Contact', href: '#contact', key: 'contact' },
];

function Header({ active, nav, brandHref = '/' }) {
  const [theme, toggle] = useTheme();
  const items = nav || NAV;
  return (
    <header className="bd-header">
      <div className="bd-page bd-header__inner">
        <a href={brandHref} className="bd-brand">
          <img src="assets/logomark.svg" width="34" height="34" alt="" />
          <span className="bd-brand__word">Bruno<span style={{ color: 'var(--accent)' }}>Nardi</span></span>
        </a>
        <nav className="bd-nav">
          {items.map((n) => (
            <a key={n.key} href={n.href}
               className={'bd-nav__link' + (active === n.key ? ' is-active' : '')}>
              {n.label}
            </a>
          ))}
        </nav>
        <div className="bd-header__actions">
          <IconButton label="Toggle theme" variant="outline" size="sm" onClick={toggle}>
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={16} />
          </IconButton>
          <Button size="sm" variant="primary" href={'mailto:' + LINKS.email}
                  iconRight={<Icon name="arrow-right" size={15} />}>
            Get in touch
          </Button>
        </div>
      </div>
    </header>
  );
}

/* ---- Social icon row -------------------------------------------------- */
function Socials() {
  return (
    <div className="bd-socials">
      <IconButton label="GitHub" variant="outline" href={LINKS.github} target="_blank" rel="noopener">
        <Icon name="github" size={18} />
      </IconButton>
      <IconButton label="LinkedIn" variant="outline" href={LINKS.linkedin} target="_blank" rel="noopener">
        <Icon name="linkedin" size={18} />
      </IconButton>
      <IconButton label="Email" variant="outline" href={'mailto:' + LINKS.email}>
        <Icon name="mail" size={18} />
      </IconButton>
    </div>
  );
}

/* ---- Contact section (shared, id="contact") --------------------------- */
function ContactSection() {
  return (
    <section id="contact" className="bd-section bd-contact">
      <div className="bd-page bd-contact__inner">
        <div className="bd-contact__copy">
          <span className="eyebrow">— Get in touch</span>
          <h2 className="bd-contact__title">
            Have a system worth<br /><span className="accent-italic">building right?</span>
          </h2>
          <p className="bd-lead" style={{ maxWidth: 440 }}>
            I&rsquo;m a senior full-stack engineer based in London, open to roles and
            select contract work — modernising legacy platforms, designing scalable
            services, shipping the thing end to end. Tell me what you&rsquo;re building.
          </p>
          <div className="bd-contact__cta">
            <Button size="lg" variant="primary" href={'mailto:' + LINKS.email}
                    iconLeft={<Icon name="mail" size={18} />}>
              contact@brunonardi.io
            </Button>
          </div>
          <div className="bd-contact__person">
            <Avatar name="Bruno Nardi" size="lg" accent online />
            <div>
              <div className="bd-contact__name">Bruno Nardi</div>
              <div className="bd-contact__role">
                <Icon name="map-pin" size={13} style={{ verticalAlign: '-2px', marginRight: 4 }} />
                London, UK · usually replies within a day
              </div>
            </div>
            <div style={{ marginLeft: 'auto' }}><Socials /></div>
          </div>
        </div>
        <ContactAside />
      </div>
    </section>
  );
}

function ContactAside() {
  const items = [
    { icon: 'play-circle', label: 'Live demo', value: 'app.devdemo.brunonardi.io', href: LINKS.demo, accent: true },
    { icon: 'github', label: 'Code', value: 'github.com/Bruno-N', href: LINKS.github },
    { icon: 'linkedin', label: 'LinkedIn', value: 'in/bruno-snardi', href: LINKS.linkedin },
    { icon: 'mail', label: 'Email', value: 'contact@brunonardi.io', href: 'mailto:' + LINKS.email },
  ];
  return (
    <Card variant="raised" accent className="bd-contact__card">
      <span className="eyebrow" style={{ color: 'var(--text-subtle)' }}>Find me</span>
      <div className="bd-linklist">
        {items.map((it) => (
          <a key={it.label} className="bd-linkrow" href={it.href}
             target={it.href.startsWith('mailto') ? undefined : '_blank'} rel="noopener">
            <span className={'bd-linkrow__icon' + (it.accent ? ' is-accent' : '')}>
              <Icon name={it.icon} size={18} />
            </span>
            <span className="bd-linkrow__text">
              <span className="bd-linkrow__label">{it.label}</span>
              <span className="bd-linkrow__value">{it.value}</span>
            </span>
            <Icon name="arrow-up-right" size={16} className="bd-linkrow__go" />
          </a>
        ))}
      </div>
    </Card>
  );
}

/* ---- Footer ----------------------------------------------------------- */
function Footer() {
  return (
    <footer className="bd-footer">
      <div className="bd-page bd-footer__inner">
        <a href="/" className="bd-brand">
          <img src="assets/logomark.svg" width="28" height="28" alt="" />
          <span className="bd-brand__word" style={{ fontSize: 15 }}>
            Bruno<span style={{ color: 'var(--accent)' }}>Nardi</span>
          </span>
        </a>
        <span className="bd-footer__note">
          Senior Full-Stack Engineer · London · {new Date().getFullYear()}
        </span>
        <Socials />
      </div>
    </footer>
  );
}

/* favicon-service helper — reliable, CORS-friendly brand marks */
const favicon = (domain) => 'https://www.google.com/s2/favicons?domain=' + domain + '&sz=128';

/* ---- Logo slot: real logo image when we have one, else a branded monogram
   fallback. A separate probe Image decides BEFORE the visible <img> mounts —
   so the logo only ever paints once it's confirmed loaded and big enough
   (tiny 16px favicons fall back to the monogram rather than rendering blurry,
   and a slow/blocked/failed request degrades to a clean tile, never an empty
   box or an overlap). A drag-drop target stays available either way. ---- */
function LogoSlot({ id, label, src, size = 48, radius = 9 }) {
  const [loaded, setLoaded] = React.useState(false);
  React.useEffect(() => {
    setLoaded(false);
    if (!src) return;
    let cancelled = false;
    const probe = new Image();
    probe.referrerPolicy = 'no-referrer';
    const decide = () => { if (!cancelled) setLoaded(probe.naturalWidth >= 32); };
    probe.onload = decide;
    probe.onerror = () => {};
    probe.src = src;
    if (probe.complete && probe.naturalWidth) decide();
    return () => { cancelled = true; };
  }, [src]);
  return (
    <span className={'logowrap' + (loaded ? ' logowrap--filled' : '')}
          style={{ width: size, height: size, borderRadius: radius + 2 }}>
      <span className="logowrap__mono" style={{ fontSize: Math.round(size * 0.36) }}>{(label || '').slice(0, 2)}</span>
      {loaded && (
        <img className="logowrap__img" src={src} alt={(label || '') + ' logo'} referrerPolicy="no-referrer" />
      )}
      <image-slot id={id} class="logowrap__slot" shape="rounded" radius={String(radius)} placeholder=""></image-slot>
    </span>
  );
}

Object.assign(window, { LINKS, favicon, useTheme, applyTheme, Backdrop, Header, Footer, Socials, ContactSection, LogoSlot });
