// AdminDashboard.jsx — vista principal del panel admin
function AdminDashboard({ session }) {
  const [tab, setTab] = React.useState('articles');
  const [articles, setArticles] = React.useState([]);
  const [works, setWorks] = React.useState([]);
  const [contacts, setContacts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editing, setEditing] = React.useState(null);
  const [err, setErr] = React.useState('');

  const reloadAll = React.useCallback(async () => {
    setLoading(true);
    try {
      const [a, w, c] = await Promise.all([
        window.supabaseApi.fetchAllArticles(),
        window.supabaseApi.fetchAllWorks(),
        window.supabaseApi.fetchContacts(),
      ]);
      setArticles(a); setWorks(w); setContacts(c);
    } catch (e) {
      setErr(e.message || 'Error cargando');
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { reloadAll(); }, [reloadAll]);

  const toggleStatus = async (kind, item) => {
    const next = item.status === 'public' ? 'private' : 'public';
    try {
      if (kind === 'article') {
        await window.supabaseApi.setArticleStatus(item._row.id, next);
        window.dispatchEvent(new Event('articles:refresh'));
      } else {
        await window.supabaseApi.setWorkStatus(item._row.id, next);
        window.dispatchEvent(new Event('works:refresh'));
      }
      reloadAll();
    } catch (e) {
      alert(e.message || 'Error');
    }
  };

  const remove = async (kind, item) => {
    if (!confirm(`¿Borrar "${item.title}"? Esta acción no se puede deshacer.`)) return;
    try {
      if (kind === 'article') {
        await window.supabaseApi.deleteArticle(item._row.id);
        window.dispatchEvent(new Event('articles:refresh'));
      } else {
        await window.supabaseApi.deleteWork(item._row.id);
        window.dispatchEvent(new Event('works:refresh'));
      }
      reloadAll();
    } catch (e) {
      alert(e.message || 'Error');
    }
  };

  const toggleRead = async (contact) => {
    try {
      await window.supabaseApi.markContactRead(contact.id, !contact.read);
      setContacts((prev) => prev.map((c) => c.id === contact.id ? { ...c, read: !c.read } : c));
    } catch (e) {
      alert(e.message || 'Error');
    }
  };

  const removeContact = async (contact) => {
    if (!confirm(`¿Borrar el mensaje de "${contact.name}"?`)) return;
    try {
      await window.supabaseApi.deleteContact(contact.id);
      setContacts((prev) => prev.filter((c) => c.id !== contact.id));
    } catch (e) {
      alert(e.message || 'Error');
    }
  };

  const logout = async () => {
    await window.supabaseApi.signOut();
  };

  if (editing) {
    if (editing.kind === 'article') {
      return (
        <AdminArticleEditor
          article={editing.item}
          onCancel={() => setEditing(null)}
          onSaved={() => { setEditing(null); reloadAll(); }}
        />
      );
    }
    return (
      <AdminWorkEditor
        work={editing.item}
        articles={articles}
        onCancel={() => setEditing(null)}
        onSaved={() => { setEditing(null); reloadAll(); }}
      />
    );
  }

  const unread = contacts.filter((c) => !c.read).length;

  return (
    <div className="im-admin">
      <header className="im-admin-head">
        <div className="im-admin-brand">
          <span className="im-admin-logo">iM</span>
          <div>
            <div className="im-admin-title">Panel</div>
            <div className="im-admin-user">{session?.user?.email}</div>
          </div>
        </div>
        <nav className="im-admin-tabs">
          <button className={tab === 'articles' ? 'active' : ''} onClick={() => setTab('articles')}>
            Artículos ({articles.length})
          </button>
          <button className={tab === 'works' ? 'active' : ''} onClick={() => setTab('works')}>
            Trabajos ({works.length})
          </button>
          <button className={tab === 'contacts' ? 'active' : ''} onClick={() => setTab('contacts')}>
            Mensajes {unread > 0 && <span className="im-admin-badge">{unread}</span>}
          </button>
        </nav>
        <div className="im-admin-head-actions">
          <a href="#/" className="im-btn im-btn-ghost">Ver web</a>
          <button className="im-btn im-btn-ghost" onClick={logout}>Salir</button>
        </div>
      </header>

      {tab === 'contacts' ? (
        <>
          <div className="im-admin-toolbar">
            <h2>Mensajes de contacto</h2>
          </div>
          {err && <div className="im-admin-error">{err}</div>}
          {loading ? (
            <div className="im-admin-empty">Cargando…</div>
          ) : contacts.length === 0 ? (
            <div className="im-admin-empty">Aún no hay mensajes.</div>
          ) : (
            <table className="im-admin-table">
              <thead>
                <tr>
                  <th>Remitente</th>
                  <th>Mensaje</th>
                  <th>Fecha</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {contacts.map((c) => (
                  <tr key={c.id} className={c.read ? '' : 'im-contact-row-unread'}>
                    <td>
                      <div className="im-admin-cell-name">{c.name}</div>
                      <div className="im-admin-cell-slug">{c.email}</div>
                    </td>
                    <td className="im-contact-msg-cell">{c.message}</td>
                    <td className="im-admin-cell-date">
                      {window.supabaseApi.fmtDate(c.created_at)}
                    </td>
                    <td className="im-admin-row-actions">
                      <a href={`mailto:${c.email}?subject=Re: tu mensaje en isamunoz.com`} className="im-btn im-btn-ghost">
                        Responder
                      </a>
                      <button className="im-btn im-btn-ghost" onClick={() => toggleRead(c)}>
                        {c.read ? 'Marcar no leído' : 'Marcar leído'}
                      </button>
                      <button className="im-btn im-btn-danger" onClick={() => removeContact(c)}>Borrar</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </>
      ) : (
        <>
          <div className="im-admin-toolbar">
            <h2>{tab === 'articles' ? 'Artículos' : 'Trabajos'}</h2>
            <button className="im-btn im-btn-primary" onClick={() => setEditing({ kind: tab === 'articles' ? 'article' : 'work', item: null })}>
              + Nuevo {tab === 'articles' ? 'artículo' : 'trabajo'}
            </button>
          </div>
          {err && <div className="im-admin-error">{err}</div>}
          {loading ? (
            <div className="im-admin-empty">Cargando…</div>
          ) : (tab === 'articles' ? articles : works).length === 0 ? (
            <div className="im-admin-empty">
              Aún no hay {tab === 'articles' ? 'artículos' : 'trabajos'}. Crea el primero.
            </div>
          ) : (
            <table className="im-admin-table">
              <thead>
                <tr>
                  <th>Título</th>
                  <th>{tab === 'articles' ? 'Categoría' : 'Cliente'}</th>
                  <th>Estado</th>
                  <th>Actualizado</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {(tab === 'articles' ? articles : works).map((it) => (
                  <tr key={it._row.id}>
                    <td>
                      <div className="im-admin-cell-title">
                        {it.coverUrl && <img src={it.coverUrl} alt="" />}
                        <div>
                          <div className="im-admin-cell-name">{it.title}</div>
                          <div className="im-admin-cell-slug">/{it.slug}</div>
                        </div>
                      </div>
                    </td>
                    <td>{tab === 'articles' ? it.category : it.client}</td>
                    <td>
                      <button
                        className={`im-status-pill ${it.status} im-status-toggle`}
                        onClick={() => toggleStatus(tab === 'articles' ? 'article' : 'work', it)}
                        title="Cambiar visibilidad"
                      >
                        {it.status === 'public' ? 'Público' : 'Privado'}
                      </button>
                    </td>
                    <td className="im-admin-cell-date">
                      {window.supabaseApi.fmtDate(it._row.updated_at)}
                    </td>
                    <td className="im-admin-row-actions">
                      <button className="im-btn im-btn-ghost" onClick={() => setEditing({ kind: tab === 'articles' ? 'article' : 'work', item: it })}>Editar</button>
                      <button className="im-btn im-btn-danger" onClick={() => remove(tab === 'articles' ? 'article' : 'work', it)}>Borrar</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </>
      )}
    </div>
  );
}

window.AdminDashboard = AdminDashboard;
