/* Shop — merchandise grid */
const { useState: useShopState, useRef: useShopRef, useEffect: useShopEffect } = React;

/* ============ SHOPIFY (native storefront) ============
   Connect your real store: fill these three from Shopify admin
   (Sales channels → Buy Button, or Headless / Storefront API).
   When set, products + cart load natively on this page. When blank,
   the page falls back to the static grid below so it still looks complete. */
const NG_SHOPIFY = {
  domain: '',                 // e.g. 'naomi-gal.myshopify.com'
  storefrontAccessToken: '',  // Storefront API access token
  collectionId: '',           // a collection ID to display
};
const NG_SHOPIFY_READY = !!(NG_SHOPIFY.domain && NG_SHOPIFY.storefrontAccessToken && NG_SHOPIFY.collectionId);

function ShopifyCollection() {
  const node = useShopRef(null);
  const [status, setStatus] = useShopState('loading'); // loading | ready | error
  useShopEffect(() => {
    let cancelled = false;
    const mount = () => {
      if (cancelled || !node.current || !window.ShopifyBuy || !window.ShopifyBuy.UI) return;
      try {
        const client = window.ShopifyBuy.buildClient({
          domain: NG_SHOPIFY.domain,
          storefrontAccessToken: NG_SHOPIFY.storefrontAccessToken,
        });
        window.ShopifyBuy.UI.onReady(client).then((ui) => {
          if (cancelled || !node.current) return;
          node.current.innerHTML = '';
          ui.createComponent('collection', {
            id: NG_SHOPIFY.collectionId,
            node: node.current,
            moneyFormat: '%24%7B%7Bamount%7D%7D',
            options: {
              product: {
                styles: {
                  product: { 'font-family': 'var(--font-sans)', 'text-align': 'left' },
                  title:   { 'font-weight': '700', color: 'var(--ink)' },
                  price:   { 'font-weight': '700', color: 'var(--ink)' },
                  button:  {
                    'font-family': 'var(--font-sans)', 'font-weight': '700', 'border-radius': '4px',
                    'background-color': '#c8362b', ':hover': { 'background-color': '#a82c23' },
                    ':focus': { 'background-color': '#a82c23' },
                  },
                },
                buttonDestination: 'cart',
                contents: { img: true, title: true, price: true },
                text: { button: 'Add to cart' },
              },
              cart: {
                styles: { button: { 'background-color': '#c8362b', 'border-radius': '4px',
                  ':hover': { 'background-color': '#a82c23' } } },
                text: { total: 'Subtotal', button: 'Checkout' },
              },
              toggle: { styles: { toggle: { 'background-color': '#c8362b',
                ':hover': { 'background-color': '#a82c23' } } } },
            },
          });
          setStatus('ready');
        }).catch(() => { if (!cancelled) setStatus('error'); });
      } catch (e) { if (!cancelled) setStatus('error'); }
    };
    if (window.ShopifyBuy && window.ShopifyBuy.UI) { mount(); }
    else {
      const existing = document.getElementById('shopify-buy-sdk');
      if (existing) { existing.addEventListener('load', mount); existing.addEventListener('error', () => setStatus('error')); }
      else {
        const s = document.createElement('script');
        s.id = 'shopify-buy-sdk'; s.async = true;
        s.src = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
        s.onload = mount; s.onerror = () => setStatus('error');
        document.head.appendChild(s);
      }
    }
    return () => { cancelled = true; };
  }, []);
  return (
    <div>
      <div ref={node} className="ng-shopify"/>
      {status === 'loading' && (
        <p style={{ textAlign:'center', color:'var(--graphite)', fontSize:14, padding:'40px 0' }}>Loading the shop…</p>
      )}
      {status === 'error' && (
        <p style={{ textAlign:'center', color:'var(--marker-red)', fontSize:14, padding:'40px 0' }}>
          Couldn’t reach the store. Check the Shopify domain & token in the code.
        </p>
      )}
    </div>
  );
}

function ProductIcon({ kind }) {
  const stroke = 'var(--ink)';
  const sw = 1.3;
  if (kind === 'keychain') return (
    <svg viewBox="0 0 80 80" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <circle cx="28" cy="40" r="14"/>
      <rect x="42" y="36" width="22" height="8" rx="1.5"/>
      <path d="M22 40h12 M28 34v12"/>
    </svg>);
  if (kind === 'sticker') return (
    <svg viewBox="0 0 80 80" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M16 24 L56 18 L62 58 L20 64 Z"/>
      <path d="M52 18 L60 26 L62 18 Z" fill="var(--ribbon)" stroke="var(--ink)"/>
      <path d="M26 36 h22 M26 44 h28 M26 52 h18"/>
    </svg>);
  if (kind === 'book') return (
    <svg viewBox="0 0 80 80" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <rect x="18" y="14" width="44" height="56" rx="1"/>
      <path d="M18 22h44 M28 36h24 M28 46h18 M28 56h22"/>
    </svg>);
  if (kind === 'shirt') return (
    <svg viewBox="0 0 80 80" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 24 L30 16 L40 22 L50 16 L62 24 L56 32 L50 30 V62 H30 V30 L24 32 Z"/>
    </svg>);
  if (kind === 'sleeve') return (
    <svg viewBox="0 0 80 80" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 22 L58 22 L54 64 L26 64 Z"/>
      <circle cx="40" cy="42" r="9"/>
    </svg>);
  return null;
}

function ProductCard({ p }) {
  const [hover, setHover] = useShopState(false);
  return (
    <article
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{ background:'var(--white)', borderRadius:'var(--radius-lg)', overflow:'hidden',
        boxShadow: hover ? '0 2px 6px rgba(20,17,15,.06),0 16px 38px rgba(20,17,15,.14)' :
                            '0 1px 2px rgba(20,17,15,.05),0 8px 24px rgba(20,17,15,.08)',
        transform: hover ? 'translateY(-3px)' : 'none', transition:'transform .18s ease, box-shadow .18s ease',
        display:'flex', flexDirection:'column' }}>
      <div style={{ aspectRatio:'4/3', background:'var(--paper-2)', display:'flex',
        alignItems:'center', justifyContent:'center', padding:24 }}>
        <ProductIcon kind={p.kind}/>
      </div>
      <div style={{ padding:'14px 16px 18px' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:10 }}>
          <h3 style={{ margin:0, fontSize:16, fontWeight:700, letterSpacing:'-.005em', color:'var(--ink)' }}>{p.name}</h3>
          <span style={{ fontWeight:700, fontSize:16, color:'var(--ink)' }}>{p.price}</span>
        </div>
        <p style={{ margin:'6px 0 14px', fontSize:13, color:'var(--graphite)', lineHeight:1.5 }}>{p.note}</p>
        <Button kind="ink" onClick={()=>window.open(window.NG_SHOP_URL, '_blank', 'noopener')}
          style={{ width:'100%', justifyContent:'center', padding:'10px 14px', fontSize:13 }}>
          Buy on Shopify
        </Button>
      </div>
    </article>
  );
}

function ShopPage({ go }) {
  return (
    <main style={{ background:'var(--paper)' }}>
      <section style={{ padding:'clamp(36px,6vw,56px) var(--pad-x) 28px', borderBottom:'1px solid var(--line)' }}>
        <div style={{ maxWidth:1120, margin:'0 auto', display:'flex', justifyContent:'space-between',
          alignItems:'flex-end', gap:24, flexWrap:'wrap' }}>
          <div>
            <h1 style={{ fontSize:'clamp(32px,5.5vw,54px)', fontWeight:700, letterSpacing:'-.01em', margin:'0 0 8px' }}>
              Stickers, tees, books.<br/>Tiny acts of <span style={{ color:'var(--marker-red)' }}>memory</span>.
            </h1>
          </div>
          <p style={{ fontSize:16, lineHeight:1.55, color:'var(--ink-soft)', maxWidth:360, margin:0 }}>
            Carry a portrait. Start a conversation. Keep a name where people can see it.
          </p>
        </div>
      </section>

      <section style={{ padding:'40px var(--pad-x) clamp(56px,9vw,88px)' }}>
        <div style={{ maxWidth:1120, margin:'0 auto' }}>
          {NG_SHOPIFY_READY ? (
            <ShopifyCollection/>
          ) : (
            <React.Fragment>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(240px,1fr))', gap:20 }}>
                {window.NG_PRODUCTS.map(p => <ProductCard key={p.id} p={p}/>)}
              </div>
              <p style={{ marginTop:22, textAlign:'center', fontSize:12.5, color:'var(--graphite)',
                fontFamily:'var(--font-sans)' }}>
                Connect your Shopify store in the code to sell these natively, with a live cart &amp; checkout.
              </p>
            </React.Fragment>
          )}
        </div>
        <div style={{ maxWidth:760, margin:'56px auto 0', textAlign:'center',
          padding:'28px 24px', background:'var(--ink)', color:'var(--paper)', borderRadius:'var(--radius-lg)' }}>
          <Ribbon size={22} color="var(--ribbon)"/>
          <h3 style={{ fontFamily:'var(--font-display)', textTransform:'uppercase', fontSize:'clamp(26px,5vw,32px)',
            letterSpacing:'-.02em', margin:'10px 0 8px' }}>Want a custom portrait?</h3>
          <p style={{ fontSize:15, lineHeight:1.6, color:'rgba(247,242,233,.78)', margin:'0 0 18px' }}>
            Tell Naomi who to draw. She'll start tonight.
          </p>
          <Button kind="yellow" onClick={()=>go('commission')}>Commission a portrait →</Button>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { ShopPage });
