import { EventEmitter } from 'node:events';
import type { WaAuthClient } from '../auth/WaAuthClient';
import type { WaAppStateMutationCoordinator } from './coordinators/WaAppStateMutationCoordinator';
import type { WaBotCoordinator } from './coordinators/WaBotCoordinator';
import type { WaBroadcastListCoordinator } from './coordinators/WaBroadcastListCoordinator';
import type { WaBusinessCoordinator } from './coordinators/WaBusinessCoordinator';
import type { WaEmailCoordinator } from './coordinators/WaEmailCoordinator';
import type { WaGroupCoordinator } from './coordinators/WaGroupCoordinator';
import type { WaLowLevelCoordinator } from './coordinators/WaLowLevelCoordinator';
import type { WaMessageCoordinator } from './coordinators/WaMessageCoordinator';
import type { WaMobileCoordinator } from './coordinators/WaMobileCoordinator';
import type { WaNewsletterCoordinator } from './coordinators/WaNewsletterCoordinator';
import type { WaPresenceCoordinator } from './coordinators/WaPresenceCoordinator';
import type { WaPrivacyCoordinator } from './coordinators/WaPrivacyCoordinator';
import type { WaProfileCoordinator } from './coordinators/WaProfileCoordinator';
import type { WaStatusCoordinator } from './coordinators/WaStatusCoordinator';
import type { WaClientExposedFromPlugins, WaClientPluginDefinition, WaClientPluginEventsFromPlugins } from './plugins/types';
import type { WaClientEventMap, WaClientOptions, WaIgnoreKey, WaIgnoreKeyPredicate } from './types';
import type { Logger } from '../infra/log/types';
import { type WaLogoutReason } from '../protocol/stream';
/** @internal Implementation backing the exported {@link WaClient}. */
declare class WaClientImpl extends EventEmitter {
    private readonly options;
    private readonly logger;
    private readonly stores;
    private readonly deps;
    private readonly appStateSync;
    private readonly mediaTransfer;
    private readonly writeBehind;
    private readonly observeEphemeralSetting;
    private connectPromise;
    private acceptingIncomingEvents;
    private activeIncomingHandlers;
    private readonly incomingHandlersDrainedWaiters;
    private disposePlugins;
    private readonly pluginInstallInput;
    /**
     * @param options Client configuration (store, transport, addons, history...).
     * @param logger  Optional structured logger. Defaults to a `ConsoleLogger('info')`.
     */
    constructor(options: WaClientOptions, logger?: Logger);
    private installPlugins;
    private runClientTooOldRecover;
    /** Strongly-typed `EventEmitter#on` over {@link WaClientEventMap}. */
    on<K extends keyof WaClientEventMap>(event: K, listener: WaClientEventMap[K]): this;
    on(event: string | symbol, listener: (...args: unknown[]) => void): this;
    /** Strongly-typed `EventEmitter#once` over {@link WaClientEventMap}. */
    once<K extends keyof WaClientEventMap>(event: K, listener: WaClientEventMap[K]): this;
    once(event: string | symbol, listener: (...args: unknown[]) => void): this;
    /** Strongly-typed `EventEmitter#off` over {@link WaClientEventMap}. */
    off<K extends keyof WaClientEventMap>(event: K, listener: WaClientEventMap[K]): this;
    off(event: string | symbol, listener: (...args: unknown[]) => void): this;
    /** Strongly-typed `EventEmitter#emit` over {@link WaClientEventMap}. */
    emit<K extends keyof WaClientEventMap>(event: K, payload: Parameters<WaClientEventMap[K]>[0]): boolean;
    emit(event: string | symbol, ...args: unknown[]): boolean;
    /**
     * Returns the current auth state snapshot (credentials, registration,
     * connection flag) – useful for resuming or inspecting the client.
     */
    getState(): {
        connected: boolean;
        registered: boolean;
        hasQr: boolean;
        hasPairingCode: boolean;
    };
    /**
     * Returns the credentials persisted for the current session, or `null` if
     * the client has not been paired yet.
     */
    getCredentials(): import("..").WaAuthCredentials | null;
    /**
     * Returns the measured skew between the local clock and the server, in
     * milliseconds, or `null` if no handshake has completed yet.
     */
    getClockSkewMs(): number | null;
    private bindNodeTransportEvents;
    private handleIncomingMessageEvent;
    /**
     * Kicks off the group-history bundle download when the incoming message
     * carries one. Fire-and-forget: the blob can be large, and the incoming
     * handler must not stall behind a CDN fetch.
     *
     * The download outlives the handler that started it, so it takes a slot of
     * its own in the drain accounting - `disconnect()` and `clearStoredState()`
     * must not flush or wipe the stores while a bundle is still writing.
     */
    private tryProcessGroupHistoryBundle;
    private queryWithContext;
    private handleIncomingFrame;
    /**
     * Opens the transport and runs the noise/auth handshake. If a connection
     * is already in flight, the in-flight promise is reused. Resolves once the
     * client is fully ready; pairing prompts are surfaced via the `auth_qr`
     * and `auth_pairing_code` events while this awaits.
     *
     * **First-time pairing:** the promise stays pending until the user scans a
     * QR or types the pairing code. Subscribe to `auth_qr` / `auth_pairing_code`
     * *before* awaiting – they fire while `connect()` is still running.
     *
     * @example
     * ```ts
     * // QR pairing (default – works headless)
     * client.on('auth_qr', ({ qr }) => console.log('scan:', qr))
     * client.on('auth_paired', ({ credentials }) => console.log('paired:', credentials.meJid))
     * await client.connect()
     *
     * // Link-code pairing – call requestPairingCode while connect() is running
     * void client.connect()
     * await new Promise((r) => client.once('auth_pairing_required', r))
     * const code = await client.auth.requestPairingCode('5511999999999')
     * console.log('enter code on phone:', code)
     * ```
     */
    connect(): Promise<void>;
    /**
     * Closes the transport gracefully: pauses incoming events, flushes the
     * write-behind persistence queue, disposes installed plugins, and emits a
     * `connection` close event with reason `client_disconnected`. Does not
     * clear stored credentials - call {@link connect} again to resume the same
     * session, which reinstalls the plugins. There is no built-in
     * auto-reconnect; subscribe to `connection: { status: 'close' }` and decide
     * your own backoff.
     */
    disconnect(): Promise<void>;
    /**
     * Drops matching inbound stanzas before any handler runs. Server still
     * gets the ack so it stops re-delivering. Returns an `unregister` function.
     *
     * Accepts either a declarative descriptor or a predicate. The descriptor
     * matches by `remoteJid`/`fromMe`/`id`/`participant` (PN ↔ LID alt-attrs
     * resolved automatically) and throws when no match field is given or
     * arrays are empty. The predicate receives a parsed
     * {@link WaIgnoreKeyContext} and returns `true` to drop the stanza.
     *
     * `category='peer'` messages from our own account (app-state key share,
     * history sync, PDO responses) are never dropped: they are protocol
     * traffic between our own devices, not chat messages.
     *
     * @example
     * ```ts
     * client.ignoreKey({ remoteJid: spammerJid })
     * client.ignoreKey({ fromMe: true, only: ['message'] })
     * client.ignoreKey((m) => m.kind === 'message' && isGroupJid(m.remoteJid ?? ''))
     * ```
     */
    ignoreKey(input: WaIgnoreKey | WaIgnoreKeyPredicate): () => void;
    /** Auth client: pairing, credentials, registration state. */
    get auth(): WaAuthClient;
    /** Message coordinator: send/receive, receipts, addons, media upload/download. */
    get message(): WaMessageCoordinator;
    /** Presence coordinator: own/peer presence subscriptions. */
    get presence(): WaPresenceCoordinator;
    /** Low-level coordinator: raw node send/query escape hatch. */
    get lowlevel(): WaLowLevelCoordinator;
    /** App-state mutation coordinator: chat-side settings (mute, pin, etc.). */
    get chat(): WaAppStateMutationCoordinator;
    /** Group coordinator: create/query/manage WhatsApp groups and communities. */
    get group(): WaGroupCoordinator;
    /** Status coordinator: status broadcast send and reactions. */
    get status(): WaStatusCoordinator;
    /**
     * Broadcast-list coordinator: list management and broadcast sends.
     * **Business-only** - the underlying app-state schema rejects regular
     * accounts. See {@link WaBroadcastListCoordinator}.
     */
    get broadcastList(): WaBroadcastListCoordinator;
    /** Newsletter coordinator: create/query/follow/admin/send for channels. */
    get newsletter(): WaNewsletterCoordinator;
    /** Privacy coordinator: privacy categories, blocklist, disallowed list. */
    get privacy(): WaPrivacyCoordinator;
    /** Profile coordinator: own/peer profile fields (picture, status, username). */
    get profile(): WaProfileCoordinator;
    /**
     * Business coordinator: business profile, verified-name lookups. Reads
     * work from any account; **writes (`editBusinessProfile`,
     * `updateCoverPhoto`, `deleteCoverPhoto`) are business-only** and throw
     * on regular accounts. See {@link WaBusinessCoordinator}.
     */
    get business(): WaBusinessCoordinator;
    /** Bot coordinator: Meta-AI bot profiles, prompt/chunk decryption. */
    get bot(): WaBotCoordinator;
    /**
     * Email coordinator: bind/unbind/verify email on the account.
     * **Mobile-only** - every method throws unless the client is connected
     * via `options.mobileTransport`. See {@link WaEmailCoordinator}.
     */
    get email(): WaEmailCoordinator;
    /**
     * Mobile coordinator: host and manage companion devices linked to this
     * mobile-primary account (link via QR or pairing code, list, revoke).
     * Requires a registered primary session. See {@link WaMobileCoordinator}.
     */
    get mobile(): WaMobileCoordinator;
    /**
     * Unpairs this companion device by removing it server-side. Requires an
     * authenticated session; throws when no `meJid` is present.
     *
     * **Does not** disconnect the socket or clear local stores by itself -
     * the server initiates the close after accepting the IQ, which surfaces
     * via a `connection` event with `isLogout: true`. That close handler is
     * what wipes the persisted state, honoring `options.logoutStoreClear`.
     * The {@link WaClient} instance is single-shot after logout: create a
     * fresh one (with a fresh `sessionId` or pre-cleared store) to re-pair.
     */
    logout(reason?: WaLogoutReason): Promise<void>;
    private clearStoredState;
    private tryEnterIncomingHandler;
    private leaveIncomingHandler;
    private pauseIncomingEventsAndWaitDrain;
    private notifyIncomingHandlersDrained;
    private handleError;
}
/**
 * A WhatsApp client instance: per-feature coordinator getters ({@link message},
 * {@link group}, {@link newsletter}, ...) plus typed `on`/`once`/`off`/`emit`.
 *
 * `TPluginEvents` carries the events of the plugins installed on this client.
 * Prefer deriving the precise type from the construction site (e.g.
 * `type AppClient = ReturnType<typeof createClient>`) over the bare `WaClient`,
 * which only knows the core events and no plugin getters.
 */
export interface WaClient<TPluginEvents = {}> extends WaClientImpl {
    on<K extends keyof (WaClientEventMap & TPluginEvents)>(event: K, listener: (WaClientEventMap & TPluginEvents)[K]): this;
    once<K extends keyof (WaClientEventMap & TPluginEvents)>(event: K, listener: (WaClientEventMap & TPluginEvents)[K]): this;
    off<K extends keyof (WaClientEventMap & TPluginEvents)>(event: K, listener: (WaClientEventMap & TPluginEvents)[K]): this;
    emit<K extends keyof (WaClientEventMap & TPluginEvents)>(event: K, payload: Parameters<Extract<(WaClientEventMap & TPluginEvents)[K], (...args: never[]) => unknown>>[0]): boolean;
}
/**
 * Constructor surface for {@link WaClient}. `new WaClient({ plugins })` infers the
 * exposed plugin getters (e.g. `client.voip`) from the plugin values passed:
 * no global type augmentation, so a getter exists only when its plugin is installed.
 */
export interface WaClientConstructor {
    new <const P extends readonly WaClientPluginDefinition[] = []>(options: Omit<WaClientOptions, 'plugins'> & {
        readonly plugins?: P;
    }, logger?: Logger): WaClient<WaClientPluginEventsFromPlugins<P>> & WaClientExposedFromPlugins<P>;
}
/**
 * Top-level WhatsApp client. Owns the transport, auth, signal, and per-feature
 * coordinators (accessible via getters such as {@link message}, {@link group},
 * {@link newsletter}, etc.) and re-emits every {@link WaClientEventMap} event.
 *
 * Lifecycle: construct with {@link WaClientOptions}, call {@link connect} to
 * open the socket, react to `connection`/`auth_qr`/`auth_pairing_code` events,
 * then use the coordinator getters to drive the session. Call {@link disconnect}
 * to shut down cleanly or {@link logout} to remove the companion device.
 *
 * Pass `plugins` to expose plugin getters and events on the returned client,
 * typed from the values you pass: e.g. `plugins: [voipPlugin()]` adds
 * `client.voip` and the `voip_*` events, and only then. See
 * {@link WaClientConstructor}.
 *
 * @example
 * ```ts
 * import { createPinoLogger, createStore, WaClient } from '..'
 * import { createSqliteStore } from '@zapo-js/store-sqlite'
 *
 * const store = createStore({
 *     backends: { sqlite: createSqliteStore({ path: '.auth/state.sqlite' }) },
 *     providers: {
 *         auth: 'sqlite',
 *         signal: 'sqlite',
 *         preKey: 'sqlite',
 *         session: 'sqlite',
 *         identity: 'sqlite',
 *         senderKey: 'sqlite',
 *         appState: 'sqlite',
 *         privacyToken: 'sqlite',
 *         messages: 'sqlite',
 *         threads: 'sqlite',
 *         contacts: 'sqlite'
 *     }
 * })
 *
 * const client = new WaClient(
 *     { store, sessionId: 'default' },
 *     await createPinoLogger({ level: 'info', pretty: true })
 * )
 *
 * client.on('auth_qr', ({ qr, ttlMs }) => console.log('scan:', qr, ttlMs))
 * client.on('connection', (event) => console.log('connection', event))
 * client.on('message', async (event) => {
 *     if (event.message?.conversation === 'ping') {
 *         await client.message.send(event.chatJid!, 'pong')
 *     }
 * })
 *
 * await client.connect()
 * ```
 */
export declare const WaClient: WaClientConstructor;
export {};
