/* ============================================================
   ADMIN · login + editor de contenido
   ============================================================ */

/* ---- login ---- */
function LoginScreen({ onCancel }) {
  const { login, data, online } = useStore();
  const [user, setUser] = useState('');
  const [pass, setPass] = useState('');
  const [err, setErr] = useState(false);
  const go = () => { if (!login(user, pass)) { setErr(true); setPass(''); } };
  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="lc-seal">{data.brand.logo ? <img src={data.brand.logo} style={{width:'100%',height:'100%',objectFit:'cover',borderRadius:14}}/> : 'GC'}</div>
        <h2 style={{fontFamily:'var(--font-display)',fontWeight:400,fontSize:24,margin:'0 0 4px'}}>Panel de administración</h2>
        <p style={{color:'var(--ink-soft)',fontSize:13.5,margin:'0 0 22px'}}>Ingresa con tu usuario para gestionar las cartas, reservas y el dashboard.</p>
        <Field label="Usuario">
          <input className="input" value={user} autoFocus onChange={e=>{setUser(e.target.value);setErr(false);}} onKeyDown={e=>e.key==='Enter'&&go()} placeholder="admin" />
        </Field>
        <Field label="Clave">
          <input className="input" type="password" value={pass}
            onChange={e=>{setPass(e.target.value);setErr(false);}}
            onKeyDown={e=>e.key==='Enter'&&go()}
            placeholder="••••••••"
            style={err?{borderColor:'var(--danger)',boxShadow:'0 0 0 3px rgba(163,58,42,.12)'}:null} />
        </Field>
        {err && <div style={{color:'var(--danger)',fontSize:12.5,marginTop:-6,marginBottom:10}}>Usuario o clave incorrectos.</div>}
        <button className="btn block" onClick={go}><Icon name="lock" size={16}/> Entrar</button>
        <button className="btn ghost block" style={{marginTop:8}} onClick={onCancel}>Volver a la carta</button>
        <p style={{color:'var(--ink-faint)',fontSize:11.5,marginTop:16}}>
          Acceso inicial: <b>admin</b> / <b>chimu2027</b>
          <br/><span style={{color: online===true?'var(--ok)':'var(--ink-faint)'}}>{online===true?'● Conectado al servidor':'○ Modo local (sin servidor)'}</span>
        </p>
      </div>
    </div>
  );
}

/* ---- small name/subtitle prompt ---- */
function NamePrompt({ title, fields, initial, onSave, onClose }) {
  const [v, setV] = useState(initial || {});
  return (
    <Modal title={title} onClose={onClose}
      footer={<>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={!(v.name||'').trim() && fields.some(f=>f.key==='name'&&f.required!==false)} onClick={()=>onSave(v)}>Guardar</button>
      </>}>
      {fields.map(f => (
        <Field key={f.key} label={f.label} hint={f.hint}>
          {f.area
            ? <textarea className="textarea" value={v[f.key]||''} onChange={e=>setV(s=>({...s,[f.key]:e.target.value}))} placeholder={f.ph}/>
            : <input className="input" value={v[f.key]||''} autoFocus={f.key==='name'} onChange={e=>setV(s=>({...s,[f.key]:e.target.value}))} placeholder={f.ph}/>}
        </Field>
      ))}
    </Modal>
  );
}

/* ---- product editor ---- */
function ProductEditor({ carta, catId, subId, product, onClose }) {
  const store = useStore();
  const editing = !!product;
  const [f, setF] = useState(product ? structuredClone(product) : store.blankProduct());
  const [loc, setLoc] = useState({ catId, subId });
  const set = (k,v) => setF(s => ({...s,[k]:v}));

  const onPhoto = async (e) => {
    const file = e.target.files[0]; if (!file) return;
    try { const url = await store.fileToDataURL(file); set('photo', url); }
    catch { store.toast('No se pudo cargar la imagen','err'); }
  };
  const addVariant = () => set('variants', [...(f.variants||[]), { label:'', price:null }]);
  const setVariant = (i, k, val) => set('variants', f.variants.map((v,idx)=>idx===i?{...v,[k]:val}:v));
  const delVariant = (i) => set('variants', f.variants.filter((_,idx)=>idx!==i));

  const save = () => {
    const payload = {
      name:f.name.trim(), desc:(f.desc||'').trim(),
      price: f.price===''||f.price==null?null:Number(f.price),
      priceText: (f.priceText||'').trim() || null,
      cost: f.cost===''||f.cost==null?null:Number(f.cost),
      recipe:(f.recipe||'').trim(), photo:f.photo||null,
      featured:!!f.featured, active:f.active!==false,
      variants:(f.variants||[]).filter(v=>v.label.trim()).map(v=>({label:v.label.trim(), price:v.price===''||v.price==null?null:Number(v.price)})),
    };
    if (editing) {
      store.updateProduct(carta.id, catId, subId, product.id, payload);
      if (loc.catId !== catId || loc.subId !== subId) store.reassignProduct(carta.id, catId, subId, product.id, loc.catId, loc.subId);
    } else {
      store.addProduct(carta.id, loc.catId, loc.subId, payload);
    }
    onClose();
  };

  const margin = (f.price!=null && f.cost!=null && f.cost!=='') ? Number(f.price)-Number(f.cost) : null;

  return (
    <Modal wide title={editing ? 'Editar producto' : 'Nuevo producto'} onClose={onClose}
      footer={<>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={!f.name.trim()} onClick={save}><Icon name="save" size={16}/> Guardar producto</button>
      </>}>
      <Field label="Nombre"><input className="input" value={f.name} autoFocus onChange={e=>set('name',e.target.value)} placeholder="Nombre del producto"/></Field>
      <Field label="Descripción"><textarea className="textarea" value={f.desc} onChange={e=>set('desc',e.target.value)} placeholder="Ingredientes, preparación…"/></Field>
      <div className="row">
        <Field label="Precio" hint="$ CLP"><input className="input" type="number" value={f.price??''} onChange={e=>set('price',e.target.value)} placeholder="8900"/></Field>
        <Field label="Costo" hint="para ingeniería de menú"><input className="input" type="number" value={f.cost??''} onChange={e=>set('cost',e.target.value)} placeholder="opcional"/></Field>
      </div>
      {margin!=null && <div style={{fontSize:12.5,color:'var(--ink-soft)',marginTop:-6,marginBottom:12}}>Margen de contribución: <b style={{color:'var(--accent-deep)'}}>{store.money(margin)}</b> ({f.price>0?Math.round(margin/f.price*100):0}%)</div>}
      <Field label="Etiqueta de precio especial" hint='solo si no usa precio numérico, ej. "Consultar" o "+$800"'>
        <input className="input" value={f.priceText||''} onChange={e=>set('priceText',e.target.value)} placeholder="(opcional)"/>
      </Field>

      <div style={{display:'flex',gap:24,margin:'14px 0',flexWrap:'wrap'}}>
        <Toggle on={!!f.featured} onChange={v=>set('featured',v)} label="★ Recomendado de la casa" />
        <Toggle on={f.active!==false} onChange={v=>set('active',v)} label="Visible en la carta" />
      </div>

      {/* photo */}
      <Field label="Foto (opcional)" hint="se optimiza automáticamente">
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <div className="pa-thumb" style={{width:64,height:64}}>{f.photo ? <img src={f.photo}/> : <Icon name="image" size={22}/>}</div>
          <label className="btn ghost sm" style={{cursor:'pointer'}}><Icon name="upload" size={15}/> Subir foto<input type="file" accept="image/*" style={{display:'none'}} onChange={onPhoto}/></label>
          {f.photo && <button className="btn danger sm" onClick={()=>set('photo',null)}><Icon name="trash" size={15}/> Quitar</button>}
        </div>
      </Field>

      {/* recipe */}
      <Field label="Receta / ficha técnica" hint="uso interno, no se muestra al cliente">
        <textarea className="textarea" value={f.recipe||''} onChange={e=>set('recipe',e.target.value)} placeholder="Ingredientes, gramajes, pasos…"/>
      </Field>

      {/* variants */}
      <div className="field">
        <label>Variantes / tamaños <span className="hint">· ej. tortas por porción</span></label>
        {(f.variants||[]).map((v,i)=>(
          <div key={i} style={{display:'flex',gap:8,marginBottom:6}}>
            <input className="input" style={{flex:2}} value={v.label} onChange={e=>setVariant(i,'label',e.target.value)} placeholder="Mediana (8 porc.)"/>
            <input className="input" style={{flex:1}} type="number" value={v.price??''} onChange={e=>setVariant(i,'price',e.target.value)} placeholder="$"/>
            <button className="iconbtn danger" onClick={()=>delVariant(i)}><Icon name="trash" size={16}/></button>
          </div>
        ))}
        <button className="btn ghost sm" onClick={addVariant} style={{alignSelf:'flex-start'}}><Icon name="plus" size={15}/> Agregar variante</button>
      </div>

      {/* move to */}
      <Field label="Ubicación (categoría / subcategoría)">
        <div className="row">
          <select className="select" value={loc.catId} onChange={e=>{const c=carta.categories.find(x=>x.id===e.target.value);setLoc({catId:e.target.value,subId:c.subcats[0]?.id});}}>
            {carta.categories.map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <select className="select" value={loc.subId} onChange={e=>setLoc(s=>({...s,subId:e.target.value}))}>
            {(carta.categories.find(c=>c.id===loc.catId)?.subcats||[]).map(s=><option key={s.id} value={s.id}>{s.name||'(directo)'}</option>)}
          </select>
        </div>
      </Field>
    </Modal>
  );
}

/* ---- content editor ---- */
function ContentEditor() {
  const store = useStore();
  const { data } = store;
  const [confirm, confirmNode] = useConfirm();
  const [cartaId, setCartaId] = useState(data.cartas[0].id);
  const carta = data.cartas.find(c => c.id === cartaId);
  const [sel, setSel] = useState({ catId: carta.categories[0]?.id, subId: carta.categories[0]?.subcats[0]?.id });
  const [prompt, setPrompt] = useState(null);
  const [prodModal, setProdModal] = useState(null); // {product} or {} for new

  useEffect(() => {
    const c = data.cartas.find(c => c.id === cartaId);
    if (!c.categories.find(x=>x.id===sel.catId)) setSel({ catId:c.categories[0]?.id, subId:c.categories[0]?.subcats[0]?.id });
  }, [cartaId, data]);

  const cat = carta.categories.find(c => c.id === sel.catId);
  const sub = cat?.subcats.find(s => s.id === sel.subId);

  const theme = themeFor(cartaId);
  return (
    <div style={accentVars(cartaId)}>
      <div className="section-bar">
        <div>
          <h1 className="admin-h">Contenido de la carta</h1>
          <p className="admin-sub">Agrega, edita, ordena y elimina categorías, subcategorías y productos.</p>
        </div>
      </div>

      <div className="carta-pick panel" style={{marginBottom:18}}>
        {data.cartas.map(c => (
          <button key={c.id} className={cartaId===c.id?'active':''} onClick={()=>setCartaId(c.id)}
            style={cartaId===c.id?accentVars(c.id):null}>
            <Icon name={themeFor(c.id).icon} size={15} style={{verticalAlign:'-2px',marginRight:6}}/>{c.name}
          </button>
        ))}
      </div>

      <div className="tree-layout">
        {/* left: structure */}
        <div className="panel">
          <div className="panel-head"><h4>Estructura</h4>
            <button className="iconbtn" title="Agregar categoría" onClick={()=>setPrompt({type:'add-cat'})}><Icon name="plus" size={17}/></button>
          </div>
          <div className="panel-body">
            {carta.categories.map((c,ci) => (
              <div key={c.id} style={{marginBottom:4}}>
                <div className={'trow'+(sel.catId===c.id?' active':'')}>
                  <div className="tmove">
                    <button disabled={ci===0} onClick={()=>store.moveCategory(cartaId,c.id,-1)}><Icon name="chevup" size={13}/></button>
                    <button disabled={ci===carta.categories.length-1} onClick={()=>store.moveCategory(cartaId,c.id,1)}><Icon name="chevdown" size={13}/></button>
                  </div>
                  <span className="tname" onClick={()=>setSel({catId:c.id,subId:c.subcats[0]?.id})}>{c.name}</span>
                  <div className="tactions">
                    <button className="iconbtn" onClick={()=>setPrompt({type:'edit-cat',cat:c})}><Icon name="edit" size={15}/></button>
                    <button className="iconbtn danger" onClick={async()=>{ if(await confirm({title:'Eliminar categoría',message:`Se eliminará "${c.name}" y todos sus productos. ¿Continuar?`,danger:true,confirmText:'Eliminar'})) store.deleteCategory(cartaId,c.id); }}><Icon name="trash" size={15}/></button>
                  </div>
                </div>
                {sel.catId===c.id && (
                  <div style={{marginLeft:14,borderLeft:'1px solid var(--line)',paddingLeft:6,marginTop:2}}>
                    {c.subcats.map((s,si) => (
                      <div key={s.id} className={'trow'+(sel.subId===s.id?' active':'')} style={{padding:'6px 8px'}}>
                        <div className="tmove">
                          <button disabled={si===0} onClick={()=>store.moveSub(cartaId,c.id,s.id,-1)}><Icon name="chevup" size={12}/></button>
                          <button disabled={si===c.subcats.length-1} onClick={()=>store.moveSub(cartaId,c.id,s.id,1)}><Icon name="chevdown" size={12}/></button>
                        </div>
                        <span className="tname" style={{fontSize:13,fontWeight:500}} onClick={()=>setSel({catId:c.id,subId:s.id})}>{s.name||'(directo)'}</span>
                        <span className="tcount">{s.products.length}</span>
                        <div className="tactions">
                          <button className="iconbtn" onClick={()=>setPrompt({type:'edit-sub',cat:c,sub:s})}><Icon name="edit" size={14}/></button>
                          <button className="iconbtn danger" onClick={async()=>{ if(await confirm({title:'Eliminar subcategoría',message:`Se eliminará "${s.name||'(directo)'}" y sus ${s.products.length} productos.`,danger:true,confirmText:'Eliminar'})) store.deleteSub(cartaId,c.id,s.id); }}><Icon name="trash" size={14}/></button>
                        </div>
                      </div>
                    ))}
                    <button className="btn ghost sm" style={{margin:'4px 0 4px 8px'}} onClick={()=>setPrompt({type:'add-sub',cat:c})}><Icon name="plus" size={14}/> Subcategoría</button>
                  </div>
                )}
              </div>
            ))}
            <button className="btn soft sm block" style={{marginTop:8}} onClick={()=>setPrompt({type:'add-cat'})}><Icon name="plus" size={15}/> Nueva categoría</button>
          </div>
        </div>

        {/* right: products */}
        <div>
          <div className="crumb" style={{marginBottom:14}}>
            <b>{carta.name}</b><span className="sep"><Icon name="chevright" size={14}/></span>
            <span>{cat?.name||'—'}</span>
            {sub && <><span className="sep"><Icon name="chevright" size={14}/></span><span>{sub.name||'(directo)'}</span></>}
          </div>
          {sub ? (
            <>
              <div className="section-bar">
                <span className="chip"><Icon name="list" size={14}/> {sub.products.length} productos</span>
                <button className="btn sm" onClick={()=>setProdModal({})}><Icon name="plus" size={15}/> Agregar producto</button>
              </div>
              {sub.products.length===0 && <div className="empty">No hay productos aquí todavía.</div>}
              {sub.products.map((p,pi)=>(
                <div key={p.id} className={'prod-admin-row'+(p.active===false?' inactive':'')}>
                  <div className="tmove">
                    <button disabled={pi===0} onClick={()=>store.moveProduct(cartaId,cat.id,sub.id,p.id,-1)}><Icon name="chevup" size={14}/></button>
                    <button disabled={pi===sub.products.length-1} onClick={()=>store.moveProduct(cartaId,cat.id,sub.id,p.id,1)}><Icon name="chevdown" size={14}/></button>
                  </div>
                  <div className="pa-thumb">{p.photo?<img src={p.photo}/>:<Icon name={theme.icon} size={18}/>}</div>
                  <div className="pa-main">
                    <div className="pa-name">{p.featured&&<Icon name="star" size={13} fill style={{color:'var(--ocre-deep)'}}/>}{p.name}{p.active===false&&<span className="chip" style={{fontSize:10,padding:'1px 7px'}}>oculto</span>}</div>
                    {p.desc&&<div className="pa-meta">{p.desc}</div>}
                  </div>
                  <div className="pa-price">{p.priceText||(p.price!=null?store.money(p.price):(p.variants.length?`${p.variants.length} var.`:'—'))}</div>
                  <div style={{display:'flex',gap:2}}>
                    <button className="iconbtn" onClick={()=>setProdModal({product:p})}><Icon name="edit" size={16}/></button>
                    <button className="iconbtn danger" onClick={async()=>{ if(await confirm({title:'Eliminar producto',message:`¿Eliminar "${p.name}"?`,danger:true,confirmText:'Eliminar'})) store.deleteProduct(cartaId,cat.id,sub.id,p.id); }}><Icon name="trash" size={16}/></button>
                  </div>
                </div>
              ))}
            </>
          ) : <div className="empty">Selecciona o crea una subcategoría.</div>}
        </div>
      </div>

      {/* prompts */}
      {prompt?.type==='add-cat' && <NamePrompt title="Nueva categoría" fields={[{key:'name',label:'Nombre',ph:'DESAYUNOS'},{key:'subtitle',label:'Subtítulo (opcional)',ph:'breve descripción'}]} onClose={()=>setPrompt(null)} onSave={v=>{store.addCategory(cartaId,v);setPrompt(null);}}/>}
      {prompt?.type==='edit-cat' && <NamePrompt title="Editar categoría" initial={{name:prompt.cat.name,subtitle:prompt.cat.subtitle}} fields={[{key:'name',label:'Nombre'},{key:'subtitle',label:'Subtítulo'}]} onClose={()=>setPrompt(null)} onSave={v=>{store.updateCategory(cartaId,prompt.cat.id,v);setPrompt(null);}}/>}
      {prompt?.type==='add-sub' && <NamePrompt title="Nueva subcategoría" fields={[{key:'name',label:'Nombre',hint:'déjalo vacío para productos directos',required:false,ph:'Brunch'}]} onClose={()=>setPrompt(null)} onSave={v=>{store.addSub(cartaId,prompt.cat.id,v);setPrompt(null);}}/>}
      {prompt?.type==='edit-sub' && <NamePrompt title="Editar subcategoría" initial={{name:prompt.sub.name}} fields={[{key:'name',label:'Nombre',required:false}]} onClose={()=>setPrompt(null)} onSave={v=>{store.updateSub(cartaId,prompt.cat.id,prompt.sub.id,v);setPrompt(null);}}/>}

      {prodModal && <ProductEditor carta={carta} catId={sel.catId} subId={sel.subId} product={prodModal.product} onClose={()=>setProdModal(null)} />}
      {confirmNode}
    </div>
  );
}

Object.assign(window, { LoginScreen, NamePrompt, ProductEditor, ContentEditor });
