// Art Tools: las herramientas de arte de la plataforma, en pestañas (igual que
// Templates / Lockers / Admin). Una pestaña es Ask Bruce (el agente IA); las
// demas son utilidades de arte. El titulo y las pestañas los pone el Shell.
function descargar(href,name){const a=document.createElement("a");a.href=href;a.download=name;document.body.appendChild(a);a.click();a.remove();}

// Acabado unico de las tarjetas de preview de resultado (Vectorize, Text Effects, Mockups).
const cajaPreview={aspectRatio:"1 / 1",background:"var(--gray-100)",borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden"};
function ResultCard({title,children}){
  return <Card padding="20px" style={{display:"flex",flexDirection:"column",gap:14}}>
    <span style={{fontSize:13,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>{title}</span>
    {children}
  </Card>;
}

// Vectorize: sube una imagen y elige la salida — vectores o bordado (stitch file).
function VectorizeTool(){
  const modos=[
    {label:"Vectors",cta:"Vectorize",resultado:"Traced to vectors — scales without losing quality.",formato:"svg",nombre:"vectorized"},
    {label:"Embroidery",cta:"Convert to embroidery",resultado:"Digitized for stitching — stitch file ready.",formato:"dst",nombre:"embroidery"}
  ];
  const [img,setImg]=React.useState(null);
  const [listo,setListo]=React.useState(false);
  const [modo,setModo]=React.useState(0);
  const inp=React.useRef(null);
  const m=modos[modo];
  const cargar=f=>{if(!f)return;const r=new FileReader();r.onload=e=>{setImg(e.target.result);setListo(false)};r.readAsDataURL(f)};
  return <div style={{display:"flex",flexDirection:"column",gap:20,maxWidth:820}}>
    <div style={{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"}}>
      {modos.map((mm,i)=><button key={mm.label} type="button" onClick={()=>{setModo(i);setListo(false)}}
        style={{fontSize:12,fontWeight:700,padding:"6px 14px",borderRadius:"var(--radius-pill)",cursor:"pointer",
          border:"var(--border-width-hairline) solid "+(modo===i?"var(--bruce-black)":"var(--border-hairline)"),
          background:modo===i?"var(--bruce-black)":"var(--bruce-white)",color:modo===i?"#fff":"var(--text-muted)"}}>{mm.label}</button>)}
    </div>
    <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(260px,1fr))",gap:20,alignItems:"stretch"}}>
      <ResultCard title="Source">
        <input ref={inp} type="file" accept="image/*" style={{display:"none"}} onChange={e=>cargar(e.target.files&&e.target.files[0])}/>
        <button onClick={()=>inp.current&&inp.current.click()} onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();cargar(e.dataTransfer.files&&e.dataTransfer.files[0])}}
          style={{...cajaPreview,width:"100%",background:"var(--surface-sunken)",cursor:"pointer",font:"inherit",flexDirection:"column",gap:8,padding:img?0:24,boxSizing:"border-box",
            border:img?"var(--border-width-hairline) solid var(--border-hairline)":"2px dashed var(--border-hairline)"}}>
          {img?<img src={img} alt="" style={{width:"100%",height:"100%",objectFit:"contain"}}/>
            :<React.Fragment><Icon name="image" size={30} strokeColor="var(--text-muted)"/>
              <div style={{fontSize:13,fontWeight:700,color:"var(--text-body)"}}>Upload an image</div>
              <div style={{fontSize:11,color:"var(--text-subtle)"}}>Click or drop · PNG, JPG</div></React.Fragment>}
        </button>
        <Button size="md" fullWidth disabled={!img} onClick={()=>setListo(true)}>{m.cta}</Button>
      </ResultCard>
      <ResultCard title="Result">
        <div style={cajaPreview}>
          {listo&&img?<img src={img} alt="" style={{width:"100%",height:"100%",objectFit:"contain",padding:16,boxSizing:"border-box"}}/>
            :<Icon name="image" size={26} strokeColor="var(--text-subtle)"/>}
        </div>
        <Button size="md" fullWidth variant="outline" disabled={!listo||!img} iconLeft={<Icon name="download" size={15}/>}
          onClick={()=>descargar(img,m.nombre+"."+m.formato)}>Download {m.formato.toUpperCase()}</Button>
      </ResultCard>
    </div>
  </div>;
}

// Un mismo SVG alimenta el preview y la descarga (WYSIWYG y siempre encaja).
function svgTexto(txt,efecto){
  const s=(txt||"Your text").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
  const T=(x,y,fill,extra="")=>`<text x="${x}" y="${y}" text-anchor="middle" font-family="sans-serif" font-weight="800" font-size="112" fill="${fill}" ${extra}>${s}</text>`;
  let body;
  if(efecto==="Outline")body=`<text x="400" y="205" text-anchor="middle" font-family="sans-serif" font-weight="800" font-size="112" fill="none" stroke="#1b211f" stroke-width="3">${s}</text>`;
  else if(efecto==="Drop shadow")body=T(410,213,"#00000030")+T(400,205,"#1b211f");
  else if(efecto==="3D extrude")body=[6,5,4,3,2,1].map(i=>T(400+i,205+i,"#8a8a8a")).join("")+T(400,205,"#1b211f");
  else if(efecto==="Distress")body=T(400,205,"#1b211f",'opacity="0.6"');
  else if(efecto==="Arch")body=`<defs><path id="p" d="M 90 250 Q 400 70 710 250"/></defs><text font-family="sans-serif" font-weight="800" font-size="90" fill="#1b211f"><textPath href="#p" startOffset="50%" text-anchor="middle">${s}</textPath></text>`;
  else if(efecto==="Bridge")body=`<defs><path id="p" d="M 90 110 Q 400 300 710 110"/></defs><text font-family="sans-serif" font-weight="800" font-size="90" fill="#1b211f"><textPath href="#p" startOffset="50%" text-anchor="middle">${s}</textPath></text>`;
  else body=T(400,205,"#1b211f");
  return `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="320" viewBox="0 0 800 320"><rect width="800" height="320" fill="#ffffff"/>${body}</svg>`;
}

// Text Effects: escribe un texto, elige un efecto prediseñado y descarga.
function TextEffectsTool(){
  const efectos=(window.DATA.catalog.effects.items)||[];
  const [txt,setTxt]=React.useState("CHAMPIONS");
  const [efecto,setEfecto]=React.useState(efectos[0]||"Drop shadow");
  const [aviso,setAviso]=React.useState("");
  const uri=()=>"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(svgTexto(txt,efecto));
  const exportar=fmt=>{
    setAviso("");
    if(fmt==="svg"){descargar(uri(),"text-effect.svg");return}
    if(fmt==="png"){const im=new Image();im.onload=()=>{const c=document.createElement("canvas");c.width=800;c.height=320;c.getContext("2d").drawImage(im,0,0);descargar(c.toDataURL("image/png"),"text-effect.png")};im.src=uri();return}
    setAviso(fmt.toUpperCase()+" export is coming soon.");
  };
  return <div style={{display:"flex",flexDirection:"column",gap:16}}>
    <p style={{margin:0,fontSize:14,color:"var(--text-muted)",maxWidth:560,lineHeight:1.5}}>Type your text, pick a predesigned effect and export it.</p>
    <div style={{display:"flex",gap:24,flexWrap:"wrap",alignItems:"flex-start"}}>
      <div style={{flex:"1 1 260px",minWidth:0,display:"flex",flexDirection:"column",gap:16}}>
        <Input label="Text" value={txt} onChange={e=>setTxt(e.target.value)}/>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>
          <span style={{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-muted)"}}>Effect</span>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            {efectos.map(e=><button key={e} type="button" onClick={()=>setEfecto(e)}
              style={{fontSize:12,fontWeight:700,padding:"6px 12px",borderRadius:"var(--radius-pill)",cursor:"pointer",
                border:"var(--border-width-hairline) solid "+(efecto===e?"var(--bruce-black)":"var(--border-hairline)"),
                background:efecto===e?"var(--bruce-black)":"var(--bruce-white)",color:efecto===e?"#fff":"var(--text-muted)"}}>{e}</button>)}
          </div>
        </div>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>
          <span style={{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-muted)"}}>Download</span>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            {["png","svg","pdf","eps"].map(f=><Button key={f} size="sm" variant="outline" onClick={()=>exportar(f)}>{f.toUpperCase()}</Button>)}
          </div>
          {aviso&&<span style={{fontSize:12,color:"var(--text-subtle)"}}>{aviso}</span>}
        </div>
      </div>
      <div style={{flex:"1 1 320px",minWidth:0}}>
        <ResultCard title="Preview">
          <div style={{borderRadius:8,overflow:"hidden"}}>
            <img src={uri()} alt="" style={{width:"100%",display:"block"}}/>
          </div>
        </ResultCard>
      </div>
    </div>
  </div>;
}

// Mockup creator: elige un diseño y un producto y arma el mockup.
function MockupTool({go}){
  const designs=window.DATA.designs||[];
  const productos=Object.keys(window.DATA.precios.garment);
  const [design,setDesign]=React.useState(designs[0]);
  const [prod,setProd]=React.useState(productos[0]);
  return <div style={{display:"flex",flexDirection:"column",gap:16}}>
    <p style={{margin:0,fontSize:14,color:"var(--text-muted)",maxWidth:560,lineHeight:1.5}}>Put a design on a product to preview and share a mockup.</p>
    <div style={{display:"flex",gap:24,flexWrap:"wrap",alignItems:"flex-start"}}>
      <div style={{flex:"1 1 240px",minWidth:0,display:"flex",flexDirection:"column",gap:16}}>
        <Select label="Product" options={productos} value={prod} onChange={e=>setProd(e.target.value)}/>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>
          <span style={{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-muted)"}}>Design</span>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(84px,1fr))",gap:8}}>
            {designs.map(d=><button key={d.name} type="button" onClick={()=>setDesign(d)}
              style={{padding:6,cursor:"pointer",background:"var(--bruce-white)",borderRadius:6,
                border:"var(--border-width-hairline) solid "+(design&&design.name===d.name?"var(--bruce-black)":"var(--border-hairline)")}}>
              <div style={{aspectRatio:"1 / 1",background:"var(--surface-sunken)",borderRadius:4,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center"}}>
                <img src={d.preview} alt="" style={{width:"100%",height:"100%",objectFit:"contain",padding:6,boxSizing:"border-box"}}/>
              </div></button>)}
          </div>
        </div>
      </div>
      <div style={{flex:"1 1 320px",minWidth:0}}>
        <ResultCard title={prod}>
          <div style={cajaPreview}>
            {design&&<img src={design.preview} alt="" style={{width:"70%",height:"70%",objectFit:"contain"}}/>}
          </div>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            <Button size="sm" variant="outline" iconLeft={<Icon name="download" size={15}/>}
              onClick={()=>design&&descargar(design.preview,"mockup.png")}>Download</Button>
            <Button size="sm" variant="ghost" onClick={()=>go&&go("builderEdit")}>Open in editor</Button>
          </div>
        </ResultCard>
      </div>
    </div>
  </div>;
}

function ArtToolsScreen({go,tab,setTab,showTabs,tabs}){
  const {isMobile}=useBreakpoint();
  const pad=isMobile?"16px":"24px 32px";
  return <div style={{display:"flex",flexDirection:"column",minHeight:"100%"}}>
    {showTabs&&<div style={{padding:"12px 16px 0",borderBottom:"var(--border-width-hairline) solid var(--border-hairline)",overflowX:"auto"}}>
      <Tabs tabs={tabs} value={tab} onChange={setTab}/>
    </div>}
    {tab==="Ask Bruce"&&<AIStudioScreen go={go}/>}
    {tab!=="Ask Bruce"&&<div style={{padding:pad}}>
      {tab==="Vectorize"&&<VectorizeTool/>}
      {tab==="Text Effects"&&<TextEffectsTool/>}
      {tab==="Mockups"&&<MockupTool go={go}/>}
    </div>}
  </div>;
}
window.ArtToolsScreen=ArtToolsScreen;
