/* ============================================================
   ADMIN · información del restaurante + reservas
   ============================================================ */

function BrandEditor() {
  const store = useStore();
  const [confirm, confirmNode] = useConfirm();
  const [f, setF] = useState(structuredClone(store.data.brand));
  const set = (k,v) => setF(s => ({...s,[k]:v}));
  const dirty = JSON.stringify(f) !== JSON.stringify(store.data.brand);

  const onLogo = async (e) => {
    const file = e.target.files[0]; if (!file) return;
    try { const url = await store.fileToDataURL(file, 400, 0.85); set('logo', url); } catch { store.toast('No se pudo cargar el logo','err'); }
  };

  return (
    <div>
      <div className="section-bar">
        <div>
          <h1 className="admin-h">Información del restaurante</h1>
          <p className="admin-sub">Datos de contacto, redes sociales, logo y reservas. Se muestran en la carta pública.</p>
        </div>
        <button className="btn" disabled={!dirty} onClick={()=>store.updateBrand(f)}><Icon name="save" size={16}/> Guardar cambios</button>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:20,alignItems:'start'}} className="brand-cols">
        <div className="card">
          <div className="card-h"><h3>Identidad</h3></div>
          <Field label="Nombre"><input className="input" value={f.name} onChange={e=>set('name',e.target.value)}/></Field>
          <Field label="Bajada / tagline"><input className="input" value={f.tagline} onChange={e=>set('tagline',e.target.value)}/></Field>
          <Field label="Sitio web"><input className="input" value={f.website} onChange={e=>set('website',e.target.value)}/></Field>
          <Field label="Logo" hint="cuadrado, se optimiza">
            <div style={{display:'flex',alignItems:'center',gap:12}}>
              <div className="lc-seal" style={{width:54,height:54,margin:0,fontSize:22}}>{f.logo?<img src={f.logo} style={{width:'100%',height:'100%',objectFit:'cover',borderRadius:14}}/>:'GC'}</div>
              <label className="btn ghost sm" style={{cursor:'pointer'}}><Icon name="upload" size={15}/> Subir logo<input type="file" accept="image/*" style={{display:'none'}} onChange={onLogo}/></label>
              {f.logo&&<button className="btn danger sm" onClick={()=>set('logo',null)}>Quitar</button>}
            </div>
          </Field>
        </div>

        <div className="card">
          <div className="card-h"><h3>Contacto</h3></div>
          <div className="row">
            <Field label="Teléfono"><input className="input" value={f.phone} onChange={e=>set('phone',e.target.value)}/></Field>
            <Field label="WhatsApp"><input className="input" value={f.whatsapp} onChange={e=>set('whatsapp',e.target.value)}/></Field>
          </div>
          <Field label="Correo"><input className="input" value={f.email} onChange={e=>set('email',e.target.value)}/></Field>
          <Field label="Dirección"><input className="input" value={f.address} onChange={e=>set('address',e.target.value)}/></Field>
          <Field label="Horario"><input className="input" value={f.hours} onChange={e=>set('hours',e.target.value)}/></Field>
        </div>

        <div className="card">
          <div className="card-h"><h3>Redes sociales</h3></div>
          <Field label="Instagram" hint="solo el usuario, sin @"><input className="input" value={f.instagram} onChange={e=>set('instagram',e.target.value)} placeholder="granchimu"/></Field>
          <Field label="Facebook"><input className="input" value={f.facebook} onChange={e=>set('facebook',e.target.value)} placeholder="granchimu"/></Field>
          <Field label="TikTok"><input className="input" value={f.tiktok} onChange={e=>set('tiktok',e.target.value)} placeholder="(opcional)"/></Field>
        </div>

        <div className="card">
          <div className="card-h"><h3>Reservas & servidor</h3></div>
          <div style={{marginBottom:16}}><Toggle on={f.reservationsOn} onChange={v=>set('reservationsOn',v)} label="Formulario de reserva activado"/></div>
          <Field label="Clave del servidor" hint="debe ser igual a $WRITE_KEY en data.php">
            <input className="input" value={f.serverKey||''} onChange={e=>set('serverKey',e.target.value)} placeholder="chimu2027"/>
          </Field>
          <p style={{fontSize:12,color:'var(--ink-faint)',margin:'-6px 0 0',lineHeight:1.5}}>Las claves de cada persona se gestionan en <b>Usuarios</b>. Esta clave es solo la que usa el sitio para guardar en el servidor.</p>
        </div>
      </div>

      <div className="card" style={{borderColor:(f.emailjs&&f.emailjs.enabled)?'color-mix(in srgb,var(--ok) 40%,var(--line))':'var(--line)'}}>
        <div className="card-h">
          <h3>Confirmación de reservas por correo</h3>
          <span className="chip" style={{color:(f.emailjs&&f.emailjs.enabled)?'var(--ok)':'var(--ink-faint)'}}>
            <Icon name={(f.emailjs&&f.emailjs.enabled)?'check':'alert'} size={14}/> {(f.emailjs&&f.emailjs.enabled)?'Activo':'Inactivo'}
          </span>
        </div>
        <p style={{color:'var(--ink-soft)',fontSize:13.5,margin:'0 0 16px',lineHeight:1.6}}>
          Activación rápida con <b>EmailJS</b> (sin servidor). Cuando un cliente reserva: recibe un correo de
          <b> “solicitud recibida — pendiente”</b> y a ti te llega un aviso. Apruebas o rechazas en <b>Reservas</b> y el
          cliente recibe automáticamente tu respuesta.
        </p>
        <div style={{marginBottom:16}}><Toggle on={!!(f.emailjs&&f.emailjs.enabled)} onChange={v=>set('emailjs',{...(f.emailjs||{}),enabled:v})} label="Activar confirmación por correo"/></div>
        <div className="row">
          <Field label="Public Key" hint="EmailJS → Account"><input className="input" value={(f.emailjs&&f.emailjs.publicKey)||''} onChange={e=>set('emailjs',{...(f.emailjs||{}),publicKey:e.target.value})} placeholder="xxxxxxxxxxxx"/></Field>
          <Field label="Service ID" hint="EmailJS → Email Services"><input className="input" value={(f.emailjs&&f.emailjs.serviceId)||''} onChange={e=>set('emailjs',{...(f.emailjs||{}),serviceId:e.target.value})} placeholder="service_xxxxx"/></Field>
          <Field label="Template ID" hint="EmailJS → Email Templates"><input className="input" value={(f.emailjs&&f.emailjs.templateId)||''} onChange={e=>set('emailjs',{...(f.emailjs||{}),templateId:e.target.value})} placeholder="template_xxxxx"/></Field>
        </div>
        <div style={{background:'var(--surface)',border:'1px solid var(--line)',borderRadius:'var(--radius-sm)',padding:'12px 14px',fontSize:12.5,color:'var(--ink-soft)',lineHeight:1.6}}>
          <b style={{color:'var(--ink)'}}>Cómo activarlo en 4 pasos:</b><br/>
          1. Crea una cuenta gratis en <b>emailjs.com</b> y conecta tu correo (Add Service).<br/>
          2. Crea un <b>Template</b> con estos campos: <b>To Email</b> = <code>{'{{to_email}}'}</code>, <b>Subject</b> = <code>{'{{subject}}'}</code>, <b>Content</b> = <code>{'{{message}}'}</code>.<br/>
          3. Copia tu <b>Public Key</b>, <b>Service ID</b> y <b>Template ID</b> y pégalos arriba.<br/>
          4. Activa el interruptor y pulsa <b>Guardar cambios</b>. ¡Listo!
        </div>
        <details style={{marginTop:12}}>
          <summary style={{cursor:'pointer',fontSize:13,color:'var(--ink-soft)',fontWeight:600}}>Alternativa avanzada: servidor PHP (reserva.php)</summary>
          <Field label="Endpoint de reservas (PHP)" hint="URL de reserva.php en tu hosting"><input className="input" value={f.reservationEndpoint||''} onChange={e=>set('reservationEndpoint',e.target.value)} placeholder="https://granchimu.cl/reserva.php"/></Field>
        </details>
      </div>

      <div className="card" style={{borderColor:'color-mix(in srgb,var(--danger) 25%,var(--line))',marginTop:4}}>
        <div className="card-h"><h3>Datos del sistema</h3></div>
        <p style={{color:'var(--ink-soft)',fontSize:13.5,margin:'0 0 14px',lineHeight:1.6}}>
          Los datos se guardan en este dispositivo/navegador. Exporta un respaldo con regularidad y úsalo para pasar la información a otro equipo.
        </p>
        <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
          <button className="btn ghost" onClick={store.exportData}><Icon name="download" size={16}/> Exportar respaldo</button>
          <label className="btn ghost" style={{cursor:'pointer'}}><Icon name="upload" size={16}/> Importar respaldo
            <input type="file" accept="application/json" style={{display:'none'}} onChange={e=>{const file=e.target.files[0];if(!file)return;const r=new FileReader();r.onload=()=>store.importData(r.result);r.readAsText(file);e.target.value='';}}/>
          </label>
          <button className="btn danger" onClick={async()=>{ if(await confirm({title:'Restablecer todo',message:'Se borrarán todos tus cambios y se restaurará la carta original. Esta acción se puede deshacer una vez.',danger:true,confirmText:'Restablecer'})) store.resetData(); }}><Icon name="reset" size={16}/> Restablecer datos</button>
        </div>
      </div>
      {confirmNode}
    </div>
  );
}

function ReservationsView() {
  const store = useStore();
  const [confirm, confirmNode] = useConfirm();
  const reservations = store.data.reservations || [];
  const [filter, setFilter] = useState('todas');
  const list = reservations.filter(r => filter==='todas' || r.status===filter);
  const fmt = (s) => { if(!s) return '—'; const d=new Date(s); return d.toLocaleString('es-CL',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'}); };
  const statusColor = {nueva:'var(--ocre-deep)',aprobada:'var(--ok)',rechazada:'var(--ink-faint)'};
  const decide = (r, approve) => {
    store.updateReservation(r.id, { status: approve?'aprobada':'rechazada' });
    const b = store.data.brand;
    if (r.email) {
      if (approve) store.sendMail({ to:r.email, subject:`Tu reserva en ${b.name} fue APROBADA`, message:`Hola ${r.nombre},\n\n¡Buenas noticias! Tu reserva fue APROBADA.\n\n• Fecha y hora: ${(r.fecha||'').replace('T',' ')}\n• Personas: ${r.personas}\n• Local: ${r.local}\n\nTe esperamos.\n${b.name}` }).then(ok=>ok&&store.toast('Correo de aprobación enviado'));
      else store.sendMail({ to:r.email, subject:`Tu reserva en ${b.name}`, message:`Hola ${r.nombre},\n\nLamentablemente no pudimos confirmar tu reserva para esa fecha/hora. Por favor contáctanos para buscar otra alternativa.\n\n${b.name}` }).then(ok=>ok&&store.toast('Correo de respuesta enviado'));
    }
  };

  return (
    <div>
      <div className="section-bar">
        <div>
          <h1 className="admin-h">Reservas</h1>
          <p className="admin-sub">Solicitudes recibidas desde la carta. {reservations.filter(r=>r.status==='nueva').length} nuevas.</p>
        </div>
        <div className="dash-tabs" style={{margin:0}}>
          {['todas','nueva','aprobada','rechazada'].map(s=>(
            <button key={s} className={'dash-tab'+(filter===s?' active':'')} onClick={()=>setFilter(s)} style={{textTransform:'capitalize'}}>{s}</button>
          ))}
        </div>
      </div>

      {list.length===0 ? <div className="card"><div className="empty">No hay reservas {filter!=='todas'?`(${filter})`:''} por ahora.</div></div> : (
        <div style={{display:'grid',gap:12}}>
          {list.map(r=>(
            <div key={r.id} className="card" style={{margin:0,padding:16}}>
              <div style={{display:'flex',justifyContent:'space-between',gap:12,flexWrap:'wrap',alignItems:'flex-start'}}>
                <div>
                  <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:4}}>
                    <span style={{fontFamily:'var(--font-display)',fontSize:19}}>{r.nombre}</span>
                    <span className="chip" style={{color:statusColor[r.status],fontSize:11,textTransform:'capitalize'}}>{r.status}</span>
                  </div>
                  <div style={{display:'flex',gap:16,flexWrap:'wrap',fontSize:13.5,color:'var(--ink-soft)'}}>
                    <span><Icon name="calendar" size={14} style={{verticalAlign:'-2px'}}/> {r.fecha?r.fecha.replace('T',' · '):'—'}</span>
                    <span><Icon name="users" size={14} style={{verticalAlign:'-2px'}}/> {r.personas} pers.</span>
                    <span><Icon name="utensils" size={14} style={{verticalAlign:'-2px'}}/> {r.local}</span>
                    <span><Icon name="phone" size={14} style={{verticalAlign:'-2px'}}/> {r.telefono}</span>
                    {r.email&&<span><Icon name="mail" size={14} style={{verticalAlign:'-2px'}}/> {r.email}</span>}
                  </div>
                  {r.comentario&&<div style={{fontSize:13,color:'var(--ink-soft)',marginTop:8,fontStyle:'italic'}}>“{r.comentario}”</div>}
                  <div style={{fontSize:11.5,color:'var(--ink-faint)',marginTop:6}}>Recibida {fmt(r.createdAt)}</div>
                </div>
                <div style={{display:'flex',gap:6}}>
                  {r.status!=='aprobada'&&<button className="btn soft sm" onClick={()=>decide(r,true)}><Icon name="check" size={14}/> Aprobar</button>}
                  {r.status!=='rechazada'&&<button className="btn ghost sm" onClick={()=>decide(r,false)}>Rechazar</button>}
                  <button className="iconbtn danger" onClick={async()=>{ if(await confirm({title:'Eliminar reserva',message:`¿Eliminar la reserva de ${r.nombre}?`,danger:true,confirmText:'Eliminar'})) store.deleteReservation(r.id); }}><Icon name="trash" size={16}/></button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      {confirmNode}
    </div>
  );
}

function UserModal({ user, onClose }) {
  const store = useStore();
  const editing = !!user;
  const [f, setF] = useState(user ? { ...user, password:'' } : { name:'', username:'', password:'', role:'editor', active:true });
  const set = (k,v) => setF(s => ({...s,[k]:v}));
  const save = () => {
    if (editing) {
      const patch = { name:f.name, username:f.username, role:f.role };
      if (f.password) patch.password = f.password;
      store.updateUser(user.id, patch);
    } else {
      store.addUser(f);
    }
    onClose();
  };
  const valid = f.name.trim() && f.username.trim() && (editing || f.password);
  return (
    <Modal title={editing ? 'Editar usuario' : 'Nuevo usuario'} onClose={onClose}
      footer={<>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={!valid} onClick={save}><Icon name="save" size={16}/> Guardar</button>
      </>}>
      <Field label="Nombre"><input className="input" value={f.name} autoFocus onChange={e=>set('name',e.target.value)} placeholder="Nombre y apellido"/></Field>
      <div className="row">
        <Field label="Usuario" hint="para iniciar sesión"><input className="input" value={f.username} onChange={e=>set('username',e.target.value)} placeholder="ej. cocina"/></Field>
        <Field label={editing?'Nueva clave':'Clave'} hint={editing?'vacío = no cambiar':''}><input className="input" type="text" value={f.password} onChange={e=>set('password',e.target.value)} placeholder="••••••"/></Field>
      </div>
      <Field label="Rol / perfil">
        <select className="select" value={f.role} onChange={e=>set('role',e.target.value)}>
          {Object.entries(store.ROLES).map(([k,v])=><option key={k} value={k}>{v.label}</option>)}
        </select>
      </Field>
      <div style={{fontSize:12.5,color:'var(--ink-soft)',background:'var(--surface)',border:'1px solid var(--line)',borderRadius:8,padding:'10px 12px',lineHeight:1.5}}>
        <b>Permisos del rol:</b> {(store.ROLES[f.role]||store.ROLES.editor).perms.join(' · ')}
      </div>
    </Modal>
  );
}

function UsersView() {
  const store = useStore();
  const [confirm, confirmNode] = useConfirm();
  const users = store.data.users || [];
  const [modal, setModal] = useState(null);
  const activeAdmins = users.filter(u => u.role==='admin' && u.active).length;
  const roleColor = { admin:'var(--clay)', editor:'var(--coffee)', reservas:'var(--ocre-deep)', caja:'var(--green)' };

  return (
    <div>
      <div className="section-bar">
        <div>
          <h1 className="admin-h">Usuarios y perfiles</h1>
          <p className="admin-sub">Crea cuentas para tu equipo y define qué puede ver y editar cada perfil.</p>
        </div>
        <button className="btn" onClick={()=>setModal({})}><Icon name="plus" size={16}/> Nuevo usuario</button>
      </div>

      <div style={{display:'grid',gap:10}}>
        {users.map(u => {
          const isMe = store.currentUser && store.currentUser.id === u.id;
          const role = store.ROLES[u.role] || store.ROLES.editor;
          return (
            <div key={u.id} className="card" style={{margin:0,padding:'14px 16px',opacity:u.active?1:.55}}>
              <div style={{display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
                <div style={{width:42,height:42,borderRadius:'50%',background:'var(--paper-2)',display:'grid',placeItems:'center',fontFamily:'var(--font-display)',fontSize:18,flexShrink:0}}>{(u.name||'?').charAt(0).toUpperCase()}</div>
                <div style={{flex:1,minWidth:160}}>
                  <div style={{fontWeight:700,fontSize:15,display:'flex',alignItems:'center',gap:8}}>{u.name} {isMe && <span className="chip" style={{fontSize:10,padding:'1px 7px'}}>tú</span>}</div>
                  <div style={{fontSize:13,color:'var(--ink-faint)'}}>@{u.username}</div>
                </div>
                <span className="chip" style={{color:roleColor[u.role]||'var(--ink-soft)'}}><Icon name="lock" size={13}/> {role.label}</span>
                <span className="chip" style={{color:u.active?'var(--ok)':'var(--ink-faint)'}}>{u.active?'Activo':'Inactivo'}</span>
                <div style={{display:'flex',gap:4}}>
                  <button className="iconbtn" title="Editar" onClick={()=>setModal({user:u})}><Icon name="edit" size={16}/></button>
                  <button className="iconbtn" title={u.active?'Desactivar':'Activar'} onClick={()=>{
                    if (u.active && u.role==='admin' && activeAdmins<=1) { store.toast('Debe quedar al menos un administrador activo','err'); return; }
                    store.updateUser(u.id,{active:!u.active});
                  }}><Icon name={u.active?'eyeoff':'eye'} size={16}/></button>
                  <button className="iconbtn danger" title="Eliminar" disabled={isMe} onClick={async()=>{
                    if (u.role==='admin' && activeAdmins<=1) { store.toast('No puedes eliminar al único administrador','err'); return; }
                    if(await confirm({title:'Eliminar usuario',message:`¿Eliminar a ${u.name} (@${u.username})?`,danger:true,confirmText:'Eliminar'})) store.deleteUser(u.id);
                  }}><Icon name="trash" size={16}/></button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="card" style={{marginTop:16,background:'var(--surface)'}}>
        <div style={{fontSize:13,color:'var(--ink-soft)',lineHeight:1.6}}>
          <b style={{color:'var(--ink)'}}>Perfiles disponibles:</b><br/>
          {Object.entries(store.ROLES).map(([k,v])=>(
            <div key={k} style={{marginTop:4}}>• <b>{v.label}:</b> {v.perms.join(', ')}</div>
          ))}
        </div>
      </div>

      {modal && <UserModal user={modal.user} onClose={()=>setModal(null)} />}
      {confirmNode}
    </div>
  );
}

Object.assign(window, { BrandEditor, ReservationsView, UsersView, UserModal });
