const BRAND_ICON_SLUGS={whatsapp:'whatsapp',telegram:'telegram',facebook:'facebook',pinterest:'pinterest',x:'x'};
function loadImage(src){
  return new Promise((res,rej)=>{
    const img=new Image();
    img.crossOrigin='anonymous';
    img.onload=()=>res(img);
    img.onerror=rej;
    img.src=src;
  });
}
function drawCover(ctx,img,x,y,w,h){
  const ir=img.width/img.height, tr=w/h;
  let sw=img.width,sh=img.height,sx=0,sy=0;
  if(ir>tr){ sw=img.height*tr; sx=(img.width-sw)/2; } else { sh=img.width/tr; sy=(img.height-sh)/2; }
  ctx.drawImage(img,sx,sy,sw,sh,x,y,w,h);
}
function wrapText(ctx,text,cx,y,maxWidth,lineHeight){
  const words=text.split(' ');
  let line='',lines=[];
  words.forEach(w=>{
    const test=line?line+' '+w:w;
    if(ctx.measureText(test).width>maxWidth&&line){ lines.push(line); line=w; } else { line=test; }
  });
  if(line)lines.push(line);
  lines.slice(0,3).forEach((l,i)=>ctx.fillText(l,cx,y+i*lineHeight));
  return lines.length;
}
async function buildLuxuryCard(p,cfg,url){
  if(document.fonts&&document.fonts.ready)await document.fonts.ready;
  const W=1000,H=1300;
  const canvas=document.createElement('canvas');
  canvas.width=W;canvas.height=H;
  const ctx=canvas.getContext('2d');
  const dark=cfg.cardTheme==='charcoal';
  const gold='#B89B5E';
  ctx.fillStyle=dark?'#1F1F1F':'#F8F5F0';
  ctx.fillRect(0,0,W,H);
  const imgH=Math.round(H*0.60);
  try{ const img=await loadImage(photo(p.imgs[0],1200)); drawCover(ctx,img,0,0,W,imgH); }catch(e){ ctx.fillStyle='#ddd'; ctx.fillRect(0,0,W,imgH); }
  ctx.fillStyle=gold; ctx.fillRect(0,imgH,W,3);
  ctx.textAlign='center';
  let y=imgH+66;
  ctx.fillStyle=gold; ctx.font='600 20px Jost, sans-serif';
  ctx.fillText((cfg.logoText||'BOLD BEE').toUpperCase().split('').join('\u200a'),W/2,y);
  y+=58;
  ctx.fillStyle=dark?'#F8F5F0':'#1F1F1F'; ctx.font='400 46px "Cormorant Garamond", Georgia, serif';
  ctx.fillText(p.name,W/2,y);
  y+=44;
  ctx.fillStyle=gold; ctx.font='italic 400 23px "Cormorant Garamond", Georgia, serif';
  ctx.fillText(cfg.tagline||'',W/2,y);
  y+=46;
  ctx.fillStyle=dark?'#C9C4BA':'#5b5952'; ctx.font='400 19px Jost, sans-serif';
  wrapText(ctx,cfg.defaultDescription||'',W/2,y,740,28);
  ctx.fillStyle=dark?'#8a877f':'#8a877f'; ctx.font='500 15px Jost, sans-serif';
  ctx.fillText((cfg.brandFooter||'www.boldbee.store').toLowerCase(),W/2,H-52);
  if(cfg.cardQrEnabled){
    try{ const qrImg=await loadImage('https://api.qrserver.com/v1/create-qr-code/?size=200x200&margin=0&color=1F1F1F&bgcolor='+(dark?'1F1F1F':'F8F5F0')+'&data='+encodeURIComponent(url)); ctx.drawImage(qrImg,W-160,H-160,110,110); }catch(e){}
  }
  return canvas;
}
function ShareSheet({product,url}){
  const cfg=ShareStore.config();
  if(!cfg.enabled)return null;
  const [open,setOpen]=React.useState(false);
  const [copied,setCopied]=React.useState(false);
  const [showQr,setShowQr]=React.useState(false);
  const [downloading,setDownloading]=React.useState(false);
  const canonicalUrl=url||location.href;
  const desc=cfg.defaultDescription;
  const dark=cfg.cardTheme==='charcoal';
  React.useEffect(()=>{ if(open&&window.lucide)window.lucide.createIcons(); },[open,showQr]);
  function track(channel){ ShareStore.log(product.id,product.name,channel,false); }
  function whatsappText(){ return `I thought you might appreciate this beautiful creation from BOLD BEE.\n\n${product.name}\n\nDiscover more\n${canonicalUrl}`; }
  async function downloadCard(){
    setDownloading(true);
    try{
      const canvas=await buildLuxuryCard(product,cfg,canonicalUrl);
      const link=document.createElement('a');
      link.download=`${product.id}-luxury-card.png`;
      link.href=canvas.toDataURL('image/png');
      link.click();
      track('cardDownload');
    }catch(e){}
    setDownloading(false);
  }
  async function shareCardNative(){
    track('nativeShare');
    try{
      const canvas=await buildLuxuryCard(product,cfg,canonicalUrl);
      const blob=await new Promise(r=>canvas.toBlob(r,'image/png'));
      const file=new File([blob],`${product.id}-luxury-card.png`,{type:'image/png'});
      if(navigator.canShare&&navigator.canShare({files:[file]})){
        await navigator.share({title:product.name,text:desc,url:canonicalUrl,files:[file]});
        return;
      }
    }catch(e){}
    if(navigator.share){ navigator.share({title:product.name,text:desc,url:canonicalUrl}).catch(()=>{}); }
  }
  function openChannel(id){
    track(id);
    if(id==='whatsapp'){ window.open('https://wa.me/?text='+encodeURIComponent(whatsappText()),'_blank'); }
    else if(id==='telegram'){ window.open('https://t.me/share/url?url='+encodeURIComponent(canonicalUrl)+'&text='+encodeURIComponent(product.name),'_blank'); }
    else if(id==='email'){ location.href='mailto:?subject='+encodeURIComponent('Discover a Creation from BOLD BEE')+'&body='+encodeURIComponent(`${product.name}\n${desc}\n\n${canonicalUrl}\n\nBOLD BEE`); }
    else if(id==='facebook'){ window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(canonicalUrl),'_blank'); }
    else if(id==='pinterest'){ window.open('https://pinterest.com/pin/create/button/?url='+encodeURIComponent(canonicalUrl)+'&description='+encodeURIComponent(product.name),'_blank'); }
    else if(id==='x'){ window.open('https://twitter.com/intent/tweet?text='+encodeURIComponent(product.name)+'&url='+encodeURIComponent(canonicalUrl),'_blank'); }
    else if(id==='copyLink'){ navigator.clipboard&&navigator.clipboard.writeText(canonicalUrl).then(()=>{setCopied(true);setTimeout(()=>setCopied(false),2000);}); }
    else if(id==='qr'){ setShowQr(true); }
    else if(id==='nativeShare'){ shareCardNative(); }
  }
  const channels=ShareStore.activeChannels().filter(id=>id!=='nativeShare'||!!navigator.share);
  const qrSrc='https://api.qrserver.com/v1/create-qr-code/?size=280x280&color=1F1F1F&bgcolor=F8F5F0&data='+encodeURIComponent(canonicalUrl);
  return (
    <div>
      <button onClick={()=>setOpen(true)} style={{display:'flex',alignItems:'center',gap:8,background:'none',border:'none',padding:'10px 0',cursor:'pointer',fontSize:12,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',color:'var(--text-primary)'}}>
        <i data-lucide="share-2" style={{width:15,height:15}}></i>{cfg.sectionTitle}
      </button>
      {open&&(
        <div onClick={()=>setOpen(false)} style={{position:'fixed',inset:0,background:'rgba(31,31,31,0.6)',zIndex:500,display:'flex',alignItems:'center',justifyContent:'center',padding:20,overflowY:'auto'}}>
          <div onClick={e=>e.stopPropagation()} style={{background:'var(--ivory)',borderRadius:'var(--radius-lg)',maxWidth:460,width:'100%',padding:'32px',boxShadow:'var(--shadow-card)',position:'relative',maxHeight:'92vh',overflowY:'auto'}}>
            <button onClick={()=>setOpen(false)} aria-label="Close" style={{position:'absolute',top:18,right:18,background:'none',border:'none',cursor:'pointer',color:'var(--text-muted)'}}><i data-lucide="x" style={{width:18,height:18}}></i></button>
            <div style={{fontSize:11,letterSpacing:'var(--tracking-widest)',textTransform:'uppercase',color:'var(--gold-deep)',marginBottom:8}}>Luxury Sharing</div>
            <h3 style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:24,margin:'0 0 20px',color:'var(--text-primary)'}}>{cfg.sectionTitle}</h3>
            {!showQr?(
              <React.Fragment>
                <div style={{borderRadius:'var(--radius-lg)',overflow:'hidden',border:'1px solid var(--border-soft)',background:dark?'var(--charcoal)':'#fff'}}>
                  <div style={{aspectRatio:'5/3',overflow:'hidden'}}><img src={photo(product.imgs[0],800)} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}}/></div>
                  <div style={{textAlign:'center',padding:'22px 20px 26px',borderTop:'2px solid var(--gold-deep)'}}>
                    <div style={{fontSize:11,letterSpacing:'0.3em',color:'var(--gold-deep)',marginBottom:10}}>{cfg.logoText||'BOLD BEE'}</div>
                    <div style={{fontFamily:'var(--font-serif)',fontSize:22,color:dark?'var(--ivory)':'var(--text-primary)',marginBottom:6}}>{product.name}</div>
                    <div style={{fontFamily:'var(--font-serif)',fontStyle:'italic',fontSize:15,color:'var(--gold-deep)',marginBottom:10}}>{cfg.tagline}</div>
                    <div style={{fontSize:13,color:dark?'#c9c4ba':'var(--text-muted)',lineHeight:1.6,marginBottom:14}}>{desc}</div>
                    <div style={{fontSize:11,letterSpacing:'0.08em',color:'var(--text-muted)'}}>{cfg.brandFooter}</div>
                  </div>
                </div>
                {cfg.features.download&&<button onClick={downloadCard} disabled={downloading} style={{width:'100%',marginTop:18,padding:'14px',background:'var(--charcoal)',color:'var(--ivory)',border:'none',borderRadius:'var(--radius-md)',fontSize:13,letterSpacing:'0.06em',textTransform:'uppercase',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',gap:8}}>
                  <i data-lucide="download" style={{width:15,height:15}}></i>{downloading?'Preparing…':'Download Luxury Card'}
                </button>}
                <div style={{fontSize:11,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--text-muted)',margin:'22px 0 12px'}}>Or Share Via</div>
                <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12}}>
                  {channels.map(id=>{
                    const brandSlug=BRAND_ICON_SLUGS[id];
                    return (
                    <button key={id} onClick={()=>openChannel(id)} className="share-chip" style={{display:'flex',flexDirection:'column',alignItems:'center',gap:7,background:'none',border:'1px solid var(--border-soft)',borderRadius:'var(--radius-md)',padding:'13px 6px',cursor:'pointer',color:'var(--text-primary)',transition:'transform 220ms var(--ease-out),border-color 220ms var(--ease-out)'}}>
                      {brandSlug?<img src={`https://cdn.simpleicons.org/${brandSlug}`} alt="" style={{width:20,height:20}}/>:<i data-lucide={ShareStore.CHANNEL_DEFS[id].icon} style={{width:18,height:18}}></i>}
                      <span style={{fontSize:10.5,letterSpacing:'0.02em'}}>{id==='copyLink'&&copied?'Copied':ShareStore.CHANNEL_DEFS[id].label}</span>
                    </button>
                  );})}
                </div>
              </React.Fragment>
            ):(
              <div style={{textAlign:'center'}}>
                <img src={qrSrc} alt="QR code for product link" style={{width:220,height:220,borderRadius:'var(--radius-md)',border:'1px solid var(--border-soft)'}}/>
                <div style={{display:'flex',gap:10,justifyContent:'center',marginTop:18}}>
                  {cfg.features.qrDownload&&<a href={qrSrc} download={`${product.id}-qr.png`} style={{fontSize:12,letterSpacing:'0.04em',textTransform:'uppercase',color:'var(--gold-deep)',textDecoration:'none'}}>Download</a>}
                  {cfg.features.qrPrint&&<button onClick={()=>{const w=window.open('');w.document.write(`<img src="${qrSrc}" onload="window.print()">`);}} style={{fontSize:12,letterSpacing:'0.04em',textTransform:'uppercase',color:'var(--gold-deep)',background:'none',border:'none',cursor:'pointer'}}>Print</button>}
                  <button onClick={()=>setShowQr(false)} style={{fontSize:12,letterSpacing:'0.04em',textTransform:'uppercase',color:'var(--text-muted)',background:'none',border:'none',cursor:'pointer'}}>Back</button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
      <style>{`.share-chip:hover{color:var(--gold-deep);border-color:var(--gold);transform:scale(1.04)}`}</style>
    </div>
  );
}
window.ShareSheet=ShareSheet;
