// Shop screens — product grid, product detail, WhatsApp sheet.

const { useState: useS_sh } = React;

function ProductCard({ product, layout = 'grid2', onClick, showEditHandles, onEdit, onCta }) {
  const [pressed, setPressed] = useS_sh(false);
  const out = product.stock === 0;

  const handleCta = (e) => {
    e.stopPropagation();
    onCta?.(product);
  };

  const pointerProps = {
    onPointerDown: () => setPressed(true),
    onPointerUp:   () => setPressed(false),
    onPointerLeave:() => setPressed(false),
  };

  if (layout === 'list') {
    return (
      <div
        onClick={onClick}
        {...pointerProps}
        style={{
          background:'#fff', borderRadius:18, padding:10, display:'flex', gap:12,
          boxShadow: HUUL_TOKENS.shadow.card,
          transform: pressed ? 'scale(0.985)' : 'scale(1)',
          transition:'transform 140ms', cursor:'pointer', position:'relative',
        }}>
        <img src={product.image} alt="" style={{
          width:96, height:96, borderRadius:12, objectFit:'cover', flexShrink:0,
          opacity: out ? 0.5 : 1,
        }}/>
        <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', justifyContent:'space-between', padding:'4px 0' }}>
          <div>
            <div style={{ fontSize:15, fontWeight:600, letterSpacing:-0.2, lineHeight:1.25 }}>{product.name}</div>
            <div style={{ fontSize:12.5, color:HUUL_TOKENS.color.ink3, marginTop:4, lineHeight:1.4,
              display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden',
            }}>{product.desc}</div>
          </div>
          <div style={{ fontSize:15, fontWeight:600, marginTop:2 }}>{product.priceLabel}</div>
          <button onClick={out ? undefined : handleCta} disabled={out} style={{
            marginTop:8, width:'100%', height:38, border:'none', borderRadius:10,
            background: out ? 'rgba(0,0,0,0.07)' : HUUL_TOKENS.color.wa,
            color: out ? HUUL_TOKENS.color.ink4 : '#fff',
            fontSize:13.5, fontWeight:600, cursor: out ? 'not-allowed' : 'pointer',
            fontFamily: HUUL_TOKENS.font.stack,
            display:'flex', alignItems:'center', justifyContent:'center', gap:6,
          }}>
            {out ? 'Out of stock' : <><IconWhatsApp size={15}/> Contact</>}
          </button>
        </div>
        {showEditHandles && (
          <IconButton icon={<IconEdit size={14}/>} onClick={(e)=>{e.stopPropagation(); onEdit?.(product)}}
            size={28} style={{position:'absolute', top:8, right:8}} bg="rgba(255,255,255,0.95)"/>
        )}
      </div>
    );
  }

  if (layout === 'immersive') {
    return (
      <div
        onClick={onClick}
        {...pointerProps}
        style={{
          position:'relative', borderRadius:22, overflow:'hidden',
          aspectRatio:'1', cursor:'pointer',
          transform: pressed ? 'scale(0.985)' : 'scale(1)',
          transition:'transform 140ms',
          boxShadow: HUUL_TOKENS.shadow.card,
        }}>
        <img src={product.image} alt="" style={{ width:'100%', height:'100%', objectFit:'cover', opacity: out ? 0.5 : 1 }}/>
        <div style={{
          position:'absolute', left:0, right:0, bottom:0,
          padding:'36px 12px 12px',
          background:'linear-gradient(to top, rgba(0,0,0,0.6), transparent)',
          color:'#fff',
        }}>
          <div style={{ fontSize:14, fontWeight:600, letterSpacing:-0.2, lineHeight:1.2,
            display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden',
            textShadow:'0 1px 2px rgba(0,0,0,0.25)',
          }}>{product.name}</div>
          <div style={{ fontSize:13, fontWeight:500, opacity:0.95, marginTop:3 }}>{product.priceLabel}</div>
          {!out && (
            <button onClick={handleCta} style={{
              marginTop:8, width:'100%', height:36, border:'none', borderRadius:10,
              background: HUUL_TOKENS.color.wa, color:'#fff',
              fontSize:13, fontWeight:600, cursor:'pointer',
              fontFamily: HUUL_TOKENS.font.stack,
              display:'flex', alignItems:'center', justifyContent:'center', gap:6,
            }}><IconWhatsApp size={15}/> Contact</button>
          )}
        </div>
        {showEditHandles && (
          <IconButton icon={<IconEdit size={14}/>} onClick={(e)=>{e.stopPropagation(); onEdit?.(product)}}
            size={28} style={{position:'absolute', top:8, right:8}} bg="rgba(255,255,255,0.95)"/>
        )}
      </div>
    );
  }

  // grid2
  return (
    <div
      onClick={onClick}
      {...pointerProps}
      style={{
        background:'#fff', borderRadius:20, overflow:'hidden',
        boxShadow: HUUL_TOKENS.shadow.card,
        transform: pressed ? 'scale(0.985)' : 'scale(1)',
        transition:'transform 140ms', cursor:'pointer', position:'relative',
        display:'flex', flexDirection:'column',
      }}>
      <div style={{ position:'relative', aspectRatio:'1', background:'#F5F5F7' }}>
        <img src={product.image} alt="" style={{
          width:'100%', height:'100%', objectFit:'cover',
          opacity: out ? 0.4 : 1,
        }}/>
        {out && (
          <div style={{
            position:'absolute', top:10, left:10,
            background:'rgba(30,30,32,0.9)', color:'#fff',
            fontSize:11, fontWeight:600, padding:'4px 9px', borderRadius:99,
          }}>Out</div>
        )}
        {showEditHandles && (
          <IconButton icon={<IconEdit size={14}/>} onClick={(e)=>{e.stopPropagation(); onEdit?.(product)}}
            size={28} style={{position:'absolute', top:8, right:8}} bg="rgba(255,255,255,0.95)"/>
        )}
      </div>
      <div style={{ padding:'12px 12px 12px', background:'#fff', display:'flex', flexDirection:'column', gap:2 }}>
        <div style={{ fontSize:14, fontWeight:600, letterSpacing:-0.2, lineHeight:1.3,
          display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden',
        }}>{product.name}</div>
        <div style={{ fontSize:13.5, fontWeight:600, color: HUUL_TOKENS.color.ink2, marginBottom:8 }}>{product.priceLabel}</div>
        <button onClick={out ? undefined : handleCta} disabled={out} style={{
          width:'100%', height:40, border:'none', borderRadius:10,
          background: out ? 'rgba(0,0,0,0.07)' : HUUL_TOKENS.color.wa,
          color: out ? HUUL_TOKENS.color.ink4 : '#fff',
          fontSize:13, fontWeight:600, cursor: out ? 'not-allowed' : 'pointer',
          fontFamily: HUUL_TOKENS.font.stack,
          display:'flex', alignItems:'center', justifyContent:'center', gap:6,
        }}>
          {out ? 'Out of stock' : <><IconWhatsApp size={15}/> Contact</>}
        </button>
      </div>
    </div>
  );
}

function ProductGrid({ products, cardLayout, onOpenProduct, showEditHandles, onEdit, onCta }) {
  if (products.length === 0) {
    return (
      <div style={{ padding:'20px 24px', textAlign:'center', color:HUUL_TOKENS.color.ink3, fontSize:14 }}>
        No products yet.
      </div>
    );
  }
  if (cardLayout === 'list') {
    return (
      <div style={{ padding:'0 16px', display:'flex', flexDirection:'column', gap:10 }}>
        {products.map(p => (
          <ProductCard key={p.id} product={p} layout="list"
            onClick={() => onOpenProduct(p)} showEditHandles={showEditHandles} onEdit={onEdit} onCta={onCta}/>
        ))}
      </div>
    );
  }
  const isImmersive = cardLayout === 'immersive';
  return (
    <div style={{ padding:'0 16px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
      {products.map(p => (
        <ProductCard key={p.id} product={p} layout={isImmersive ? 'immersive' : 'grid2'}
          onClick={() => onOpenProduct(p)} showEditHandles={showEditHandles} onEdit={onEdit} onCta={onCta}/>
      ))}
    </div>
  );
}

// ─── Full shop screen (all products) ─────────────────────────
function ShopScreen({ profile, products, onBack, onOpenProduct, cardLayout, onChangeCardLayout, onContactWhatsApp }) {
  const [query, setQuery] = useS_sh('');
  const [cat, setCat] = useS_sh('All');
  const [searchOpen, setSearchOpen] = useS_sh(false);

  const cats = ['All', ...new Set(products.filter(p=>p.published).map(p => p.category))];

  let list = products.filter(p => p.published);
  if (cat !== 'All') list = list.filter(p => p.category === cat);
  if (query) list = list.filter(p => p.name.toLowerCase().includes(query.toLowerCase()));

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      {/* sticky top bar */}
      <div style={{
        padding:'50px 16px 12px', background:'#fff',
        borderBottom:'1px solid rgba(0,0,0,0.07)',
        position:'sticky', top:0, zIndex:10,
      }}>
        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
          <div style={{ width:36, height:36, borderRadius:10, overflow:'hidden', flexShrink:0 }}>
            <Avatar profile={profile} size={36}/>
          </div>
          <div style={{ flex:1, fontSize:16, fontWeight:700, letterSpacing:-0.4 }}>{profile.businessName}</div>
          <IconButton icon={<IconSearch size={19}/>} onClick={() => setSearchOpen(s => !s)} bg="rgba(0,0,0,0.05)"/>
          <button onClick={() => onContactWhatsApp(null)} style={{
            display:'flex', alignItems:'center', gap:6,
            background: HUUL_TOKENS.color.wa, color:'#fff',
            border:'none', borderRadius:99, padding:'9px 16px',
            fontSize:14, fontWeight:600, fontFamily: HUUL_TOKENS.font.stack, cursor:'pointer',
            flexShrink:0,
          }}>
            <IconWhatsApp size={17}/> Chat
          </button>
        </div>

        {searchOpen && (
          <div style={{ marginTop:10 }}>
            <TextField
              value={query} onChange={setQuery} placeholder="Search products"
              prefix={<IconSearch size={17} color={HUUL_TOKENS.color.ink3}/>}
              style={{ minHeight:42, background:'rgba(0,0,0,0.05)', boxShadow:'none' }}
            />
          </div>
        )}
      </div>

      <div style={{ flex:1, overflow:'auto', paddingBottom:100 }}>
        {/* Profile mini-section */}
        <div style={{ padding:'18px 16px 14px', display:'flex', gap:14, alignItems:'flex-start' }}>
          <div style={{ width:86, height:86, borderRadius:18, overflow:'hidden', flexShrink:0, background:'#F2F2F4' }}>
            <Avatar profile={profile} size={86}/>
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:20, fontWeight:700, letterSpacing:-0.5, lineHeight:1.2 }}>{profile.businessName}</div>
            <div style={{ fontSize:13, color:HUUL_TOKENS.color.ink3, marginTop:5, lineHeight:1.4,
              display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden',
            }}>{profile.bio}</div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap', marginTop:8 }}>
              {cats.filter(c => c !== 'All').map(c => (
                <div key={c} style={{
                  background:'#F2F2F4', borderRadius:99, padding:'4px 10px',
                  fontSize:12, fontWeight:500, color:HUUL_TOKENS.color.ink2,
                }}>{c}</div>
              ))}
            </div>
          </div>
        </div>

        {/* Category filter */}
        <div style={{ display:'flex', gap:8, overflowX:'auto', padding:'2px 16px 14px' }}>
          {cats.map(c => (
            <button key={c} onClick={() => setCat(c)} style={{
              border:'none',
              background: cat===c ? HUUL_TOKENS.color.ink : 'rgba(0,0,0,0.05)',
              color: cat===c ? '#fff' : HUUL_TOKENS.color.ink2,
              fontSize:14, fontWeight:600, padding:'10px 18px', borderRadius:99,
              cursor:'pointer', whiteSpace:'nowrap', fontFamily:HUUL_TOKENS.font.stack,
              transition:'background 140ms',
            }}>{c}</button>
          ))}
        </div>

        <ProductGrid products={list} cardLayout={cardLayout} onOpenProduct={onOpenProduct} onCta={onContactWhatsApp}/>
        {list.length === 0 && (
          <div style={{ textAlign:'center', color:HUUL_TOKENS.color.ink3, padding:'60px 20px', fontSize:14 }}>
            No products match your search.
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Product detail ──────────────────────────────────────────
function ProductDetail({ product, profile, onBack, onContactWhatsApp }) {
  const out = product.stock === 0;
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div style={{ flex:1, overflow:'auto', paddingBottom: 100 }}>
        {/* image */}
        <div style={{ position:'relative', background:'#E5E5EA' }}>
          <img src={product.image} alt="" style={{ width:'100%', aspectRatio:'1', objectFit:'cover', display:'block' }}/>
          <IconButton icon={<IconBack size={20}/>} onClick={onBack}
            style={{ position:'absolute', top:56, left:16 }}
            bg="rgba(255,255,255,0.9)"/>
          <IconButton icon={<IconShare size={17}/>} onClick={()=>{}}
            style={{ position:'absolute', top:56, right:16 }}
            bg="rgba(255,255,255,0.9)"/>
        </div>

        {/* content */}
        <div style={{ padding:'20px 20px 120px' }}>
          <div style={{ fontSize:12, color:HUUL_TOKENS.color.accent, fontWeight:600, textTransform:'uppercase', letterSpacing:0.5, marginBottom:6 }}>
            {product.category}
          </div>
          <h1 style={{ fontSize:24, fontWeight:700, letterSpacing:-0.5, margin:0, lineHeight:1.2 }}>{product.name}</h1>
          <div style={{ fontSize:22, fontWeight:600, marginTop:6 }}>{product.priceLabel}</div>

          {out && (
            <div style={{
              marginTop:14, background:'rgba(255,59,48,0.1)', color:HUUL_TOKENS.color.danger,
              padding:'8px 12px', borderRadius:10, fontSize:13, fontWeight:500,
              display:'inline-block',
            }}>Currently out of stock</div>
          )}

          <div style={{ fontSize:15, lineHeight:1.5, color:HUUL_TOKENS.color.ink2, marginTop:18 }}>
            {product.desc}
          </div>

          {/* seller mini card */}
          <div style={{
            marginTop:24, background:'#fff', borderRadius:18, padding:14,
            display:'flex', gap:12, alignItems:'center', boxShadow: HUUL_TOKENS.shadow.card,
          }}>
            <Avatar profile={profile} size={44}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:15, fontWeight:600, letterSpacing:-0.2 }}>{profile.businessName}</div>
              <div style={{ fontSize:13, color:HUUL_TOKENS.color.ink3, marginTop:1 }}>
                {profile.location} · huul.so/{profile.username}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* sticky CTA — sits above the tab bar (~72px) */}
      <div style={{
        position:'absolute', left:0, right:0, bottom:72,
        padding:'20px 20px 0',
        background:'linear-gradient(to top, rgba(242,242,244,1) 60%, rgba(242,242,244,0))',
      }}>
        <PrimaryButton
          variant="wa"
          onClick={() => onContactWhatsApp(product)}
          disabled={out}
          icon={<IconWhatsApp size={22}/>}
        >
          {out ? 'Out of stock' : 'Contact on WhatsApp'}
        </PrimaryButton>
      </div>
    </div>
  );
}

// ─── WhatsApp confirmation sheet ────────────────────────────
function WhatsAppSheet({ open, onClose, product, profile, onSend }) {
  const defaultMsg = product
    ? `Hi ${profile.businessName}! I'm interested in "${product.name}" (${product.priceLabel}) from huul.so/${profile.username}. Is it available?`
    : '';
  const [msg, setMsg] = useS_sh(defaultMsg);

  React.useEffect(() => { if (open) setMsg(defaultMsg); }, [open, product]);

  return (
    <BottomSheet open={open} onClose={onClose} title="Message seller">
      {product && (
        <div style={{
          background:'#fff', borderRadius:14, padding:10,
          display:'flex', gap:10, alignItems:'center', marginBottom:14,
          boxShadow: HUUL_TOKENS.shadow.card,
        }}>
          <img src={product.image} alt="" style={{ width:50, height:50, borderRadius:10, objectFit:'cover' }}/>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:14, fontWeight:600 }}>{product.name}</div>
            <div style={{ fontSize:13, color:HUUL_TOKENS.color.ink3 }}>{product.priceLabel} · {profile.whatsapp}</div>
          </div>
        </div>
      )}

      <HuulLabel>Your message</HuulLabel>
      <TextField value={msg} onChange={setMsg} multiline rows={5}/>

      <div style={{ marginTop:16, display:'flex', flexDirection:'column', gap:10 }}>
        <PrimaryButton variant="wa" icon={<IconWhatsApp size={22}/>} onClick={() => onSend(msg)}>
          Open WhatsApp
        </PrimaryButton>
        <GhostButton onClick={onClose} style={{ justifyContent:'center', width:'100%' }}>Cancel</GhostButton>
      </div>
    </BottomSheet>
  );
}

window.ProductGrid = ProductGrid;
window.ProductCard = ProductCard;
window.ShopScreen = ShopScreen;
window.ProductDetail = ProductDetail;
window.WhatsAppSheet = WhatsAppSheet;
