/* Organization-wide proposal skill management. Skill text is edited as plain text. */
function SkillEditorModal({skill,onClose,onSaved}) {
  const {createSkill,updateSkill,showToast}=useStore();
  const [name,setName]=React.useState(skill?.name||''),[kind,setKind]=React.useState(skill?.kind||'brief'),[version,setVersion]=React.useState(skill?.version||'v1'),[description,setDescription]=React.useState(skill?.description||'');
  const textFiles=Object.fromEntries(Object.entries(skill?.files||{'SKILL.md':{text:t('skill.defaultContent')}}).filter(([,v])=>typeof v.text==='string').map(([k,v])=>[k,v.text]));
  const [files,setFiles]=React.useState(textFiles),[file,setFile]=React.useState('SKILL.md'),[busy,setBusy]=React.useState(false),[error,setError]=React.useState('');
  const save=async()=>{setBusy(true);setError('');try{if(skill)await updateSkill(skill.id,{revision:skill.revision,name,version,description,files});else await createSkill({name,kind,version,description,content:files['SKILL.md']});showToast(t("skill.saved"));onSaved();}catch(e){setError(e.message);}finally{setBusy(false);}};
  return <Modal open onClose={()=>!busy&&onClose()} title={skill?t("skill.edit"):t("skill.add")} width={860} footer={<><Button variant="subtle" disabled={busy} onClick={onClose}>{t("btn.cancel")}</Button><Button variant="primary" disabled={busy||!name.trim()||!version.trim()||!files['SKILL.md']?.trim()} onClick={save}>{busy?t("common.savingMore"):t("common.saveMore")}</Button></>}>
    <div style={{display:'flex',gap:14,flexWrap:'wrap'}}>
      <label style={{flex:'2 1 260px',fontSize:12}}>{t("skill.name")}<input aria-label={t("skill.name")} value={name} maxLength={120} disabled={busy} onChange={e=>setName(e.target.value)} style={{...inputStyle,marginTop:5}}/></label>
      <label style={{flex:'1 1 120px',fontSize:12}}>{t("skill.version")}<input aria-label={t("skill.versionLabel")} value={version} maxLength={80} disabled={busy} onChange={e=>setVersion(e.target.value)} style={{...inputStyle,marginTop:5}}/></label>
      <label style={{flex:'1 1 150px',fontSize:12}}>{t("skill.purpose")}<select aria-label={t("skill.purposeLabel")} value={kind} disabled={busy||!!skill} onChange={e=>setKind(e.target.value)} style={{...inputStyle,marginTop:5}}><option value="brief">{t("skill.proposal")}</option><option value="design">{t("skill.designPurpose")}</option></select></label>
    </div>
    <label style={{display:'block',fontSize:12,marginTop:12}}>{t("settings.description")}<input aria-label={t("skill.descriptionLabel")} value={description} maxLength={1500} disabled={busy} onChange={e=>setDescription(e.target.value)} style={{...inputStyle,marginTop:5}}/></label>
    <label style={{display:'block',fontSize:12,marginTop:12}}>{t("skill.editFile")}<select aria-label={t("skill.editFileLabel")} value={file} disabled={busy} onChange={e=>setFile(e.target.value)} style={{...inputStyle,marginTop:5}}>{Object.keys(files).map(f=><option key={f}>{f}</option>)}</select></label>
    <textarea aria-label={t("skill.content")} value={files[file]||''} disabled={busy} onChange={e=>setFiles(v=>({...v,[file]:e.target.value}))} rows={15} spellCheck={false} style={{...inputStyle,marginTop:9,fontFamily:'ui-monospace,monospace',fontSize:12,lineHeight:1.7,resize:'vertical'}}/>
    <p style={{fontSize:11.5,color:'#8a91a0',marginTop:6}}>{t("skill.editHint")}</p>
    {error&&<div role="alert" style={{color:'#b91c1c',marginTop:8}}>{localizeMessage(error)}</div>}
  </Modal>;
}
function SkillUploadModal({target,onClose,onSaved}) {
  const {createSkill,updateSkill,showToast}=useStore();
  const [name,setName]=React.useState(target?.name||''),[kind,setKind]=React.useState(target?.kind||'brief'),[file,setFile]=React.useState(null),[busy,setBusy]=React.useState(false),[error,setError]=React.useState('');
  const upload=async()=>{if(!file)return;setBusy(true);setError('');try{
    if(file.size>16*1024*1024)throw Error(t("skill.fileTooBig"));
    const zip=await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=()=>reject(Error(t("skill.readFailed")));r.readAsDataURL(file);});
    if(target)await updateSkill(target.id,{zip,revision:target.revision});else await createSkill({name,kind,zip});showToast(t("skill.imported"));onSaved();
  }catch(e){setError(e.message);}finally{setBusy(false);}};
  return <Modal open title={target?t("skill.updateFiles"):t("skill.import")} width={560} onClose={()=>!busy&&onClose()} footer={<><Button disabled={busy} variant="subtle" onClick={onClose}>{t("btn.cancel")}</Button><Button variant="primary" onClick={upload} disabled={busy||!file||!target&&!name.trim()}>{busy?t("common.importingMore"):t("common.importMore")}</Button></>}>
    {target?<p style={{marginBottom:12,fontWeight:700}}>{target.name} · {target.version}</p>:<>
      <Field label={t("skill.name")}><input aria-label={t("skill.importName")} value={name} onChange={e=>setName(e.target.value)} maxLength={120} disabled={busy} style={inputStyle}/></Field>
      <Field label={t("skill.purpose")}><select aria-label={t("skill.importPurpose")} value={kind} onChange={e=>setKind(e.target.value)} disabled={busy} style={inputStyle}><option value="brief">{t("skill.proposal")}</option><option value="design">{t("skill.designPurpose")}</option></select></Field>
    </>}
    <input aria-label={t("skill.file")} type="file" accept=".skill,.zip" disabled={busy} onChange={e=>setFile(e.target.files?.[0]||null)} style={{maxWidth:'100%'}}/>
    <p style={{fontSize:12,color:'#8a91a0',marginTop:12}}>{t("skill.archiveHint")}{target?t("skill.replaceHint"):t("skill.appendHint")}</p>
    {error&&<div role="alert" style={{color:'#b91c1c',marginTop:10}}>{localizeMessage(error)}</div>}
  </Modal>;
}
function SkillsScreen() {
  const {skillCatalog,skillCatalogError,refreshSkillCatalog,loadSkill,createSkill,updateSkill,setDefaultSkill,skillDownloadUrl,showToast,isAdmin}=useStore();
  const [filter,setFilter]=React.useState('all'),[search,setSearch]=React.useState(''),[disabled,setDisabled]=React.useState(false),[editor,setEditor]=React.useState(null),[upload,setUpload]=React.useState(null),[busy,setBusy]=React.useState('');
  React.useEffect(()=>{refreshSkillCatalog().catch(()=>{});},[]);
  const act=async(id,fn)=>{setBusy(id);try{await fn();}catch(e){showToast(e.message,'x');}finally{setBusy('');}};
  if(!isAdmin)return <Page title={t("skill.title")}><p>{t("skill.adminOnly")}</p></Page>;
  const rows=(skillCatalog?.items||[]).filter(s=>(disabled||s.enabled)&&(filter==='all'||s.kind===filter)&&(`${s.name} ${s.description} ${s.version}`).toLowerCase().includes(search.toLowerCase()));
  const done=()=>{setEditor(null);setUpload(null);};
  return <Page title={t("skill.title")} right={<><Button icon="upload" disabled={!!busy} onClick={()=>setUpload({target:null})}>{t("skill.importArchive")}</Button><Button icon="plus" variant="primary" disabled={!!busy} onClick={()=>setEditor({skill:null})}>{t("skill.add")}</Button></>}>
    <div style={{marginBottom:20}}><h1 style={{fontSize:23,marginBottom:8}}>{t("skill.heading")}</h1><p style={{fontSize:13,color:'#8a91a0',lineHeight:1.8}}>{t("skill.headingHint")}</p></div>
    <div style={{display:'flex',gap:10,flexWrap:'wrap',alignItems:'center',marginBottom:18}}>
      <input aria-label={t("skill.search")} placeholder={t("skill.searchHint")} value={search} onChange={e=>setSearch(e.target.value)} style={{...inputStyle,width:280,maxWidth:'100%'}}/>
      <select aria-label={t("skill.filterPurpose")} value={filter} onChange={e=>setFilter(e.target.value)} style={{...inputStyle,width:160}}><option value="all">{t("skill.allPurposes")}</option><option value="brief">{t("skill.proposal")}</option><option value="design">{t("skill.designPurpose")}</option></select>
      <label style={{fontSize:12,color:'#7b828d',display:'flex',gap:6,alignItems:'center'}}><input type="checkbox" checked={disabled} onChange={e=>setDisabled(e.target.checked)}/>{t("skill.showDisabled")}</label>
    </div>
    {skillCatalogError&&<div role="alert" style={{marginBottom:14,color:'#b91c1c'}}>{localizeMessage(skillCatalogError)} <Button size="sm" onClick={()=>refreshSkillCatalog().catch(()=>{})}>{t("common.reload")}</Button></div>}
    {!skillCatalog&&!skillCatalogError&&<p>{t("skill.loading")}</p>}
    <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(min(100%,360px),1fr))',gap:16}}>{rows.map(s=>{
      const def=skillCatalog.defaults[s.kind]===s.id;
      return <article key={s.id} aria-label={s.name} style={{border:'1px solid #e7e9f1',borderRadius:16,background:'#fff',padding:20,opacity:s.enabled?1:.7,minWidth:0}}>
        <div style={{display:'flex',gap:7,alignItems:'center',flexWrap:'wrap',fontSize:11.5,marginBottom:10}}><span style={{color:s.kind==='brief'?'#4a5af0':'#0891b2',background:s.kind==='brief'?'#eeefff':'#e7f7fb',padding:'3px 8px',borderRadius:6}}>{s.kind==='brief'?t("skill.proposal"):t("skill.designPurpose")}</span>{def&&<span style={{color:'#16a34a'}}>{t("skill.default")}</span>}{!s.enabled&&<span>{t("skill.disabled")}</span>}<span style={{marginLeft:'auto',color:'#8a91a0'}}>{s.version} · rev {s.revision}</span></div>
        <h2 style={{fontSize:16,overflowWrap:'anywhere'}}>{s.name}</h2><p style={{fontSize:12.5,color:'#7b828d',lineHeight:1.8,marginTop:7,minHeight:42,overflowWrap:'anywhere'}}>{s.description||t("skill.noDescription")}</p>
        <div style={{fontSize:11.5,color:'#9aa1ab',margin:'10px 0 15px'}}>{s.fileCount}{t("skill.filesUpdated")}{s.updatedAt?.replace('T',' ')}</div>
        <div style={{display:'flex',gap:7,flexWrap:'wrap'}}>
          <Button size="sm" icon="edit" disabled={!!busy} onClick={()=>act(s.id,async()=>setEditor({skill:await loadSkill(s.id)}))}>{t("btn.edit")}</Button>
          <Button size="sm" disabled={!!busy} onClick={()=>act(s.id,async()=>{const r=await createSkill({cloneId:s.id,name:s.name.slice(0,110)+(" "+t("skill.copySuffix")+"")});setEditor({skill:await loadSkill(r.id)});})}>{t("skill.duplicate")}</Button>
          <Button size="sm" disabled={!!busy} onClick={()=>setUpload({target:s})}>{t("skill.fileUpdate")}</Button>
          <a href={skillDownloadUrl(s.id)} style={{fontSize:12,color:'#4a5af0',padding:'6px 4px'}}>{t("btn.download")}</a>
          {!def&&s.enabled&&<Button size="sm" disabled={!!busy} onClick={()=>act(s.id,async()=>{await setDefaultSkill(s.id);showToast(t("skill.defaultSaved"));})}>{t("skill.makeDefault")}</Button>}
          {!def&&<Button size="sm" variant="subtle" disabled={!!busy} onClick={()=>act(s.id,async()=>{await updateSkill(s.id,{revision:s.revision,enabled:!s.enabled});showToast(s.enabled?t("skill.disabledSaved"):t("skill.enabledSaved"));})}>{s.enabled?t("skill.disable"):t("skill.enable")}</Button>}
        </div>
      </article>;
    })}</div>
    {skillCatalog&&!rows.length&&<p style={{padding:28,color:'#8a91a0',textAlign:'center'}}>{t("skill.empty")}</p>}
    <p style={{marginTop:18,color:'#9aa1ab',fontSize:12}}>{t("skill.organizationHint")}</p>
    {editor&&<SkillEditorModal skill={editor.skill} onClose={done} onSaved={done}/>}
    {upload&&<SkillUploadModal target={upload.target} onClose={done} onSaved={done}/>}
  </Page>;
}
Object.assign(window,{SkillsScreen,SkillEditorModal,SkillUploadModal});
