// admin.jsx — Back-office AUTOMOTORES OMEGA
const { useState, useEffect, useRef, useMemo } = React;

const ADMIN_PASSWORD = 'omega2026'; // Cambiable. En producción usar auth real.

// Icons reusados del sitio público
const AIcon = {
  Arrow: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  Plus: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>,
  Pencil: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>,
  Trash: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>,
  Check: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6L9 17l-5-5"/></svg>,
  X: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M18 6L6 18M6 6l12 12"/></svg>,
  Eye: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
  Upload: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>,
  Search: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.5-4.5"/></svg>,
  Download: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>,
  Logout: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/></svg>,
  Drag: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>,
  Car: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 17h14l-1.5-7H6.5L5 17zM7 17v2M17 17v2M9 14h6"/></svg>,
  Inbox: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M22 12h-6l-2 3h-4l-2-3H2M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>,
  Users: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/><circle cx="9" cy="7" r="4"/></svg>
};

const fmtPriceARS = (n) => n ? '$' + new Intl.NumberFormat('es-AR').format(Math.round(n)) : '—';
const fmtKm = (n) => n ? new Intl.NumberFormat('es-AR').format(n) + ' km' : '—';

// === LOGIN (Supabase email + password) ===
const LoginScreen = ({ onAuth }) => {
  const [email, setEmail] = useState('');
  const [pwd, setPwd] = useState('');
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr('');
    try {
      const _em = email.indexOf('@')<0 ? email.trim().toLowerCase()+'@automotoresomega.com' : email.trim(); await window.OMEGA_STORE.signIn(_em, pwd);
      onAuth();
    } catch (e) {
      setErr(e.message || 'Credenciales inválidas');
      setTimeout(() => setErr(''), 4000);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="login-logo">
          <img src="logo-omega.png" alt="OMEGA"/>
          <div className="login-logo-divider"/>
          <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--ink-dim)'}}>Back-office</div>
        </div>
        <h1>Acceso al panel</h1>
        <p>Iniciá sesión con tu cuenta OMEGA.</p>
        {window.OMEGA_STORE?.__local && (
          <div style={{marginBottom:24, padding:'12px 14px', background:'rgba(234,90,12,0.07)', borderLeft:'2px solid var(--accent)', fontFamily:'var(--mono)', fontSize:11, lineHeight:1.6, color:'var(--ink-dim)', letterSpacing:'0.04em'}}>
            <strong style={{color:'var(--ink)'}}>Modo local</strong> · datos guardados en este navegador.<br/>
            Acceso: <strong style={{color:'var(--accent-bright)'}}>admin@omega</strong> / <strong style={{color:'var(--accent-bright)'}}>omega2026</strong>
          </div>
        )}
        <form onSubmit={submit}>
          <label className="adm-input-label">Email</label>
          <input
            type="text" className="adm-input"
            value={email} onChange={(e)=>setEmail(e.target.value)}
            placeholder="vos@automotoresomega.com" autoFocus required
            style={{marginBottom:16}}
          />
          <label className="adm-input-label">Contraseña</label>
          <input
            type="password" className="adm-input"
            value={pwd} onChange={(e)=>setPwd(e.target.value)}
            placeholder="••••••••" required
          />
          {err && <div className="login-error">{err}</div>}
          <button className="btn btn-accent btn-lg btn-block" style={{marginTop:20}} type="submit" disabled={loading}>
            {loading ? 'Ingresando...' : 'Ingresar'} <AIcon.Arrow width="14" height="14"/>
          </button>
        </form>
      </div>
    </div>
  );
};

// === TOAST ===
const Toast = ({ msg, type, onClose }) => {
  useEffect(() => {
    const t = setTimeout(onClose, 3500);
    return () => clearTimeout(t);
  }, [onClose]);
  return (
    <div className={`adm-toast ${type||'success'}`}>
      {type === 'success' ? <AIcon.Check width="14" height="14"/> : <AIcon.X width="14" height="14"/>}
      {msg}
    </div>
  );
};

// === CONFIRM MODAL ===
const ConfirmModal = ({ title, msg, onConfirm, onCancel, confirmLabel = 'Confirmar' }) => (
  <div className="adm-modal-overlay" onClick={onCancel}>
    <div className="adm-modal" onClick={e=>e.stopPropagation()}>
      <h3>{title}</h3>
      <p>{msg}</p>
      <div className="adm-modal-actions">
        <button className="btn btn-ghost" onClick={onCancel}>Cancelar</button>
        <button className="btn btn-accent" onClick={onConfirm}>{confirmLabel}</button>
      </div>
    </div>
  </div>
);

// === DASHBOARD ===
const Dashboard = ({ vehicles, profile, onEdit, onNew, onDelete, onTogglePublished, onLogout, onTab }) => {
  const [q, setQ] = useState('');
  const [filterMarca, setFilterMarca] = useState('Todas');
  const [filterStatus, setFilterStatus] = useState('todos');
  const [confirm, setConfirm] = useState(null);

  const marcas = ['Todas', ...Array.from(new Set(vehicles.map(v => v.marca))).sort()];

  const filtered = useMemo(() => {
    return vehicles.filter(v => {
      if (filterMarca !== 'Todas' && v.marca !== filterMarca) return false;
      if (filterStatus === 'publicados' && v.draft) return false;
      if (filterStatus === 'borradores' && !v.draft) return false;
      if (filterStatus === 'sinfotos' && v.photos && v.photos.length > 0) return false;
      if (q && !(`${v.marca} ${v.modelo} ${v.patente||''}`.toLowerCase().includes(q.toLowerCase()))) return false;
      return true;
    });
  }, [vehicles, q, filterMarca, filterStatus]);

  const stats = useMemo(() => ({
    total: vehicles.length,
    publicados: vehicles.filter(v => !v.draft).length,
    sinFotos: vehicles.filter(v => !v.photos || v.photos.length === 0).length,
    valorTotal: vehicles.reduce((s,v) => s + (v.precio||0), 0)
  }), [vehicles]);

  return (
    <React.Fragment>
      <AdminTopBar profile={profile} active="vehiculos" onTab={onTab} onLogout={onLogout}/>

      <main className="adm-main">
        <div className="adm-pagehead">
          <div>
            <div className="eyebrow">Espejo en vivo · sistema.automotoresomega.com</div>
            <h1>Catálogo OMEGA</h1>
            <p style={{color:'var(--ink-dim)', marginTop:10, maxWidth:640, fontSize:14}}>
              Los autos se cargan y se dan de baja desde tu <strong style={{color:'var(--ink)'}}>sistema de gestión</strong>. Acá agregás las <strong style={{color:'var(--ink)'}}>fotos</strong> y los datos de vidriera para que se vean en la web.
            </p>
          </div>
        </div>

        <div className="adm-stats">
          <div className="adm-stat">
            <div className="adm-stat-label">Total en stock</div>
            <div className="adm-stat-value">{stats.total}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Publicados</div>
            <div className="adm-stat-value accent">{stats.publicados}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Sin fotos</div>
            <div className="adm-stat-value">{stats.sinFotos}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Valor de inventario</div>
            <div className="adm-stat-value" style={{fontSize:28, marginTop:14}}>{fmtPriceARS(stats.valorTotal)}</div>
          </div>
        </div>

        <div className="adm-toolbar">
          <div className="adm-search">
            <AIcon.Search width="14" height="14"/>
            <input type="text" placeholder="Buscar por marca, modelo o patente..." value={q} onChange={(e)=>setQ(e.target.value)}/>
          </div>
          <select className="adm-filter-select" value={filterMarca} onChange={(e)=>setFilterMarca(e.target.value)}>
            {marcas.map(m => <option key={m}>{m}</option>)}
          </select>
          <select className="adm-filter-select" value={filterStatus} onChange={(e)=>setFilterStatus(e.target.value)}>
            <option value="todos">Todos</option>
            <option value="publicados">Sólo publicados</option>
            <option value="borradores">Sólo borradores</option>
            <option value="sinfotos">Sin fotos</option>
          </select>
        </div>

        {filtered.length === 0 ? (
          <div className="adm-empty">
            <div className="eyebrow">Sin autos en stock</div>
            <h3>No hay autos para mostrar</h3>
            <p style={{color:'var(--ink-dim)'}}>Cuando cargues autos en el sistema de gestión (estado "en stock"), aparecen acá automáticamente para ponerles fotos.</p>
          </div>
        ) : (
          <table className="adm-table">
            <thead>
              <tr>
                <th style={{width:96}}>Foto</th>
                <th>Vehículo</th>
                <th>Año</th>
                <th>KM</th>
                <th>Precio</th>
                <th>Patente</th>
                <th>En la web</th>
                <th style={{textAlign:'right'}}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(v => (
                <tr key={v.id} className={`adm-row ${v.draft ? 'draft' : ''}`}>
                  <td>
                    {v.photos && v.photos.length > 0
                      ? <img className="adm-thumb" src={v.photos[0]} alt={v.modelo}/>
                      : <div className="adm-thumb-empty">SIN FOTO</div>}
                  </td>
                  <td>
                    <div className="adm-cell-title">{v.marca}</div>
                    <div className="adm-cell-sub">{v.modelo} · {v.color}</div>
                  </td>
                  <td className="adm-cell-mono">{v.anio || '—'}</td>
                  <td className="adm-cell-mono">{fmtKm(v.km)}</td>
                  <td className="adm-cell-mono" style={{color:'var(--ink)', fontFamily:'var(--serif)', fontSize:15, fontWeight:700}}>{fmtPriceARS(v.precio)}</td>
                  <td>{v.patente ? <span className="adm-pat">{v.patente}</span> : <span className="adm-cell-mono">—</span>}</td>
                  <td>
                    <button
                      className={`adm-status ${v.draft ? 'draft' : 'published'}`}
                      onClick={()=>onTogglePublished(v.id)}
                      style={{cursor:'pointer'}}
                      title={v.draft ? 'Oculto de la web · click para mostrar' : 'Visible en la web · click para ocultar'}
                    >
                      {v.draft ? 'Oculto' : 'Visible'}
                    </button>
                  </td>
                  <td>
                    <div className="adm-row-actions">
                      <button className="adm-icon-btn" title={v.photos && v.photos.length ? 'Editar fotos' : 'Agregar fotos'} onClick={()=>onEdit(v.id)}>
                        <AIcon.Pencil width="15" height="15"/>
                      </button>
                      {v.photos && v.photos.length > 0 && (
                        <button className="adm-icon-btn danger" title="Quitar fotos de la web" onClick={()=>setConfirm({id: v.id, label: `${v.marca} ${v.modelo}`})}>
                          <AIcon.Trash width="15" height="15"/>
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </main>

      {confirm && (
        <ConfirmModal
          title="Quitar fotos"
          msg={`¿Querés quitar las fotos de "${confirm.label}" de la web? El auto sigue en tu sistema; sólo se borran las fotos cargadas en el sitio.`}
          confirmLabel="Sí, quitar fotos"
          onConfirm={() => { onDelete(confirm.id); setConfirm(null); }}
          onCancel={() => setConfirm(null)}
        />
      )}
    </React.Fragment>
  );
};

// === TOP BAR compartida ===
const AdminTopBar = ({ profile, active, onTab, onLogout, extraActions }) => { const puede = (s) => profile?.role === 'admin' || (profile?.secciones || []).includes(s); return (
  <header className="adm-top">
    <div className="adm-top-row">
      <div className="adm-brand">
        <img src="logo-omega.png" alt="OMEGA"/>
        <div className="adm-brand-sub">Back-office <span className="accent">●</span></div>
      </div>
      <nav className="adm-tabs">
        {puede('web_vehiculos') && (<button className={`adm-tab ${active==='vehiculos'?'on':''}`} onClick={()=>onTab('vehiculos')}>
          <AIcon.Car width="14" height="14"/> Vehículos
        </button>)}
        {puede('web_consultas') && (<button className={`adm-tab ${active==='leads'?'on':''}`} onClick={()=>onTab('leads')}>
          <AIcon.Inbox width="14" height="14"/> Consultas
        </button>)}
        {puede('web_usuarios') && (
          <button className={`adm-tab ${active==='usuarios'?'on':''}`} onClick={()=>onTab('usuarios')}>
            <AIcon.Users width="14" height="14"/> Usuarios
          </button>
        )}
      </nav>
      <div className="adm-top-actions">
        <div className="adm-user">
          {profile?.nombre || profile?.email} · <span style={{color:'var(--accent-bright)'}}>{profile?.role}</span>
        </div>
        <a className="btn btn-ghost btn-sm" href="index.html" target="_blank">
          <AIcon.Eye width="13" height="13"/> Ver sitio
        </a>
        <button className="btn btn-ghost btn-sm" onClick={onLogout}>
          <AIcon.Logout width="13" height="13"/> Salir
        </button>
      </div>
    </div>
  </header>
); };

Object.assign(window, { LoginScreen, Dashboard, AdminTopBar, Toast, ConfirmModal, AIcon, fmtPriceARS, fmtKm, ADMIN_PASSWORD });
