const { useState, useEffect, useMemo, useCallback } = React;
const fmt = window.ElyStore.formatPrice;

const CATEGORIES = ["Verduras", "Frutas", "Almacén"];
const UNITS = ["kg", "unidad", "atado", "docena"];

const IconEdit = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 20h9M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
  </svg>
);
const IconTrash = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
  </svg>
);
const IconPlus = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 5v14M5 12h14" />
  </svg>
);
const IconSettings = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="3" />
    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
  </svg>
);
const IconSearch = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" />
  </svg>
);

function Login({ onLogin }) {
  const [password, setPassword] = useState("");
  const [error, setError] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (await window.ElyStore.loginAdmin(password)) {
      onLogin();
    } else {
      setError(true);
      setTimeout(() => setError(false), 1500);
    }
  };

  return (
    <div className="admin-login">
      <form className="admin-login__card" onSubmit={submit}>
        <img src="assets/logo-fresh-vertical.png" alt="Verdulería Fresh" />
        <h1>Panel admin</h1>
        <p>Ingresá la contraseña para administrar productos.</p>
        <label className="admin-label" htmlFor="pw">Contraseña</label>
        <input
          id="pw"
          type="password"
          className={"admin-input" + (error ? " admin-input--err" : "")}
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder={error ? "Contraseña incorrecta" : "•••••••••"}
          autoFocus
        />
        <button type="submit" className="admin-btn" style={{ width: "100%", marginTop: 16 }}>
          Ingresar
        </button>
        <div style={{ textAlign: "center", marginTop: 14 }}>
          <a href="index.html" style={{ color: "var(--color-text-muted)", fontSize: 13, textDecoration: "none" }}>
            ← Volver a la tienda
          </a>
        </div>
      </form>
    </div>
  );
}

function ProductModal({ initial, onClose, onSave }) {
  const isNew = !initial.id;
  const [form, setForm] = useState({
    id: initial.id || "",
    name: initial.name || "",
    category: initial.category || "Verduras",
    price: initial.price ?? "",
    unit: initial.unit || "kg",
    image: initial.image || "",
    active: initial.active !== false,
    offers: initial.offers || [],
  });

  const setField = (key, value) => setForm((f) => ({ ...f, [key]: value }));
  const addOffer    = () => setForm((f) => ({ ...f, offers: [...f.offers, { qty: "", price: "" }] }));
  const removeOffer = (i) => setForm((f) => ({ ...f, offers: f.offers.filter((_, idx) => idx !== i) }));
  const updateOffer = (i, key, val) => setForm((f) => {
    const offers = [...f.offers];
    offers[i] = { ...offers[i], [key]: val };
    return { ...f, offers };
  });

  const submit = (e) => {
    e.preventDefault();
    if (!form.name.trim()) return alert("El nombre es obligatorio");
    const price = Number(form.price);
    if (!Number.isFinite(price) || price < 0) return alert("Precio inválido");

    onSave({
      ...form,
      id: form.id || ("p-" + Date.now().toString(36)),
      name: form.name.trim(),
      price,
      image: form.image.trim(),
      offers: form.offers
        .map((o) => ({ qty: Number(o.qty), price: Number(o.price) }))
        .filter((o) => o.qty > 0 && o.price > 0),
    });
  };

  useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  return (
    <div className="admin-modal-overlay" onClick={onClose}>
      <form className="admin-modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
        <div className="admin-modal__header">
          <h2>{isNew ? "Nuevo producto" : "Editar producto"}</h2>
        </div>
        <div className="admin-modal__body">
          <div className="admin-modal__field">
            <label className="admin-label">Nombre</label>
            <input
              className="admin-input"
              value={form.name}
              onChange={(e) => setField("name", e.target.value)}
              placeholder="Ej: Tomate Perita"
              autoFocus
            />
          </div>

          <div className="admin-modal__field admin-modal__field--row">
            <div>
              <label className="admin-label">Categoría</label>
              <select
                className="admin-input"
                value={form.category}
                onChange={(e) => setField("category", e.target.value)}
              >
                {CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="admin-label">Unidad de medida</label>
              <select
                className="admin-input"
                value={form.unit}
                onChange={(e) => setField("unit", e.target.value)}
              >
                {UNITS.map((u) => <option key={u} value={u}>x {u}</option>)}
              </select>
            </div>
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">Precio (ARS)</label>
            <input
              className="admin-input"
              type="number"
              min="0"
              step="50"
              value={form.price}
              onChange={(e) => setField("price", e.target.value)}
              placeholder="1500"
            />
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">URL de la foto</label>
            <input
              className="admin-input"
              value={form.image}
              onChange={(e) => setField("image", e.target.value)}
              placeholder="https://…/foto.jpg"
            />
            {form.image && (
              <div style={{ marginTop: 8 }}>
                <img
                  src={form.image}
                  alt=""
                  style={{ width: 80, height: 80, objectFit: "cover", borderRadius: 8, border: "1px solid var(--color-border)" }}
                  onError={(e) => { e.currentTarget.style.opacity = "0.3"; }}
                />
              </div>
            )}
          </div>

          <div className="admin-modal__field" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <label className="admin-toggle">
              <input
                type="checkbox"
                checked={form.active}
                onChange={(e) => setField("active", e.target.checked)}
              />
              <span className="admin-toggle__slider"></span>
            </label>
            <span style={{ fontWeight: 600 }}>
              {form.active ? "Visible en la tienda" : "Oculto en la tienda"}
            </span>
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">🔥 Ofertas especiales</label>
            {form.offers.map((offer, i) => (
              <div key={i} style={{ display: "flex", gap: 8, marginBottom: 8, alignItems: "center" }}>
                <input
                  className="admin-input"
                  type="number" min="0" step="0.25"
                  value={offer.qty}
                  onChange={(e) => updateOffer(i, "qty", e.target.value)}
                  placeholder={`Cant. (${form.unit})`}
                  style={{ flex: 1 }}
                />
                <span style={{ color: "var(--color-text-muted)", flexShrink: 0 }}>→ $</span>
                <input
                  className="admin-input"
                  type="number" min="0" step="50"
                  value={offer.price}
                  onChange={(e) => updateOffer(i, "price", e.target.value)}
                  placeholder="Precio total"
                  style={{ flex: 1 }}
                />
                <button
                  type="button"
                  onClick={() => removeOffer(i)}
                  style={{ background: "none", border: "1.5px solid var(--color-border)", borderRadius: 8, padding: "6px 10px", cursor: "pointer", color: "var(--color-text-muted)", flexShrink: 0, fontSize: 14 }}
                >✕</button>
              </div>
            ))}
            <button type="button" className="admin-btn admin-btn--secondary" style={{ width: "100%", fontSize: 13 }} onClick={addOffer}>
              + Agregar oferta
            </button>
          </div>
        </div>

        <div className="admin-modal__footer">
          <button type="button" className="admin-btn admin-btn--secondary" onClick={onClose}>
            Cancelar
          </button>
          <button type="submit" className="admin-btn">
            {isNew ? "Crear producto" : "Guardar cambios"}
          </button>
        </div>
      </form>
    </div>
  );
}

function SettingsModal({ initial, onClose, onSave }) {
  const [form, setForm] = useState({
    storeName:      initial.storeName      || "",
    whatsappNumber: initial.whatsappNumber || "",
    address:        initial.address        || "",
    hours:          initial.hours          || "",
    comingSoon:     initial.comingSoon === true,
  });
  const [waError, setWaError] = useState("");

  const setField = (key, value) => setForm((f) => ({ ...f, [key]: value }));

  const validateWhatsapp = (raw) => {
    const clean = raw.replace(/\D/g, "");
    if (clean.length < 10 || clean.length > 15) {
      return { ok: false, clean, err: "Debe tener entre 10 y 15 dígitos (formato internacional sin +)" };
    }
    return { ok: true, clean, err: "" };
  };

  const submit = (e) => {
    e.preventDefault();
    if (!form.storeName.trim()) return alert("El nombre de la tienda es obligatorio");
    const wa = validateWhatsapp(form.whatsappNumber);
    if (!wa.ok) { setWaError(wa.err); return; }

    onSave({
      storeName:      form.storeName.trim(),
      whatsappNumber: wa.clean,
      address:        form.address.trim(),
      hours:          form.hours.trim(),
      comingSoon:     form.comingSoon,
    });
  };

  useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  return (
    <div className="admin-modal-overlay" onClick={onClose}>
      <form className="admin-modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
        <div className="admin-modal__header">
          <h2>Configuración de la tienda</h2>
        </div>
        <div className="admin-modal__body">
          <div className="admin-modal__field">
            <label className="admin-label">Nombre de la tienda</label>
            <input
              className="admin-input"
              value={form.storeName}
              onChange={(e) => setField("storeName", e.target.value)}
              placeholder="Verdulería Ely"
              autoFocus
            />
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">Número de WhatsApp</label>
            <input
              className={"admin-input" + (waError ? " admin-input--err" : "")}
              value={form.whatsappNumber}
              onChange={(e) => { setField("whatsappNumber", e.target.value); setWaError(""); }}
              placeholder="5492612345678"
              inputMode="numeric"
            />
            <div style={{ fontSize: 12, color: waError ? "var(--color-accent)" : "var(--color-text-muted)", marginTop: 6 }}>
              {waError || "Formato internacional sin + ni espacios. Ej Mendoza 5492612345678 · CABA 5491134567890"}
            </div>
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">Dirección</label>
            <input
              className="admin-input"
              value={form.address}
              onChange={(e) => setField("address", e.target.value)}
              placeholder="Av. Siempre Viva 1234, CABA"
            />
          </div>

          <div className="admin-modal__field">
            <label className="admin-label">Horarios de atención</label>
            <input
              className="admin-input"
              value={form.hours}
              onChange={(e) => setField("hours", e.target.value)}
              placeholder="Lun a Sáb · 8:00 a 20:00"
            />
          </div>

          <div className="admin-modal__field" style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", background: form.comingSoon ? "#fff3cd" : "var(--color-primary-soft)", borderRadius: "var(--radius-md)", border: form.comingSoon ? "2px solid var(--color-accent)" : "2px solid var(--color-primary-light)" }}>
            <label className="admin-toggle">
              <input
                type="checkbox"
                checked={form.comingSoon}
                onChange={(e) => setField("comingSoon", e.target.checked)}
              />
              <span className="admin-toggle__slider"></span>
            </label>
            <div>
              <span style={{ fontWeight: 700, fontSize: 14 }}>
                {form.comingSoon ? "🚧 Página en modo \"Próximamente\"" : "✅ Página visible al público"}
              </span>
              <div style={{ fontSize: 12, color: "var(--color-text-muted)", marginTop: 2 }}>
                {form.comingSoon ? "Los visitantes verán solo el mensaje de próxima apertura" : "Los visitantes ven el catálogo completo"}
              </div>
            </div>
          </div>
        </div>

        <div className="admin-modal__footer">
          <button type="button" className="admin-btn admin-btn--secondary" onClick={onClose}>
            Cancelar
          </button>
          <button type="submit" className="admin-btn">
            Guardar configuración
          </button>
        </div>
      </form>
    </div>
  );
}

function Dashboard({ onLogout }) {
  const [products, setProducts] = useState([]);
  const [config, setConfig]     = useState({ ...window.ELY_CONFIG });
  const [loaded, setLoaded]     = useState(false);
  const [busy, setBusy]         = useState(false);
  const [error, setError]       = useState(null);
  const [editing, setEditing]   = useState(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [query, setQuery]       = useState("");
  const [catFilter, setCatFilter] = useState("Todos");

  const mode = window.ElyStore.mode;

  useEffect(() => {
    const unsubP = window.ElyStore.subscribeProducts((list, err) => {
      if (err) setError(err.message || String(err));
      if (list) setProducts(list);
      setLoaded(true);
    });
    const unsubC = window.ElyStore.subscribeConfig((cfg, err) => {
      if (cfg) setConfig(cfg);
    });
    return () => { unsubP(); unsubC(); };
  }, []);

  const withBusy = useCallback(async (fn) => {
    setBusy(true);
    setError(null);
    try { await fn(); }
    catch (e) {
      console.error(e);
      setError(e.message || String(e));
      alert("Error: " + (e.message || e));
    }
    finally { setBusy(false); }
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return products
      .filter((p) => catFilter === "Todos" || p.category === catFilter)
      .filter((p) => !q || p.name.toLowerCase().includes(q));
  }, [products, query, catFilter]);

  const saveProduct = useCallback((data) => {
    withBusy(async () => {
      await window.ElyStore.saveProduct(data);
      setEditing(null);
    });
  }, [withBusy]);

  const deleteProduct = useCallback((id) => {
    const p = products.find((x) => x.id === id);
    if (!p) return;
    if (!confirm(`¿Eliminar "${p.name}"? Esta acción no se puede deshacer.`)) return;
    withBusy(async () => {
      await window.ElyStore.deleteProduct(id);
    });
  }, [products, withBusy]);

  const toggleActive = useCallback((id) => {
    const p = products.find((x) => x.id === id);
    if (!p) return;
    withBusy(async () => {
      await window.ElyStore.saveProduct({ ...p, active: !p.active });
    });
  }, [products, withBusy]);

  const saveConfig = useCallback((patch) => {
    withBusy(async () => {
      await window.ElyStore.saveConfig(patch);
      setSettingsOpen(false);
    });
  }, [withBusy]);

  const seedCatalog = useCallback(() => {
    const remote = mode === "remote";
    const msg = remote
      ? "Esto va a copiar los productos de muestra a Firestore. Si ya hay productos con los mismos IDs, se sobrescriben. ¿Continuar?"
      : "¿Restaurar el catálogo a los productos de muestra? Se perderán tus cambios.";
    if (!confirm(msg)) return;
    withBusy(async () => { await window.ElyStore.seedProducts(); });
  }, [mode, withBusy]);

  return (
    <div className="admin-shell">
      <header className="admin-header">
        <div className="admin-header__brand">
          <img src="assets/logo-icon.png" alt="" />
          <h1>Admin · {config.storeName}</h1>
        </div>
        <span className={"admin-mode admin-mode--" + mode} title={mode === "remote" ? "Conectado a Firebase Firestore" : "Firebase no configurado — datos solo en este dispositivo"}>
          {mode === "remote" ? "● Firebase" : "○ Modo local"}
        </span>
        <div className="admin-header__spacer" />
        <button
          className="admin-btn admin-btn--secondary"
          onClick={() => setSettingsOpen(true)}
          style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
          title="Editar nombre, WhatsApp, dirección y horarios"
        >
          <IconSettings /> Configuración
        </button>
        <a href="index.html" className="admin-btn admin-btn--secondary" style={{ textDecoration: "none", display: "inline-flex", alignItems: "center" }}>
          Ver tienda
        </a>
        <button className="admin-btn admin-btn--secondary" onClick={() => { window.ElyStore.logoutAdmin(); onLogout(); }}>
          Salir
        </button>
      </header>

      <div className="admin-body">
        <div className="admin-toolbar">
          <div className="ely-search" style={{ flex: 1, minWidth: 240 }}>
            <IconSearch />
            <input
              type="search"
              placeholder="Buscar producto…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
          </div>

          <select
            className="admin-input"
            style={{ width: "auto", paddingRight: 30 }}
            value={catFilter}
            onChange={(e) => setCatFilter(e.target.value)}
          >
            <option value="Todos">Todas las categorías</option>
            {CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
          </select>

          <button className="admin-btn" onClick={() => setEditing({})} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <IconPlus /> Nuevo producto
          </button>
        </div>

        <div style={{ display: "flex", alignItems: "center", marginBottom: 12 }}>
          <span className="admin-count">{filtered.length} producto{filtered.length === 1 ? "" : "s"}{busy && " · guardando…"}</span>
          <div style={{ flex: 1 }} />
          <button className="admin-btn admin-btn--danger" onClick={seedCatalog} disabled={busy} style={{ fontSize: 13 }}>
            {products.length === 0 ? "Cargar catálogo de muestra" : "Restaurar catálogo de muestra"}
          </button>
        </div>

        {error && (
          <div className="admin-error">⚠️ {error}</div>
        )}

        <div className="admin-table">
          <div className="admin-row admin-row--header">
            <div></div>
            <div>Producto</div>
            <div>Categoría</div>
            <div>Precio</div>
            <div>Visible</div>
            <div style={{ textAlign: "right" }}>Acciones</div>
          </div>

          {!loaded ? (
            <div className="admin-empty">Cargando productos…</div>
          ) : filtered.length === 0 ? (
            <div className="admin-empty">
              {products.length === 0 ? (
                <>
                  No hay productos todavía.{" "}
                  <button className="admin-btn" style={{ marginTop: 12, display: "inline-flex", alignItems: "center", gap: 6 }} onClick={seedCatalog} disabled={busy}>
                    Cargar catálogo de muestra
                  </button>
                </>
              ) : (
                <>No hay productos que coincidan. <button className="admin-btn admin-btn--danger" style={{ height: "auto", padding: 0 }} onClick={() => setEditing({})}>Crear el primero</button>.</>
              )}
            </div>
          ) : (
            filtered.map((p) => (
              <div key={p.id} className="admin-row" style={{ opacity: p.active ? 1 : 0.55 }}>
                <div className="admin-row__img">
                  {p.image && <img src={p.image} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} />}
                </div>
                <div className="admin-row__name">
                  {p.name}
                  <small>{p.unit}</small>
                </div>
                <div className="admin-row__category-cell">
                  <span className="admin-row__category">{p.category}</span>
                </div>
                <div className="admin-row__price-cell" style={{ fontWeight: 700 }}>
                  {fmt(p.price)}
                </div>
                <div className="admin-row__toggle-cell">
                  <label className="admin-toggle">
                    <input type="checkbox" checked={p.active} onChange={() => toggleActive(p.id)} />
                    <span className="admin-toggle__slider"></span>
                  </label>
                </div>

                  <div className="admin-row__meta">
                  <span className="admin-row__category">{p.category}</span>
                  <span style={{ fontWeight: 700, color: "var(--color-text)" }}>{fmt(p.price)}</span>
                  <label className="admin-toggle" style={{ marginLeft: "auto" }}>
                    <input type="checkbox" checked={p.active} onChange={() => toggleActive(p.id)} />
                    <span className="admin-toggle__slider"></span>
                  </label>
                </div>

                <div className="admin-row__actions">
                  <button className="admin-row__action" onClick={() => setEditing(p)} aria-label="Editar">
                    <IconEdit />
                  </button>
                  <button className="admin-row__action admin-row__action--danger" onClick={() => deleteProduct(p.id)} aria-label="Eliminar">
                    <IconTrash />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {editing !== null && (
        <ProductModal
          initial={editing}
          onClose={() => setEditing(null)}
          onSave={saveProduct}
        />
      )}

      {settingsOpen && (
        <SettingsModal
          initial={config}
          onClose={() => setSettingsOpen(false)}
          onSave={saveConfig}
        />
      )}
    </div>
  );
}

function AdminApp() {
  const [logged, setLogged] = useState(() => window.ElyStore.isAdminLoggedIn());
  return logged ? <Dashboard onLogout={() => setLogged(false)} /> : <Login onLogin={() => setLogged(true)} />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<AdminApp />);
