const OUTLINES=[["none","None"],["box","Box"],["contour","Contour"]];

function Section({title,children,action}){
  return <div style={{display:"flex",flexDirection:"column",gap:12}}>
    <div style={{display:"flex",alignItems:"center",gap:8}}>
      <span style={{flex:1,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-subtle)"}}>{title}</span>
      {action}
    </div>
    {children}
  </div>;
}

function RailButton({icon,label,active,onClick}){
  return <Tooltip label={label} placement="left">
    <button aria-label={label} onClick={onClick} style={{width:40,height:40,display:"flex",alignItems:"center",justifyContent:"center",
      border:"1px solid "+(active?"var(--bruce-black)":"var(--border-hairline)"),borderRadius:8,
      background:active?"var(--bruce-black)":"var(--bruce-white)",
      color:active?"var(--bruce-white)":"var(--text-body)",cursor:"pointer",padding:0}}>
      <Icon name={icon} size={18}/>
    </button>
  </Tooltip>;
}

function AssetTile({label,selected,onClick,add,preview}){
  return <button onClick={onClick} title={label} style={{width:"100%",aspectRatio:"1 / 1",borderRadius:8,cursor:"pointer",padding:add?0:6,font:"inherit",
    border:add?"1px dashed var(--gray-300)":"2px solid "+(selected?"var(--bruce-blue)":"var(--border-hairline)"),
    background:add?"var(--surface-sunken)":"var(--bruce-white)",display:"flex",flexDirection:"column",alignItems:"center",
    justifyContent:"center",gap:6,color:"var(--text-subtle)",fontSize:10,textAlign:"center",lineHeight:1.3,overflow:"hidden"}}>
    {preview?<img src={preview} alt={label} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
      :<><Icon name={add?"plus":"image"} size={16} strokeColor="var(--text-muted)"/>{label}</>}
  </button>;
}

function HistoryTile({label,note,selected,onClick}){
  return <TemplateCard name={label} category={note} selected={selected} onClick={onClick} style={{width:"100%"}}/>;
}

function ArtTemplateBuilder({onOrder}){
  const {isMobile,isTablet}=useBreakpoint();
  const stacked=isMobile||isTablet;
  const [colors]=React.useState(["#1d4289","#f1c400","#ffffff","#1b211f"]);
  const [ink,setInk]=React.useState("#1d4289");
  const [team,setTeam]=React.useState("BULLDOGS");
  const [sport,setSport]=React.useState("Baseball");
  const [number,setNumber]=React.useState("26");
  const [asset]=React.useState("Champions banner");
  const [logoSize,setLogoSize]=React.useState(100);
  const [outlineOn,setOutlineOn]=React.useState(false);
  const [outline,setOutline]=React.useState("box");
  const [outlineW,setOutlineW]=React.useState(4);
  const [crop,setCrop]=React.useState(false);
  const [history,setHistory]=React.useState(false);
  const [notes,setNotes]=React.useState(false);
  const [hilo,setHilo]=React.useState([
    {who:"Dev Patel",text:"Can we thicken the outline on the mascot?",when:"Aug 20"},
    {who:"Ana Ruiz",text:"Done — bumped it to 4pt on v2.",when:"Aug 21"}
  ]);
  const [nota,setNota]=React.useState("");
  const [share,setShare]=React.useState(false);
  const link="https://bruce.app/t/4658-bulldogs";
  const comentar=()=>{if(!nota.trim())return;setHilo(h=>[{who:"Ana Ruiz",text:nota.trim(),when:"Just now"},...h]);setNota("")};
  const [generating,setGenerating]=React.useState(false);
  const [advanced,setAdvanced]=React.useState(false);
  const [exportOpen,setExportOpen]=React.useState(false);
  const [toast,setToast]=React.useState("");
  const [pick,setPick]=React.useState("Reference template");

  return <div style={{padding:isMobile?"16px":"24px 32px",display:"flex",flexDirection:"column",gap:24}}>
    <ShareDialog open={share} onClose={()=>setShare(false)} link={link}
      subject={"Artwork for "+team} note="Anyone with the link can view and comment on this design."/>
    <div style={{display:"grid",gridTemplateColumns:stacked?"1fr":"minmax(360px,1fr) 320px 40px",gap:16,alignItems:"start"}}>

      <Card padding="0" style={{aspectRatio:"1 / 1",display:"flex",alignItems:"center",justifyContent:"center"}}>
        <svg viewBox="0 0 400 400" role="img" aria-label={team+" "+sport+" artwork preview"}
          style={{width:"86%",height:"86%"}}>
          {outlineOn&&<rect x={8} y={8} width={384} height={384} fill="none"
            stroke="var(--gray-300)" strokeWidth={outlineW}
            strokeDasharray={outline==="contour"?"2 6":"10 6"}
            rx={outline==="contour"?190:4}/>}
          <image href="../../assets/mascots/bulldogs-mascot.png"
            x={200-(logoSize*1.6)/2} y={150-(logoSize*1.6)/2} width={logoSize*1.6} height={logoSize*1.6}
            preserveAspectRatio="xMidYMid meet"/>
          <text x={200} y={60} textAnchor="middle" fill={ink}
            style={{font:"800 42px var(--font-core)",letterSpacing:"-.01em"}}>{team}</text>
          <text x={200} y={330} textAnchor="middle" fill={ink}
            style={{font:"700 20px var(--font-core)",letterSpacing:".14em"}}>{(sport||"").toUpperCase()}</text>
          <text x={200} y={378} textAnchor="middle" fill={ink}
            style={{font:"800 44px var(--font-core)"}}>{number}</text>
        </svg>
      </Card>

      <div style={{display:"flex",flexDirection:"column",gap:12,minWidth:0}}>
        <Card padding="20px" overflow="visible" style={{display:"flex",flexDirection:"column",gap:18}}>
          <div style={{display:"flex",alignItems:"center",gap:4}}>
            <span style={{flex:1,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-subtle)"}}>{asset}</span>
            <IconButton label="Save template" size="sm" variant="ghost"><Icon name="bookmark" size={15}/></IconButton>
            <IconButton label="Reset" size="sm" variant="ghost" onClick={()=>{setLogoSize(100);setOutlineOn(false);setCrop(false)}}><Icon name="rotate-ccw" size={15}/></IconButton>
          </div>
          <ColorField value={ink} swatches={colors} onChange={setInk}/>
          <div style={{display:"flex",flexDirection:"column",gap:12}}>
            <Input label="Team name" value={team} onChange={e=>setTeam(e.target.value)}/>
            <Input label="Sport" value={sport} onChange={e=>setSport(e.target.value)}/>
            <Input label="Number" value={number} onChange={e=>setNumber(e.target.value)}/>
          </div>

          <div style={{borderTop:"1px solid var(--border-hairline)",paddingTop:16,display:"flex",flexDirection:"column",gap:16}}>
            <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(64px,1fr))",gap:8}}>
              <AssetTile label={asset} preview="../../assets/mascots/bulldogs-mascot.png" selected/>
              <AssetTile label="Add" add/>
            </div>
          </div>

          <button type="button" onClick={()=>setAdvanced(!advanced)} style={{display:"flex",alignItems:"center",gap:6,border:"none",
            background:"none",padding:0,cursor:"pointer",font:"inherit",fontSize:12,fontWeight:600,color:"var(--text-link)",
            borderTop:"1px solid var(--border-hairline)",paddingTop:16,width:"100%"}}>
            <Icon name={advanced?"chevron-up":"chevron-down"} size={14}/>Advanced options
          </button>

          {advanced&&<div style={{display:"flex",flexDirection:"column",gap:16}}>
            {/* El slider pide ancho; los dos interruptores si se emparejan. */}
            <div style={{display:"flex",flexDirection:"column",gap:6}}>
              <div style={{display:"flex",alignItems:"baseline",gap:8}}>
                <span style={{flex:1,fontSize:12,fontWeight:600}}>Logo size</span>
                <span style={{fontFamily:"var(--font-core)",fontSize:12,color:"var(--text-muted)"}}>{logoSize}%</span>
              </div>
              <Slider value={logoSize} min={25} max={400} onChange={setLogoSize}/>
            </div>

            <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(120px,1fr))",gap:12}}>
              <div style={{display:"flex",alignItems:"center",gap:8,minWidth:0}}>
                <span style={{flex:1,fontSize:12,fontWeight:600}}>Cut-line</span>
                <Switch checked={outlineOn} onChange={setOutlineOn} size="sm"/>
              </div>
              <div style={{display:"flex",alignItems:"center",gap:8,minWidth:0}}>
                <span style={{flex:1,fontSize:12,fontWeight:600}}>Trim exports</span>
                <Switch checked={crop} onChange={setCrop} size="sm"/>
              </div>
            </div>

            <div style={{display:"flex",flexDirection:"column",gap:12}}>
              {outlineOn&&<div style={{display:"flex",flexDirection:"column",gap:12}}>
                <div style={{display:"inline-flex",width:"100%",border:"1px solid var(--border-hairline)",borderRadius:4,overflow:"hidden"}}>
                  {OUTLINES.filter(o=>o[0]!=="none").map(([v,t],i)=><button key={v} type="button" aria-pressed={outline===v} onClick={()=>setOutline(v)}
                    style={{flex:1,height:34,border:"none",borderLeft:i?"1px solid var(--border-hairline)":"none",cursor:"pointer",font:"inherit",
                      fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",
                      background:outline===v?"var(--bruce-black)":"var(--bruce-white)",color:outline===v?"#fff":"var(--text-muted)"}}>{t}</button>)}
                </div>
                <div style={{display:"flex",alignItems:"center",gap:12}}>
                  <span style={{fontSize:12,color:"var(--text-muted)",width:70}}>Thickness</span>
                  <div style={{flex:1}}><Slider value={outlineW} min={1} max={12} onChange={setOutlineW}/></div>
                  <span style={{fontFamily:"var(--font-mono)",fontSize:12,width:34,textAlign:"right"}}>{outlineW}pt</span>
                </div>
              </div>}
            </div>

          </div>}
        </Card>
      </div>

      <div style={{display:"flex",flexDirection:stacked?"row":"column",gap:8,position:"relative",
        order:stacked?-1:0,justifyContent:stacked?"flex-end":"flex-start"}}>
        <RailButton icon="sparkles" label="Generate with AI" active={generating} onClick={()=>setGenerating(!generating)}/>
        <RailButton icon="history" label="Template history" active={history} onClick={()=>setHistory(!history)}/>
        <RailButton icon="message-square" label="Comments" active={notes} onClick={()=>setNotes(!notes)}/>
        <RailButton icon="share-2" label="Share" active={share} onClick={()=>setShare(true)}/>
        <RailButton icon="clipboard-list" label="Order this design" onClick={onOrder}/>
        <RailButton icon="download" label="Download" onClick={()=>setExportOpen(!exportOpen)}/>
        {exportOpen&&<ExportMenu style={stacked?{position:"absolute",right:0,top:52,zIndex:20}:{position:"absolute",right:48,top:120,zIndex:20}}
          onPick={fmt=>{setExportOpen(false);setToast({fmt,crop})}}/>}
      </div>
    </div>

    {notes&&<Card padding="20px" overflow="visible" style={{display:"flex",flexDirection:"column",gap:14}}>
      <div style={{display:"flex",alignItems:"center",gap:8}}>
        <span style={{flex:1,fontSize:13,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>Comments</span>
        <span style={{fontSize:12,color:"var(--text-muted)"}}>{hilo.length}</span>
        <IconButton label="Hide comments" variant="ghost" size="sm" onClick={()=>setNotes(false)}><Icon name="x" size={15}/></IconButton>
      </div>
      <Textarea label="Add a comment" rows={3} value={nota} onChange={e=>setNota(e.target.value)}
        placeholder="What should change in this artwork?"/>
      <div><Button size="sm" variant="outline" disabled={!nota.trim()} onClick={comentar}>Post comment</Button></div>
      <div>{hilo.map((c,i)=>
        <div key={i} style={{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 0",borderBottom:"1px solid var(--gray-100)"}}>
          <Avatar name={c.who} size="sm"/>
          <div style={{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2}}>
            <span style={{fontSize:13}}>{c.text}</span>
            <span style={{fontSize:11,color:"var(--text-subtle)"}}>{c.who} · {c.when}</span>
          </div>
        </div>)}</div>
    </Card>}

    {history&&<div style={{display:"flex",flexDirection:"column",gap:12}}>
      <div style={{display:"flex",alignItems:"center",gap:12}}>
        <span style={{flex:1,fontSize:13,fontWeight:600,color:"var(--text-subtle)"}}>Template history</span>
        <span style={{fontSize:12,color:"var(--text-muted)"}}>3</span>
        <IconButton label="Sort history" variant="ghost" size="sm"><Icon name="arrow-up-down" size={15}/></IconButton>
        <IconButton label="Hide history" variant="ghost" size="sm" onClick={()=>setHistory(false)}><Icon name="x" size={15}/></IconButton>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(180px,1fr))",gap:16}}>
        <HistoryTile label="Reference template" note="Template 4658" selected={pick==="Reference template"} onClick={()=>setPick("Reference template")}/>
        <HistoryTile label="Creation 02" note="Today, 10:24" selected={pick==="Creation 02"} onClick={()=>setPick("Creation 02")}/>
        <HistoryTile label="Creation 01" note="Today, 09:58" selected={pick==="Creation 01"} onClick={()=>setPick("Creation 01")}/>
      </div>
    </div>}

    {toast&&<div style={{position:"fixed",left:"50%",transform:"translateX(-50%)",bottom:24,zIndex:30}}>
      <Toast tone="dark" title={"Exporting "+toast.fmt}
        message={toast.crop?"Trimmed to the artwork bounds. Your file will download in a moment.":"Full canvas. Your file will download in a moment."}
        onDismiss={()=>setToast("")}/></div>}
  </div>;
}
window.ArtTemplateBuilder=ArtTemplateBuilder;
