const K = window.SussexAudioDesignSystem_94213f;

/* Shared responsive hook. Inline styles can't carry media queries, so layouts
   branch on this instead. 760px matches the .sa-tagline breakpoint in the page
   <style> blocks. */
function useIsMobile(bp = 760) {
  const [mobile, setMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth <= bp
  );
  React.useEffect(() => {
    const onResize = () => setMobile(window.innerWidth <= bp);
    onResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [bp]);
  return mobile;
}

/* FastSpring Store Builder Library (popup). The fastspring-builder script with
   data-storefront is loaded per buy-page <head>; it exposes window.fastspring.
   Buy adds FreqKey to the bag popup (Bag, in the nav); Checkout there opens the
   FastSpring payment popup. */
const FASTSPRING_PRODUCT_PATH = 'freqkey';
function fsBuilder() { return (window.fastspring && window.fastspring.builder) || null; }
function fsAddToBag() {
  const b = fsBuilder();
  if (b) { try { b.reset(); b.add(FASTSPRING_PRODUCT_PATH); } catch (e) { /* no-op */ } }
  try { window.dispatchEvent(new CustomEvent('sa-cart-open')); } catch (e) { /* no-op */ }
}
function fsCheckout() {
  const b = fsBuilder();
  if (b) { try { b.checkout(); } catch (e) { /* no-op */ } }
}
/* FastSpring popup-closed callback. FastSpring invokes this by name (wired via
   data-popup-closed on the fastspring-builder script) when the payment popup
   closes. It passes an order reference ONLY when an order actually completed;
   on cancel or dismiss it is called with no argument. We surface the on-page
   confirmation solely in the completed case. */
function onFSPopupClosed(orderReference) {
  if (!orderReference || !orderReference.id) return; // cancelled/dismissed/incomplete — nothing purchased
  try { window.dispatchEvent(new CustomEvent('sa-purchase-complete')); } catch (e) { /* no-op */ }
}

/* Bag icon + dropdown mini-cart. Buy adds FreqKey and opens this; Checkout here
   hands off to the FastSpring payment popup. Cart state is per-page (the SBL
   session persists the item for checkout regardless). */
function Bag() {
  const [open, setOpen] = React.useState(false);
  const [inCart, setInCart] = React.useState(false);
  const [bought, setBought] = React.useState(false);
  React.useEffect(() => {
    const onOpen = () => { setInCart(true); setOpen(true); };
    const onDone = () => { setInCart(false); setOpen(false); setBought(true); };
    const onKey = (e) => { if (e.key === 'Escape') { setOpen(false); setBought(false); } };
    window.addEventListener('sa-cart-open', onOpen);
    window.addEventListener('sa-purchase-complete', onDone);
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('sa-cart-open', onOpen); window.removeEventListener('sa-purchase-complete', onDone); window.removeEventListener('keydown', onKey); };
  }, []);
  const remove = () => { const b = fsBuilder(); if (b) { try { b.reset(); } catch (e) { /* no-op */ } } setInCart(false); };
  const checkout = () => { fsCheckout(); setOpen(false); };
  const count = inCart ? 1 : 0;
  return (
    <div style={{ position: 'relative' }}>
      <button type="button" aria-label="Cart" onClick={() => setOpen((o) => !o)} style={{ position: 'relative', width: 40, height: 40, borderRadius: 'var(--radius-full)', border: '1px solid var(--hairline)', background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', cursor: 'pointer' }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8h12l-1 13H7L6 8z"></path><path d="M9 8V6a3 3 0 0 1 6 0v2"></path></svg>
        {count > 0 && <span style={{ position: 'absolute', top: -5, right: -5, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 9, background: 'var(--accent-magenta, #e6007e)', color: '#fff', font: '600 11px var(--font-sans)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxSizing: 'border-box' }}>{count}</span>}
      </button>
      {open && (
        <React.Fragment>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div role="dialog" aria-label="Shopping bag" style={{ position: 'absolute', top: 'calc(100% + 12px)', right: 0, zIndex: 50, width: 328, maxWidth: '90vw', background: 'var(--white)', border: '1px solid var(--hairline)', borderRadius: 'var(--radius-lg)', boxShadow: '0 14px 40px rgba(33,28,23,.18)', padding: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ font: '400 12px var(--font-mono)', letterSpacing: '0.6px', textTransform: 'uppercase', color: '#8a8a8a' }}>Your bag</span>
              <button type="button" onClick={() => setOpen(false)} aria-label="Close" style={{ background: 'none', border: 'none', cursor: 'pointer', font: '400 20px var(--font-sans)', color: '#8a8a8a', lineHeight: 1, padding: 0 }}>×</button>
            </div>
            {inCart ? (
              <React.Fragment>
                <div style={{ marginTop: 16, display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                  <button type="button" onClick={remove} aria-label="Remove FreqKey" style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#8a8a8a', font: '400 16px var(--font-sans)', lineHeight: 1, padding: 0, marginTop: 3 }}>×</button>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ font: '540 16px var(--font-sans)', letterSpacing: '-0.2px', color: 'var(--ink)' }}>FreqKey — full license</div>
                    <div style={{ marginTop: 3, font: '330 13px/1.4 var(--font-sans)', color: '#777' }}>macOS · AU + VST3 · serial by email · 2 machines</div>
                  </div>
                  <div style={{ textAlign: 'right', flex: 'none' }}>
                    <div style={{ font: '540 16px var(--font-sans)', color: 'var(--ink)' }}>$20</div>
                    <div style={{ font: '400 10px var(--font-mono)', letterSpacing: '0.5px', textTransform: 'uppercase', color: '#8a8a8a', textDecoration: 'line-through' }}>Reg. $50</div>
                  </div>
                </div>
                <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--hairline)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ font: '400 12px var(--font-mono)', letterSpacing: '0.6px', textTransform: 'uppercase', color: '#8a8a8a' }}>Total</span>
                  <span style={{ font: '540 20px var(--font-sans)', color: 'var(--ink)' }}>$20</span>
                </div>
                <button type="button" onClick={checkout} style={{ marginTop: 16, width: '100%', padding: '13px 16px', border: 'none', borderRadius: 'var(--radius-md)', background: 'var(--accent-magenta, #e6007e)', color: '#fff', font: '540 15px var(--font-sans)', cursor: 'pointer' }}>Checkout</button>
                <div style={{ marginTop: 10, textAlign: 'center', font: '400 11px var(--font-mono)', letterSpacing: '0.5px', textTransform: 'uppercase', color: '#a5a5a5' }}>Secure checkout by FastSpring</div>
              </React.Fragment>
            ) : (
              <div style={{ marginTop: 14, font: '330 15px/1.5 var(--font-sans)', color: '#777' }}>Your bag is empty. <a href="freqkey.html" style={{ color: 'var(--ink)', textDecoration: 'underline', textUnderlineOffset: 3 }}>See FreqKey →</a></div>
            )}
          </div>
        </React.Fragment>
      )}
      {bought && (
        <React.Fragment>
          <div onClick={() => setBought(false)} style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'rgba(33,28,23,.45)' }} />
          <div role="dialog" aria-label="Purchase complete" style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 70, width: 400, maxWidth: '90vw', background: 'var(--white)', border: '1px solid var(--hairline)', borderRadius: 'var(--radius-lg)', boxShadow: '0 14px 40px rgba(33,28,23,.18)', padding: 28 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ font: '400 12px var(--font-mono)', letterSpacing: '0.6px', textTransform: 'uppercase', color: '#8a8a8a' }}>Order complete</span>
              <button type="button" onClick={() => setBought(false)} aria-label="Close" style={{ background: 'none', border: 'none', cursor: 'pointer', font: '400 20px var(--font-sans)', color: '#8a8a8a', lineHeight: 1, padding: 0 }}>×</button>
            </div>
            <div style={{ marginTop: 14, font: '540 22px var(--font-sans)', letterSpacing: '-0.2px', color: 'var(--ink)' }}>Thanks for purchasing FreqKey!</div>
            <div style={{ marginTop: 12, font: '330 16px/1.55 var(--font-sans)', color: '#555' }}>
              Check your email for your serial number, and <a href="downloads.html" style={{ color: 'var(--accent-magenta, #e6007e)', textDecoration: 'underline', textUnderlineOffset: 3 }}>download FreqKey here</a>.
            </div>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

function SiteNav({ active }) {
  const links = [['Plug-ins', 'freqkey.html'], ['Downloads', 'downloads.html'], ['Support', 'support.html']];
  const isMobile = useIsMobile();
  if (isMobile) {
    return (
      <nav className="sa-no-fade" style={{ position: 'sticky', top: 0, zIndex: 20, background: '#faf7f1', borderBottom: '1px solid rgba(33,28,23,.10)' }}>
        <div style={{ padding: '12px 18px 10px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <a href="index.html" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', minWidth: 0 }}>
              <img src="assets/sussex-logo.png" alt="Sussex Audio" style={{ height: 46, display: 'block', maxWidth: '62vw', objectFit: 'contain' }} />
            </a>
            <div style={{ flex: 'none' }}><Bag /></div>
          </div>
          <ul style={{ display: 'flex', gap: 4, listStyle: 'none', margin: 0, padding: 0, alignItems: 'center', flexWrap: 'wrap' }}>
            {links.map(([l, href]) => (
              <li key={l}><a href={href} style={{ font: '300 17px Oswald, var(--font-sans)', letterSpacing: '0.02em', color: 'var(--ink)', textDecoration: active === l ? 'underline' : 'none', textUnderlineOffset: 5, lineHeight: 1, padding: '4px 18px 4px 0', display: 'block' }}>{l}</a></li>
            ))}
          </ul>
        </div>
      </nav>
    );
  }
  return (
    <nav className="sa-no-fade" style={{ position: 'sticky', top: 0, zIndex: 20, background: '#faf7f1', borderBottom: '1px solid rgba(33,28,23,.10)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', height: 110, display: 'flex', alignItems: 'flex-end', paddingBottom: 0, gap: 28, padding: '0 32px' }}>
        <a href="index.html" style={{ display: 'flex', alignItems: 'flex-end', gap: 16, textDecoration: 'none', flex: 1, minWidth: 0, paddingBottom: 14 }}>
          <img src="assets/sussex-logo.png" alt="Sussex Audio" style={{ height: 78, display: 'block' }} />
          <span className="sa-tagline" style={{ font: '300 16px Oswald, var(--font-sans)', letterSpacing: '0.03em', textTransform: 'lowercase', color: '#7a7064', whiteSpace: 'nowrap', lineHeight: 1, paddingBottom: 15 }}>( audio tools for humans )</span>
        </a>
        <ul style={{ display: 'flex', gap: 8, listStyle: 'none', margin: 0, padding: '0 0 14px', alignItems: 'flex-end' }}>
          {links.map(([l, href]) => (
            <li key={l}><a href={href} style={{ font: '300 20px Oswald, var(--font-sans)', letterSpacing: '0.02em', color: 'var(--ink)', textDecoration: active === l ? 'underline' : 'none', textUnderlineOffset: 6, lineHeight: 1, padding: '0 12px 14px', display: 'block' }}>{l}</a></li>
          ))}
        </ul>
        <div style={{ paddingBottom: 7, marginBottom: 11 }}><Bag /></div>
      </div>
    </nav>
  );
}

/* Kit (ConvertKit) newsletter signup — posts to the hosted form endpoint.
   no-cors keeps the visitor on the page; Kit sends the double opt-in email. */
const KIT_FORM_ACTION = 'https://app.kit.com/forms/9547787/subscriptions';

function FooterSignup() {
  const [status, setStatus] = React.useState('idle'); // idle | sending | ok | err
  const onSubmit = (e) => {
    e.preventDefault();
    const email = (e.target.email_address.value || '').trim();
    if (!email) return;
    setStatus('sending');
    fetch(KIT_FORM_ACTION, {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ email_address: email }).toString(),
    }).then(() => setStatus('ok')).catch(() => setStatus('err'));
  };
  const inputStyle = { flex: '1 1 auto', minWidth: 0, padding: '12px 14px', font: '400 15px var(--font-sans)', color: 'var(--ink)', background: 'var(--white)', border: '1px solid rgba(33,28,23,.20)', borderRadius: 'var(--radius-md)', outline: 'none' };
  const btnStyle = { flex: 'none', padding: '12px 22px', font: '500 15px var(--font-sans)', color: 'var(--white)', background: 'var(--ink)', border: 'none', borderRadius: 'var(--radius-md)', cursor: 'pointer', whiteSpace: 'nowrap' };
  return (
    <div style={{ maxWidth: 1280, margin: '0 auto 40px', paddingBottom: 40, borderBottom: '1px solid rgba(33,28,23,.10)', display: 'flex', flexWrap: 'wrap', gap: '20px 48px', justifyContent: 'space-between', alignItems: 'center' }}>
      <div style={{ maxWidth: 460 }}>
        <div style={{ font: '500 22px Oswald, var(--font-sans)', letterSpacing: '0.01em', color: 'var(--ink)' }}>Stay updated</div>
        <div style={{ marginTop: 6, font: '330 15px/1.5 var(--font-sans)', letterSpacing: '-0.1px', color: '#7a7064' }}>Windows and AAX capabilities plus future versions.<br />Unsubscribe anytime.</div>
      </div>
      {status === 'ok' ? (
        <div style={{ flex: '1 1 300px', maxWidth: 460, font: '400 15px/1.5 var(--font-sans)', letterSpacing: '-0.1px', color: 'var(--ink)' }}>Thanks — check your email to confirm your subscription.</div>
      ) : (
        <form onSubmit={onSubmit} noValidate style={{ flex: '1 1 300px', maxWidth: 460, minWidth: 240 }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <input name="email_address" type="email" required placeholder="you@studio.com" aria-label="Email address" style={inputStyle} />
            <button type="submit" disabled={status === 'sending'} style={btnStyle}>{status === 'sending' ? 'Subscribing…' : 'Subscribe'}</button>
          </div>
          {status === 'err' && <div style={{ marginTop: 8, font: '400 13px var(--font-sans)', color: '#c7383d' }}>Something went wrong — email hello@sussex-audio.com and we'll add you.</div>}
        </form>
      )}
    </div>
  );
}

function SiteFooter() {
  const links = [['FreqKey', 'freqkey.html'], ['Downloads', 'downloads.html'], ['Support', 'support.html'], ['EULA', 'eula.html'], ['Privacy', 'privacy.html']];
  const socials = [['Instagram', 'https://www.instagram.com/sussex.audio/'], ['TikTok', 'https://www.tiktok.com/@sussex.audio']];
  return (
    <footer style={{ background: '#faf7f1', borderTop: '1px solid rgba(33,28,23,.10)', padding: '56px 32px 36px' }}>
      <FooterSignup />
      <div style={{ maxWidth: 1280, margin: '0 auto', display: 'flex', flexWrap: 'wrap', gap: 40, justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <img src="assets/sussex-logo.png" alt="Sussex Audio" style={{ height: 56, display: 'block' }} />
          <span style={{ font: '300 15px Oswald, var(--font-sans)', letterSpacing: '0.03em', textTransform: 'lowercase', color: '#7a7064' }}>( audio tools for humans )</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {links.map(([l, href]) => <a key={l} href={href} style={{ font: '330 16px var(--font-sans)', color: 'var(--ink)', textDecoration: 'none' }}>{l}</a>)}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <span style={{ font: '500 15px Oswald, var(--font-sans)', letterSpacing: '0.03em', color: '#4b4848' }}>Follow</span>
          {socials.map(([l, href]) => <a key={l} href={href} target="_blank" rel="noopener noreferrer" style={{ font: '330 16px var(--font-sans)', color: 'var(--ink)', textDecoration: 'none' }}>{l}</a>)}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <span style={{ font: '500 15px Oswald, var(--font-sans)', letterSpacing: '0.03em', color: '#4b4848' }}>Get in touch</span>
          <a href="mailto:hello@sussex-audio.com" style={{ font: '330 16px var(--font-sans)', color: 'var(--ink)', textDecoration: 'none' }}>hello@sussex-audio.com</a>
        </div>
      </div>
      <div style={{ maxWidth: 1280, margin: '40px auto 0', paddingTop: 18, borderTop: '1px solid rgba(33,28,23,.10)', font: '300 14px Oswald, var(--font-sans)', letterSpacing: '0.02em', color: '#7a7064' }}>
        © 2026 Sussex Audio (a division of Sussex Recordings)
      </div>
    </footer>
  );
}

/* Shared section shell: white canvas, 1280 column */
function Shell({ children, style }) {
  return <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 32px', ...style }}>{children}</div>;
}

Object.assign(window, { K, SiteNav, SiteFooter, Shell, fsCheckout, fsAddToBag, onFSPopupClosed, useIsMobile });
