/* ============================================================
   PURE SPA — AGENDA · App root
   Hash-routing, auth JWT, contexto de rol/permisos, host de modales.
   ============================================================ */
const AppCtx = React.createContext(null);
function useApp() { return React.useContext(AppCtx); }

const ROLE_LABELS = { OWNER: "Owner", ADMIN: "Admin", RECEPTION: "Recepción", STAFF: "Staff" };

function useHashRoute() {
  const [route, setRoute] = useState(window.location.hash.replace(/^#/, "") || "/admin/dashboard");
  useEffect(() => {
    const h = () => setRoute(window.location.hash.replace(/^#/, "") || "/admin/dashboard");
    window.addEventListener("hashchange", h); return () => window.removeEventListener("hashchange", h);
  }, []);
  const navigate = (to) => { window.location.hash = to; };
  return [route, navigate];
}

function ModalHost({ modal, close }) {
  if (!modal) return null;
  const map = {
    newBooking: window.NewBookingModal,
    detail: window.BookingDetailModal,
    move: window.MoveBookingModal,
    cancel: window.CancelBookingModal,
    block: window.BlockTimeModal,
    customer: window.CustomerModal,
    service: window.ServiceModal,
    payment: window.PaymentModal,
  };
  const Comp = map[modal.type];
  if (!Comp) return null;
  return <Comp {...modal.props} onClose={close} />;
}

// ── Vista de login ────────────────────────────────────────────
function LoginView({ onSuccess }) {
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [error, setError]       = useState("");
  const [loading, setLoading]   = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!email || !password) { setError("Ingresa email y contraseña."); return; }
    setLoading(true); setError("");
    try {
      const data = await PureApi.login(email, password);
      if (data?.user) {
        onSuccess(data.user);
        window.location.hash = "/admin/dashboard";
      } else {
        setError("Credenciales incorrectas.");
      }
    } catch (err) {
      setError(err.message || "Credenciales incorrectas.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ minHeight: "100vh", background: C.ivory, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ width: "100%", maxWidth: 380 }}>
        <div style={{ textAlign: "center", marginBottom: 36 }}>
          <img src="assets/logo-gold.png" style={{ height: 52, marginBottom: 12 }} alt="Pure Spa" />
          <div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.22em", textTransform: "uppercase", color: C.taupe }}>
            Panel interno
          </div>
        </div>

        <form onSubmit={handleSubmit} style={{ background: C.white, borderRadius: 18, padding: "32px 28px", boxShadow: "0 8px 40px rgba(43,37,32,0.08)" }}>
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: C.taupe, marginBottom: 6 }}>
              Email
            </label>
            <input
              type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="renata@purespa.cl" autoComplete="email" autoFocus
              style={{ width: "100%", padding: "10px 14px", borderRadius: 10, border: `1.5px solid ${C.line}`, fontFamily: "var(--font-body)", fontSize: 14, color: C.espresso, outline: "none", boxSizing: "border-box" }}
            />
          </div>

          <div style={{ marginBottom: 24 }}>
            <label style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: C.taupe, marginBottom: 6 }}>
              Contraseña
            </label>
            <input
              type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="••••••••" autoComplete="current-password"
              style={{ width: "100%", padding: "10px 14px", borderRadius: 10, border: `1.5px solid ${C.line}`, fontFamily: "var(--font-body)", fontSize: 14, color: C.espresso, outline: "none", boxSizing: "border-box" }}
            />
          </div>

          {error && (
            <div style={{ background: "#FEF2F2", border: "1px solid #FECACA", borderRadius: 8, padding: "10px 14px", marginBottom: 20,
              fontFamily: "var(--font-body)", fontSize: 13, color: "#B91C1C" }}>
              {error}
            </div>
          )}

          <button type="submit" disabled={loading}
            style={{ width: "100%", padding: "12px 0", background: loading ? C.taupe : C.espresso, color: C.ivory, border: "none", borderRadius: 10,
              fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", cursor: loading ? "not-allowed" : "pointer" }}>
            {loading ? "Ingresando…" : "Ingresar"}
          </button>
        </form>
      </div>
    </div>
  );
}

// ── Pantalla de carga ─────────────────────────────────────────
function LoadingScreen() {
  return (
    <div style={{ minHeight: "100vh", background: C.ivory, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div style={{ textAlign: "center" }}>
        <img src="assets/logo-gold.png" style={{ height: 44, opacity: 0.6 }} alt="Pure Spa" />
        <div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: C.taupe, marginTop: 16 }}>
          Cargando…
        </div>
      </div>
    </div>
  );
}

// ── App root ──────────────────────────────────────────────────
function App() {
  const [route, navigate] = useHashRoute();
  const [user, setUser]   = useState(null);
  const [loading, setLoading] = useState(true);
  const [version, setVersion] = useState(0);
  const [modal, setModal] = useState(null);

  // Verificar token al montar
  useEffect(() => {
    const token = localStorage.getItem("pure_token");
    if (!token) { setLoading(false); return; }
    PureApi.getMe()
      .then(data => { if (data?.user) setUser(data.user); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => PureApi.subscribe(() => setVersion(v => v + 1)), []);

  const role = user?.role ?? "STAFF";
  const can  = (perm) => PureCan(role, perm);
  const openModal  = (type, props = {}) => setModal({ type, props });
  const closeModal = () => setModal(null);
  const logout = () => { PureApi.clearToken(); setUser(null); navigate("/login"); };

  const ctx = {
    role, can, route, navigate, version, openModal, closeModal, logout,
    user:      user ? { name: user.name, role: ROLE_LABELS[role] ?? role } : null,
    roleLabel: ROLE_LABELS[role] ?? role,
    // setRole mantenido para compatibilidad con Shell (sin efecto real)
    setRole: () => {},
  };

  if (loading) return <LoadingScreen />;

  const isPublic = route.startsWith("/booking");
  const isLogin  = route === "/login" || !user;

  if (isPublic) {
    return (
      <AppCtx.Provider value={ctx}>
        <ToastProvider>
          <PublicBooking />
          {user && <a href="#/admin/dashboard" style={{ position: "fixed", bottom: 16, right: 16, zIndex: 50,
            display: "inline-flex", alignItems: "center", gap: 7, background: C.espresso, color: C.ivory,
            textDecoration: "none", padding: "10px 16px", borderRadius: 999, fontFamily: "var(--font-body)",
            fontSize: 10, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase",
            boxShadow: "0 8px 24px rgba(43,37,32,0.25)" }}>
            <Icon name="LayoutDashboard" size={14} color={C.gold} /> Panel interno
          </a>}
        </ToastProvider>
      </AppCtx.Provider>
    );
  }

  if (isLogin) {
    return (
      <AppCtx.Provider value={ctx}>
        <ToastProvider>
          <LoginView onSuccess={setUser} />
        </ToastProvider>
      </AppCtx.Provider>
    );
  }

  return (
    <AppCtx.Provider value={ctx}>
      <ToastProvider>
        <AdminShell />
        <ModalHost modal={modal} close={closeModal} />
      </ToastProvider>
    </AppCtx.Provider>
  );
}

// ROLE_USER mantenido para compatibilidad con RoleSelector en Shell.jsx
const ROLE_USER = {
  OWNER:     { name: "Owner",     role: "Fundadora" },
  ADMIN:     { name: "Admin",     role: "Administradora" },
  RECEPTION: { name: "Recepción", role: "Recepción" },
  STAFF:     { name: "Staff",     role: "Terapeuta" },
};

Object.assign(window, { App, useApp, AppCtx, ROLE_LABELS, ROLE_USER, LoginView, LoadingScreen });
