// Shared header, footer, marquee, gorilla-mark SVG

const useIsMobile = (bp = 768) => {
  const [mob, setMob] = React.useState(window.innerWidth < bp);
  React.useEffect(() => {
    const fn = () => setMob(window.innerWidth < bp);
    window.addEventListener('resize', fn, { passive: true });
    return () => window.removeEventListener('resize', fn);
  }, [bp]);
  return mob;
};

const Mark = ({ size = 44 }) => (
  <div data-comment-anchor="brand-mark" style={{display:'inline-flex',alignItems:'center',gap:10}}>
    <img src="assets/mascot.jpeg" alt="" style={{width:size,height:size,objectFit:'cover',objectPosition:'center',borderRadius:'50%',border:`3px solid var(--ink)`,background:'#fff'}}/>
    <div style={{display:'flex',flexDirection:'column',lineHeight:0.9}}>
      <span className="display" style={{fontSize:size*0.42,color:'var(--ink)',letterSpacing:'-0.02em'}}>KING KONG</span>
      <span className="display" style={{fontSize:size*0.42,color:'var(--orange)',letterSpacing:'-0.02em',WebkitTextStroke:'1px var(--ink)'}}>STICKERS</span>
    </div>
  </div>
);

const TopBar = () => (
  <div style={{background:'var(--ink)',color:'#fff',fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase'}}>
    <div className="wrap" style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 28px',gap:24}}>
      <div style={{overflow:'hidden',flex:1}}>
        <div className="marquee-track">
          {[...Array(2)].map((_,i)=>(
            <div key={i} style={{display:'flex',gap:48,flexShrink:0}}>
              <span>★ Free shipping on orders over $25</span>
              <span>🇦🇺 Printed in Sydney, Australia</span>
              <span>⚡ Free proof</span>
              <span>♻️ Waterproof + weather resistant</span>
              <span>★ Trusted by Aussie creators & brands</span>
              <span>🚚 Same-day dispatch on weekdays</span>
            </div>
          ))}
        </div>
      </div>
      <div style={{display:'flex',gap:16,flexShrink:0,opacity:0.8}}>
        <button onClick={()=>{window.location.hash='help-center'}} style={{background:'none',border:'none',color:'#fff',cursor:'pointer',fontFamily:'inherit',fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',padding:0}}>Help</button>
        <button onClick={()=>{window.location.hash='order-tracking'}} style={{background:'none',border:'none',color:'#fff',cursor:'pointer',fontFamily:'inherit',fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',padding:0}}>Track order</button>
        <span>AUD $</span>
      </div>
    </div>
  </div>
);

const navLinks = [
  { label:'Shop',        page:'shop' },
  { label:'Die-Cut',     page:'die-cut' },
  { label:'Sheets',      page:'sheets' },
  { label:'Holographic', page:'holo' },
  { label:'Glitter',     page:'glitter' },
  { label:'Mural',       page:'mural' },
  { label:'Bulk',        page:'bulk' },
  { label:'Sample Pack', page:'sample' },
];

const Header = ({ go, cart: _cartProp = 0 }) => {
  const m = useIsMobile();
  const [open, setOpen] = React.useState(false);
  const [cart, setCart] = React.useState(_cartProp);
  React.useEffect(() => {
    fetch('/wp-json/wc/store/v1/cart', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d) setCart(d.items_count || 0); })
      .catch(() => {});
  }, []);

  const [q, setQ] = React.useState('');
  const runSearch = (val) => {
    const s = (val || '').toLowerCase().trim();
    if (!s) return;
    const map = [
      [['holo','holographic'],'holo'],
      [['glitter'],'glitter'],
      [['clear','transparent'],'clear'],
      [['kiss'],'kiss-cut'],
      [['sheet'],'sheets'],
      [['bulk','wholesale','bundle'],'bulk'],
      [['mural','wall','wallpaper'],'mural'],
      [['sample'],'sample'],
    ];
    for (const [keys, page] of map) { if (keys.some(k => s.includes(k))) { go(page); return; } }
    go('shop');
  };

  if (m) return (
    <header style={{position:'sticky',top:0,zIndex:50,background:'#fff',borderBottom:'3px solid var(--ink)'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'12px 20px'}}>
        <button onClick={()=>go('home')} style={{display:'flex'}}><Mark size={36}/></button>
        <div style={{display:'flex',gap:8,alignItems:'center'}}>
          <button onClick={()=>window.location.href='/cart/'} className="pill" style={{display:'flex',alignItems:'center',gap:6,background:'var(--yellow)'}}>
            <Icon.Bag size={16}/>
            <span style={{background:'var(--ink)',color:'#fff',borderRadius:999,padding:'1px 7px',fontSize:11,fontWeight:800}}>{cart}</span>
          </button>
          <button onClick={()=>setOpen(o=>!o)} style={{width:44,height:44,display:'grid',placeItems:'center',border:'2.5px solid var(--ink)',borderRadius:10,background:open?'var(--ink)':'#fff',color:open?'#fff':'var(--ink)'}}>
            <Icon.Menu size={20}/>
          </button>
        </div>
      </div>

      {open && (
        <div style={{position:'fixed',inset:0,zIndex:200,background:'var(--cream)',display:'flex',flexDirection:'column',overflowY:'auto'}}>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'16px 20px',borderBottom:'3px solid var(--ink)',background:'#fff',position:'sticky',top:0}}>
            <Mark size={36}/>
            <button onClick={()=>setOpen(false)} style={{width:44,height:44,display:'grid',placeItems:'center',border:'2.5px solid var(--ink)',borderRadius:10,background:'var(--ink)',color:'#fff',fontSize:24,lineHeight:1}}>✕</button>
          </div>
          <div style={{padding:'16px 20px 0'}}>
            <div style={{display:'flex',alignItems:'center',gap:8,border:'2.5px solid var(--ink)',borderRadius:12,padding:'10px 12px',background:'#fff'}}>
              <Icon.Search size={18}/>
              <input placeholder="Search stickers…" value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter'){ runSearch(q); setOpen(false); } }} style={{border:'none',background:'transparent',outline:'none',width:'100%',fontFamily:'inherit',fontSize:16}}/>
            </div>
          </div>
          <nav style={{flex:1,display:'flex',flexDirection:'column',padding:'20px',gap:10}}>
            {navLinks.map(l=>(
              <button key={l.label} onClick={()=>{go(l.page);setOpen(false)}}
                style={{padding:'18px 20px',fontWeight:800,fontSize:20,textTransform:'uppercase',letterSpacing:'0.04em',borderRadius:14,textAlign:'left',background: l.label==='Sample Pack' ? 'var(--yellow)' : '#fff',border:'2.5px solid var(--ink)',boxShadow:'4px 4px 0 var(--ink)',display:'flex',justifyContent:'space-between',alignItems:'center',cursor:'pointer',color:'var(--ink)'}}>
                {l.label}
                <Icon.Arrow/>
              </button>
            ))}
          </nav>
          <div style={{padding:'20px',borderTop:'3px solid var(--ink)'}}>
            <button className="btn primary" style={{width:'100%',justifyContent:'center',fontSize:17,padding:'18px 20px'}} onClick={()=>{go('die-cut');setOpen(false)}}>Start designing <Icon.Arrow/></button>
          </div>
        </div>
      )}
    </header>
  );

  return (
    <header style={{position:'sticky',top:0,zIndex:50,background:'#fff',borderBottom:'3px solid var(--ink)'}}>
      <TopBar/>
      <div className="wrap" style={{display:'flex',alignItems:'center',gap:24,padding:'16px 28px'}}>
        <button onClick={()=>go('home')} aria-label="King Kong Stickers home" style={{display:'flex'}}>
          <Mark size={44}/>
        </button>
        <nav style={{display:'flex',gap:4,marginLeft:18,flex:1}}>
          {navLinks.map(l => (
            <button key={l.label} onClick={()=>go(l.page)}
              style={{padding:'10px 14px',fontWeight:800,fontSize:14,textTransform:'uppercase',letterSpacing:'0.04em',borderRadius:10,whiteSpace:'nowrap',background: l.label==='Sample Pack' ? 'var(--yellow)' : 'transparent', border: l.label==='Sample Pack' ? '2px solid var(--ink)' : 'none',cursor:'pointer',color:'var(--ink)'}}
              onMouseOver={e=>e.currentTarget.style.background='var(--cream-deep)'}
              onMouseOut={e=>e.currentTarget.style.background= l.label==='Sample Pack' ? 'var(--yellow)' : 'transparent'}
            >{l.label}</button>
          ))}
        </nav>
        <div style={{display:'flex',alignItems:'center',gap:8,flex:'0 0 320px',border:'2.5px solid var(--ink)',borderRadius:12,padding:'8px 12px',background:'var(--cream)'}}>
          <Icon.Search size={18}/>
          <input placeholder="Search die-cut, holo, sample packs…" value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') runSearch(q); }} style={{border:'none',background:'transparent',outline:'none',width:'100%',fontFamily:'inherit',fontSize:14}}/>
          <button onClick={()=>runSearch(q)} aria-label="Search" className="mono" style={{fontSize:11,padding:'2px 7px',border:'1.5px solid var(--ink)',borderRadius:6,background:'#fff',cursor:'pointer'}}>↵</button>
        </div>
        <div style={{display:'flex',alignItems:'center',gap:6}}>
          <button onClick={()=>window.location.href='/my-account/'} className="pill" style={{display:'flex',alignItems:'center',gap:6}}><Icon.User size={16}/>Account</button>
          <button onClick={()=>window.location.href='/cart/'} className="pill" style={{display:'flex',alignItems:'center',gap:6,background:'var(--yellow)'}}>
            <Icon.Bag size={16}/>Cart
            <span style={{background:'var(--ink)',color:'#fff',borderRadius:999,padding:'1px 7px',fontSize:11,fontWeight:800}}>{cart}</span>
          </button>
        </div>
      </div>
    </header>
  );
};

const footerCols = [
  { h:'Shop', l:[
    {label:'Die-cut stickers',  page:'die-cut'},
    {label:'Sticker sheets',    page:'sheets'},
    {label:'Holographic',       page:'holo'},
    {label:'Glitter',           page:'glitter'},
    {label:'Clear vinyl',       page:'clear'},
    {label:'Kiss-cut',          page:'kiss-cut'},
    {label:'Bulk + wholesale',  page:'bulk'},
    {label:'Sample pack',       page:'sample'},
  ]},
  { h:'Resources', l:[
    {label:'Artwork guidelines', page:'artwork-guidelines'},{label:'Templates', page:'templates'},
    {label:'Materials', page:'materials-guide'},{label:'Sizing guide', page:'sizing-guide'},
    {label:'Sustainability', page:'sustainability'},{label:'Blog', page:'blog'},
  ]},
  { h:'Support', l:[
    {label:'Contact', page:'contact'},{label:'Help center', page:'help-center'},
    {label:'Order tracking', page:'order-tracking'},{label:'Returns', page:'returns'},
    {label:'Shipping', page:'shipping'},
    {label:'Application guide', page:'install-guide'},
  ]},
];

const Footer = ({ go }) => {
  const m = useIsMobile();
  const [subEmail, setSubEmail] = React.useState('');
  const [subState, setSubState] = React.useState('idle'); // idle | loading | done | error

  const handleSubscribe = async (e) => {
    e.preventDefault();
    if (!subEmail || subState === 'loading' || subState === 'done') return;
    setSubState('loading');
    try {
      const res = await fetch('/wp-json/kk/v1/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: subEmail }),
      });
      setSubState(res.ok ? 'done' : 'error');
    } catch {
      setSubState('error');
    }
  };

  const NewsletterForm = () => subState === 'done' ? (
    <div style={{padding:'14px 16px',background:'var(--green)',borderRadius:10,fontSize:14,fontWeight:700,color:'#fff'}}>
      You're in! Check your inbox for your 10% code.
    </div>
  ) : (
    <form onSubmit={handleSubscribe} style={{display:'flex',gap:8}}>
      <input
        type="email" required placeholder="you@banana.com"
        value={subEmail} onChange={e=>setSubEmail(e.target.value)}
        style={{flex:1,padding:'12px 14px',borderRadius:10,border:`2px solid ${subState==='error'?'#FF4444':'#fff'}`,background:'transparent',color:'#fff',fontFamily:'inherit',fontSize:14}}
      />
      <button type="submit" className="btn" style={{padding:'10px 16px',opacity:subState==='loading'?0.6:1}}>
        {subState==='loading' ? '…' : 'Go'}
      </button>
    </form>
  );

  return (
    <footer style={{background:'var(--ink)',color:'#fff',marginTop:80,position:'relative',overflow:'hidden'}}>
      <div style={{position:'absolute',inset:'auto 0 -30px 0',textAlign:'center',opacity:0.06,pointerEvents:'none'}}>
        <div className="display" style={{fontSize:'clamp(140px,22vw,360px)',lineHeight:0.85}}>KING KONG</div>
      </div>
      <div className="wrap" style={{padding: m ? '48px 20px 104px' : '64px 28px 32px',position:'relative'}}>

        {m ? (
          /* ── Mobile footer layout ── */
          <div style={{display:'flex',flexDirection:'column',gap:36}}>
            {/* brand */}
            <div>
              <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:14}}>
                <img src="assets/mascot.jpeg" style={{width:48,height:48,borderRadius:'50%',border:'3px solid #fff'}}/>
                <div className="display" style={{fontSize:20,color:'#fff'}}>KING KONG<br/><span style={{color:'var(--orange)'}}>STICKERS</span></div>
              </div>
              <p style={{opacity:0.7,fontSize:14,lineHeight:1.6,margin:0}}>The loudest sticker printer in Australia. Printed and shipped from Sydney.</p>
              <p style={{opacity:0.55,fontSize:12,lineHeight:1.5,marginTop:6}}>18 Punch St, Artarmon NSW</p>
              <p style={{fontSize:13,marginTop:8}}><a href="mailto:hello@kingkongstickers.com.au" style={{color:'#fff',opacity:0.85}}>hello@kingkongstickers.com.au</a></p>
              <div style={{display:'flex',gap:10,marginTop:16}}>
                {[{s:'IG',url:'https://www.instagram.com/kingkongstickers'},{s:'FB',url:'https://www.facebook.com/kingkongstickers'}].map(({s,url})=>(
                  <a key={s} href={url} target="_blank" rel="noopener noreferrer" style={{width:36,height:36,display:'grid',placeItems:'center',borderRadius:10,border:'2px solid #fff',fontWeight:800,fontSize:11,color:'#fff'}}>{s}</a>
                ))}
              </div>
            </div>
            {/* link columns — 2-col grid */}
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:28}}>
              {footerCols.map(c=>(
                <div key={c.h}>
                  <div className="display" style={{fontSize:15,color:'var(--yellow)',marginBottom:10}}>{c.h}</div>
                  <ul style={{listStyle:'none',padding:0,margin:0,display:'flex',flexDirection:'column',gap:8}}>
                    {c.l.map(i=>(
                      <li key={i.label}>
                        {i.page && go
                          ? <button onClick={()=>go(i.page)} style={{fontSize:13,opacity:0.8,background:'none',border:'none',color:'#fff',padding:0,cursor:'pointer',textAlign:'left'}}>{i.label}</button>
                          : <span style={{fontSize:13,opacity:0.8}}>{i.label}</span>
                        }
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
            {/* newsletter */}
            <div>
              <div className="display" style={{fontSize:18,color:'var(--yellow)',marginBottom:10}}>Get 10% off</div>
              <p style={{fontSize:13,opacity:0.8,marginBottom:12}}>Pop your email in for a one-off code + a free random sticker with your first order.</p>
              <NewsletterForm/>
            </div>
          </div>
        ) : (
          /* ── Desktop footer layout ── */
          <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr 1fr 1fr 1.2fr',gap:40}}>
            <div>
              <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:18}}>
                <img src="assets/mascot.jpeg" style={{width:54,height:54,borderRadius:'50%',border:'3px solid #fff'}}/>
                <div className="display" style={{fontSize:22,color:'#fff'}}>KING KONG<br/><span style={{color:'var(--orange)'}}>STICKERS</span></div>
              </div>
              <p style={{opacity:0.7,fontSize:14,lineHeight:1.6,maxWidth:300}}>The loudest sticker printer in Australia. Premium die-cut vinyl, holo, glitter & sheets — printed and shipped from Sydney.</p>
              <p style={{opacity:0.55,fontSize:12,lineHeight:1.5,maxWidth:300,marginTop:8}}>18 Punch St, Artarmon NSW</p>
              <p style={{fontSize:13,marginTop:8}}><a href="mailto:hello@kingkongstickers.com.au" style={{color:'#fff',opacity:0.85}}>hello@kingkongstickers.com.au</a></p>
              <div style={{display:'flex',gap:10,marginTop:20}}>
                {[{s:'IG',url:'https://www.instagram.com/kingkongstickers'},{s:'FB',url:'https://www.facebook.com/kingkongstickers'}].map(({s,url})=>(
                  <a key={s} href={url} target="_blank" rel="noopener noreferrer" style={{width:38,height:38,display:'grid',placeItems:'center',borderRadius:10,border:'2px solid #fff',fontWeight:800,fontSize:12,color:'#fff'}}>{s}</a>
                ))}
              </div>
            </div>
            {footerCols.map(c=>(
              <div key={c.h}>
                <div className="display" style={{fontSize:18,color:'var(--yellow)',marginBottom:14}}>{c.h}</div>
                <ul style={{listStyle:'none',padding:0,margin:0,display:'flex',flexDirection:'column',gap:8}}>
                  {c.l.map(i=>(
                    <li key={i.label}>
                      {i.page && go
                        ? <button onClick={()=>go(i.page)} style={{fontSize:14,opacity:0.85,background:'none',border:'none',color:'#fff',padding:0,cursor:'pointer',textAlign:'left'}}
                            onMouseOver={e=>e.currentTarget.style.opacity='1'} onMouseOut={e=>e.currentTarget.style.opacity='0.85'}>{i.label}</button>
                        : <span style={{fontSize:14,opacity:0.85}}>{i.label}</span>
                      }
                    </li>
                  ))}
                </ul>
              </div>
            ))}
            <div>
              <div className="display" style={{fontSize:18,color:'var(--yellow)',marginBottom:14}}>Get 10% off</div>
              <p style={{fontSize:13,opacity:0.8,marginBottom:14}}>Pop your email in. We'll send a one-off code + a free random sticker with your first order.</p>
              <NewsletterForm/>
            </div>
          </div>
        )}

        <div style={{marginTop:40,paddingTop:20,borderTop:'2px solid rgba(255,255,255,0.15)',display:'flex',justifyContent:'space-between',flexWrap:'wrap',gap:10,fontSize:12,opacity:0.6}}>
          <div>© 2026 King Kong Stickers Pty Ltd</div>
          <div style={{display:'flex',gap:18}}>
            <a href="/privacy-policy/" style={{color:'inherit',cursor:'pointer'}}>Privacy</a>
            <a href="/terms-conditions/" style={{color:'inherit',cursor:'pointer'}}>Terms</a>
            <a href="/cookie-policy/" style={{color:'inherit',cursor:'pointer'}}>Cookies</a>
          </div>
        </div>
      </div>
    </footer>
  );
};

const TrustStrip = () => {
  const m = useIsMobile();
  return (
    <section style={{background:'var(--ink)',color:'#fff',borderTop:'3px solid var(--ink)',borderBottom:'3px solid var(--ink)'}}>
      <div className="wrap" style={{display:'grid',gridTemplateColumns: m ? 'repeat(2,1fr)' : 'repeat(4,1fr)',padding: m ? '18px 20px' : '22px 28px',gap: m ? 14 : 24}}>
        {[
          { i:<Icon.Aus/>, h:'Aussie Made', s:'Printed + shipped from Sydney' },
          { i:<Icon.Truck/>, h:'Free shipping $25+', s:'Same-day dispatch weekdays' },
          { i:<Icon.Sparkle/>, h:'Free proof', s:'Real designers, not bots' },
          { i:<Icon.Star fill="currentColor"/>, h:'Aussie customer love', s:'Honest reviews from real buyers' },
        ].map((t,i)=>(
          <div key={i} style={{display:'flex',alignItems:'center',gap:10}}>
            <div style={{width:40,height:40,display:'grid',placeItems:'center',background:'var(--orange)',border:'2px solid var(--yellow)',borderRadius:12,color:'#fff',flexShrink:0}}>{t.i}</div>
            <div>
              <div className="display" style={{fontSize: m ? 13 : 15,color:'#fff',lineHeight:1.1}}>{t.h}</div>
              <div style={{fontSize:11,opacity:0.7}}>{t.s}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

// ── SEO hook — updates <title>, meta description, OG tags & JSON-LD per page ──
const useSEO = ({ title, description, schema } = {}) => {
  React.useEffect(() => {
    const KK = ' | King Kong Stickers Australia';
    const prevTitle = document.title;
    const prevDesc  = document.querySelector('meta[name="description"]')?.content || '';

    if (title) {
      document.title = title + KK;
      const og = document.querySelector('meta[property="og:title"]');
      if (og) og.content = title + KK;
    }
    if (description) {
      const d = document.querySelector('meta[name="description"]');
      if (d) d.content = description;
      const ogd = document.querySelector('meta[property="og:description"]');
      if (ogd) ogd.content = description;
    }

    let schemaEl = document.getElementById('kk-page-schema');
    if (schema) {
      if (!schemaEl) {
        schemaEl = document.createElement('script');
        schemaEl.id = 'kk-page-schema';
        schemaEl.type = 'application/ld+json';
        document.head.appendChild(schemaEl);
      }
      // Accept single schema object or array of schemas
      schemaEl.textContent = JSON.stringify(Array.isArray(schema) ? schema : schema);
    }

    return () => {
      document.title = prevTitle;
      const d = document.querySelector('meta[name="description"]');
      if (d) d.content = prevDesc;
      if (schemaEl) schemaEl.remove();
    };
  }, [title, description]);
};

window.useIsMobile = useIsMobile;
window.useSEO = useSEO;
window.Mark = Mark;
window.Header = Header;
window.Footer = Footer;
window.TrustStrip = TrustStrip;
