function ElementArt({ kind, w = 120, h = 66 }) {
  const box = { width:w, height:h, display:'flex', alignItems:'center', justifyContent:'center', overflow:'hidden' };
  if (kind==='band-teal') return <div style={box}><div style={{width:'88%',height:h*0.34,background:'var(--sitm-teal)',borderRadius:8}}></div></div>;
  if (kind==='band-navy') return <div style={box}><div style={{width:'88%',height:h*0.34,background:'var(--sitm-navy)',borderRadius:8}}></div></div>;
  if (kind==='wave-teal') return <div style={box}><svg viewBox="0 0 120 40" width={w*0.88} height={h*0.6}><path d="M0 25 Q 20 8 40 22 T 80 20 T 120 18 L 120 40 L 0 40 Z" fill="var(--sitm-teal)"/></svg></div>;
  if (kind==='arcs') return <div style={box}><svg viewBox="0 0 60 60" width={h*0.8} height={h*0.8} fill="none" stroke="var(--sitm-teal-deep)" strokeWidth="5" strokeLinecap="round"><path d="M22 38 a 10 10 0 0 0 0-16"/><path d="M28 46 a 20 20 0 0 0 0-32"/><path d="M34 54 a 30 30 0 0 0 0-48"/></svg></div>;
  if (kind==='dots-gold') return <div style={box}><div style={{display:'flex',gap:8}}>{[10,14,10].map((s,i)=><div key={i} style={{width:s,height:s,borderRadius:'50%',background:'var(--sitm-gold)',alignSelf:'center'}}></div>)}</div></div>;
  if (kind==='swash-pink') return <div style={box}><div style={{width:'70%',height:h*0.3,background:'rgba(240,130,180,.45)',borderRadius:h*0.15}}></div></div>;
  if (kind==='star-gold') return <div style={box}><svg viewBox="0 0 24 24" width={h*0.62} height={h*0.62}><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26" fill="var(--sitm-gold)"/></svg></div>;
  if (kind==='rule') return <div style={box}><svg viewBox="0 0 100 20" width={w*0.8} height={h*0.3} stroke="var(--sitm-navy)" strokeWidth="2.5" strokeLinecap="round"><line x1="5" y1="10" x2="95" y2="10"/><line x1="5" y1="3" x2="5" y2="17"/><line x1="95" y1="3" x2="95" y2="17"/></svg></div>;
  if (kind==='rockthis') return <div style={box}><span style={{fontFamily:"'Tomarik Poster'",color:'var(--sitm-navy)',fontSize:h*0.3,whiteSpace:'nowrap'}}>You'll Rock This!</span></div>;
  if (kind==='futuresono') return <div style={box}><span style={{fontFamily:"'Tomarik Brush'",color:'var(--sitm-teal-deep)',fontSize:h*0.3,whiteSpace:'nowrap'}}>future sonographer</span></div>;
  if (kind==='logo') return <div style={box}><img src="./assets/sitm-logo.png" alt="" style={{width:h*0.82,height:h*0.82}}/></div>;
  if (kind==='frame-dash') return <div style={box}><div style={{width:'78%',height:'72%',border:'2px dashed var(--sitm-teal)',borderRadius:10}}></div></div>;
  return <div style={box}></div>;
}
function CustomElementArt({ obj, w = 120, h = 66 }) {
  const pad = 8, sc = Math.min((w-pad)/obj.w, (h-pad)/obj.h, 1);
  return <div style={{width:w,height:h,display:'flex',alignItems:'center',justifyContent:'center',overflow:'hidden'}}>
    <div style={{width:obj.w,height:obj.h,transform:'scale('+sc+')',flex:'none',opacity:(obj.opacity!=null?obj.opacity:100)/100}}>
      {obj.type==='shape' && <div style={shapeStyle(obj)}></div>}
      {obj.type==='element' && <ElementArt kind={obj.kind} w={obj.w} h={obj.h}/>}
      {obj.type==='text' && <div style={{fontFamily:"'"+obj.font+"'",fontSize:obj.size,color:obj.color,fontWeight:obj.bold?700:'normal',fontStyle:obj.italic?'italic':'normal',textDecoration:obj.underline?'underline':'none',lineHeight:1.3,whiteSpace:'nowrap'}}>{obj.text}</div>}
    </div>
  </div>;
}
function ElementTile({ el, onClick, onDelete, small, extra }) {
  const [h,setH] = React.useState(false);
  return <div onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
    style={{background:'#fff',border:'1px solid var(--sitm-border)',borderRadius:10,padding:small?6:10,cursor:'pointer',position:'relative',textAlign:'center',
      boxShadow:h?'0 4px 12px rgba(62,71,97,.12)':'none',transition:'box-shadow .15s ease'}}>
    <div style={{background:'var(--sitm-bg-light-dim)',borderRadius:7,display:'flex',justifyContent:'center'}}>
      {el.obj ? <CustomElementArt obj={el.obj} w={small?120:170} h={small?60:92}/> : <ElementArt kind={el.kind} w={small?120:170} h={small?60:92}/>}
    </div>
    <div style={{fontSize:small?10.5:12.5,fontWeight:600,color:'var(--sitm-navy)',marginTop:small?4:8,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{el.name}</div>
    {!small && <div style={{fontSize:11,color:'var(--sitm-text)',marginTop:2}}>{el.cat}</div>}
    {(onDelete||extra) && <span style={{position:'absolute',top:6,right:6,opacity:h?1:0,transition:'opacity .15s ease',display:'flex',gap:5}}>{extra}{onDelete && <DeleteBtn onClick={()=>onDelete(el)}/>}</span>}
  </div>;
}
function MoveMenu({ el, cats, onMove }) {
  const [open,setOpen] = React.useState(false);
  return <span style={{position:'relative'}} onClick={e=>e.stopPropagation()}>
    <button title="Move to another category" onClick={()=>setOpen(!open)}
      style={{background:'#fff',border:'1px solid var(--sitm-border)',color:'var(--sitm-text)',cursor:'pointer',padding:'6px 8px',borderRadius:8,display:'inline-flex',alignItems:'center'}}>
      <Icon name="folder" size={14}/>
    </button>
    {open && <div style={{position:'absolute',top:'110%',right:0,zIndex:20,background:'#fff',border:'1px solid var(--sitm-border)',borderRadius:10,boxShadow:'0 8px 24px rgba(12,12,29,.15)',minWidth:170,overflow:'hidden'}}>
      <div style={{fontSize:10.5,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',color:'var(--sitm-teal-deep)',padding:'8px 12px 4px'}}>Move to</div>
      {cats.filter(c=>c!=='All'&&c!==el.cat).map(c=><button key={c} onClick={()=>{onMove(el,c);setOpen(false);}}
        style={{display:'block',width:'100%',textAlign:'left',background:'none',border:'none',cursor:'pointer',padding:'8px 12px',fontFamily:'var(--sitm-font-body)',fontSize:12.5,color:'var(--sitm-text)'}}>{c}</button>)}
    </div>}
  </span>;
}
function ManageCategoriesModal({ open, onClose, cats, counts, onAdd, onRename, onDelete, onMoveCat }) {
  const [newName,setNewName] = React.useState('');
  const real = cats.filter(c=>c!=='All');
  return <Modal open={open} onClose={onClose} width={480}>
    <H2 style={{fontSize:20}}>Your categories</H2>
    <Sub style={{marginTop:6,marginBottom:16}}>Rename, reorder, add, or delete. Deleting a category keeps its elements and moves them to the first category.</Sub>
    <div style={{border:'1px solid var(--sitm-border)',borderRadius:10,overflow:'hidden',marginBottom:14}}>
      {real.map((c,i)=><div key={c} style={{display:'flex',alignItems:'center',gap:8,padding:'9px 12px',borderTop:i?'1px solid var(--sitm-border)':'none'}}>
        <input value={c} onChange={e=>onRename(c,e.target.value)} style={{flex:1,fontFamily:'var(--sitm-font-body)',fontSize:13,fontWeight:500,color:'var(--sitm-text-price)',border:'1px solid transparent',borderRadius:6,padding:'5px 8px',outline:'none',background:'transparent'}}
          onFocus={e=>e.target.style.borderColor='var(--sitm-teal)'} onBlur={e=>e.target.style.borderColor='transparent'}/>
        <span style={{fontSize:11.5,color:'var(--sitm-text)',width:56,textAlign:'right'}}>{counts[c]||0} item{(counts[c]||0)===1?'':'s'}</span>
        <button disabled={i===0} onClick={()=>onMoveCat(c,-1)} style={{background:'none',border:'none',cursor:i===0?'default':'pointer',color:i===0?'var(--sitm-border)':'var(--sitm-text)',padding:3,display:'flex'}}><Icon name="chevR" size={14} style={{transform:'rotate(-90deg)'}}/></button>
        <button disabled={i===real.length-1} onClick={()=>onMoveCat(c,1)} style={{background:'none',border:'none',cursor:i===real.length-1?'default':'pointer',color:i===real.length-1?'var(--sitm-border)':'var(--sitm-text)',padding:3,display:'flex'}}><Icon name="chevR" size={14} style={{transform:'rotate(90deg)'}}/></button>
        <DeleteBtn onClick={()=>onDelete(c)} title={'Delete '+c}/>
      </div>)}
    </div>
    <div style={{display:'flex',gap:8}}>
      <input value={newName} onChange={e=>setNewName(e.target.value)} placeholder="New category name"
        style={{flex:1,fontFamily:'var(--sitm-font-body)',fontSize:13,padding:'8px 11px',border:'1px solid rgba(62,71,97,.2)',borderRadius:8,outline:'none',color:'var(--sitm-text)'}}/>
      <Btn size="sm" disabled={!newName.trim()} onClick={()=>{onAdd(newName.trim());setNewName('');}}>Add</Btn>
    </div>
    <div style={{display:'flex',justifyContent:'flex-end',marginTop:16}}><Btn kind="ghost" onClick={onClose}>Done</Btn></div>
  </Modal>;
}
function ElementsPage({ elements, onDeleteElement, go, cats, catApi, onMoveElement }) {
  const [q,setQ] = React.useState('');
  const [cat,setCat] = React.useState('All');
  const [manage,setManage] = React.useState(false);
  const counts = elements.reduce((m,e)=>{m[e.cat]=(m[e.cat]||0)+1;return m;},{});
  React.useEffect(()=>{ if(cat!=='All' && !cats.includes(cat)) setCat('All'); },[cats]);
  const list = elements.filter(e => (cat==='All'||e.cat===cat) && e.name.toLowerCase().includes(q.toLowerCase()));
  return <div style={{maxWidth:1240,margin:'0 auto',padding:'36px 28px 80px'}}>
    <PageHead kicker="Elements" title="Your element library"
      sub="Little pieces you can drop onto any page: header bands, waves, word art, your logo. To save your own, select something in the editor and choose Save as element."
      right={<span style={{display:'flex',gap:8}}><Btn kind="ghost" icon="folder" onClick={()=>setManage(true)}>Manage categories</Btn><Btn icon="pdf" onClick={()=>go('pdfpick')}>Open the editor</Btn></span>}/>
    <div style={{display:'flex',gap:10,marginBottom:20,alignItems:'center'}}>
      <SearchInput value={q} onChange={setQ} placeholder="Search elements" style={{width:260}}/>
      <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
        {cats.map(c => <button key={c} onClick={()=>setCat(c)} style={{fontFamily:'var(--sitm-font-body)',fontSize:12.5,fontWeight:500,padding:'8px 13px',cursor:'pointer',borderRadius:8,
          border:'1px solid '+(cat===c?'var(--sitm-teal)':'var(--sitm-border)'),background:cat===c?'rgba(97,189,183,.12)':'#fff',color:cat===c?'var(--sitm-teal-deep)':'var(--sitm-text)'}}>{c}</button>)}
      </div>
    </div>
    {list.length===0 ? <div style={{background:'#fff',border:'1px solid var(--sitm-border)',padding:'48px 20px',textAlign:'center',borderRadius:12}}>
      <Sub>Nothing matches that. Try another word or category.</Sub></div> :
    <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:14}}>
      {list.map(e => <ElementTile key={e.id} el={e} onDelete={onDeleteElement} extra={<MoveMenu el={e} cats={cats} onMove={onMoveElement}/>}/>)}
    </div>}
    <ManageCategoriesModal open={manage} onClose={()=>setManage(false)} cats={cats} counts={counts}
      onAdd={catApi.add} onRename={catApi.rename} onDelete={catApi.remove} onMoveCat={catApi.move}/>
  </div>;
}
function ElementsPanel({ elements, onPlace, onPlaceShape, onSaveNew, cats }) {
  const [q,setQ] = React.useState('');
  const [cat,setCat] = React.useState('All');
  const list = elements.filter(e => (cat==='All'||e.cat===cat) && e.name.toLowerCase().includes(q.toLowerCase()));
  return <div style={{display:'flex',flexDirection:'column',gap:10,height:'100%'}}>
    <SearchInput value={q} onChange={setQ} placeholder="Search"/>
    <span style={{position:'relative',display:'block'}}>
      <select value={cat} onChange={e=>setCat(e.target.value)} style={{width:'100%',appearance:'none',WebkitAppearance:'none',fontFamily:'var(--sitm-font-body)',fontSize:12,fontWeight:500,color:'var(--sitm-text)',padding:'7px 26px 7px 10px',background:'#fff',border:'1px solid var(--sitm-border)',outline:'none',cursor:'pointer',borderRadius:8}}>
        {cats.map(c=><option key={c} value={c}>{c}</option>)}
      </select>
      <span style={{position:'absolute',right:8,top:'50%',transform:'translateY(-50%)',pointerEvents:'none',color:'var(--sitm-text)'}}><Icon name="chevR" size={11} style={{transform:'rotate(90deg)'}}/></span>
    </span>
    <div style={{flex:1,overflow:'auto',display:'flex',flexDirection:'column',gap:8}}>
      {!q && cat==='All' && <div>
        <div style={{fontSize:10.5,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',color:'var(--sitm-teal-deep)',marginBottom:6}}>Basic shapes</div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:6}}>
          {CS_SHAPES.map(s=><button key={s.shape} title={s.name} onClick={()=>onPlaceShape(s.shape)}
            style={{background:'#fff',border:'1px solid var(--sitm-border)',borderRadius:8,cursor:'pointer',padding:'9px 0',display:'flex',alignItems:'center',justifyContent:'center',height:44}}>
            <div style={{width:s.shape==='line'?26:22,height:s.shape==='line'?5:22,...(()=>{const st=shapeStyle({shape:s.shape,fill:'var(--sitm-teal)'});delete st.width;delete st.height;return st;})()}}></div>
          </button>)}
        </div>
        <div style={{fontSize:10.5,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',color:'var(--sitm-teal-deep)',margin:'10px 0 6px'}}>Your elements</div>
      </div>}
      <div style={{display:'grid',gridTemplateColumns:'1fr',gap:8,alignContent:'start'}}>
        {list.map(e => <ElementTile key={e.id} el={e} small onClick={()=>onPlace(e)}/>)}
        {list.length===0 && <div style={{fontSize:11.5,color:'var(--sitm-text)',padding:'10px 2px'}}>Nothing matches that.</div>}
      </div>
    </div>
    <div style={{borderTop:'1px solid var(--sitm-border)',paddingTop:10}}>
      <Btn kind="ghost" size="sm" icon="spark" style={{width:'100%',justifyContent:'center'}} onClick={onSaveNew}>Save as element</Btn>
      <div style={{fontSize:10.5,lineHeight:1.5,color:'var(--sitm-text)',marginTop:7}}>Select something on the page first, then save it here to reuse it anywhere.</div>
    </div>
  </div>;
}
function PlacedElement({ p, onMove, onRemove }) {
  const [h,setH] = React.useState(false);
  const drag = (e) => {
    e.preventDefault();
    const sx = e.clientX - p.x, sy = e.clientY - p.y;
    const mm = (ev)=> onMove(p.id, ev.clientX - sx, ev.clientY - sy);
    const up = ()=>{ window.removeEventListener('mousemove',mm); window.removeEventListener('mouseup',up); };
    window.addEventListener('mousemove',mm); window.addEventListener('mouseup',up);
  };
  return <div onMouseDown={drag} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
    style={{position:'absolute',left:p.x,top:p.y,cursor:'grab',zIndex:5,outline:h?'2px solid var(--sitm-teal)':'none',outlineOffset:2,borderRadius:6}}>
    <ElementArt kind={p.kind} w={150} h={80}/>
    {h && <button onMouseDown={e=>e.stopPropagation()} onClick={()=>onRemove(p.id)}
      style={{position:'absolute',top:-10,right:-10,width:22,height:22,borderRadius:'50%',background:'var(--sitm-navy)',color:'#fff',border:'none',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',padding:0}}><Icon name="x" size={12}/></button>}
  </div>;
}
Object.assign(window, { ElementArt, CustomElementArt, ElementTile, ElementsPage, ElementsPanel, PlacedElement, MoveMenu, ManageCategoriesModal });
