/**
 * rCrowdSurf Local-First Client
 *
 * Wraps the shared local-first stack for collaborative activity proposals
 * with swipe-based commitment, contributions, and threshold triggers.
 */

import { DocumentManager } from '../../shared/local-first/document';
import type { DocumentId } from '../../shared/local-first/document';
import { EncryptedDocStore } from '../../shared/local-first/storage';
import { DocSyncManager } from '../../shared/local-first/sync';
import { DocCrypto } from '../../shared/local-first/crypto';
import { crowdsurfSchema, crowdsurfDocId } from './schemas';
import type { CrowdSurfDoc, CrowdSurfPrompt, PromptSwipe, Contribution } from './schemas';

export class CrowdSurfLocalFirstClient {
	#space: string;
	#documents: DocumentManager;
	#store: EncryptedDocStore;
	#sync: DocSyncManager;
	#initialized = false;

	constructor(space: string, docCrypto?: DocCrypto) {
		this.#space = space;
		this.#documents = new DocumentManager();
		this.#store = new EncryptedDocStore(space, docCrypto);
		this.#sync = new DocSyncManager({
			documents: this.#documents,
			store: this.#store,
		});
		this.#documents.registerSchema(crowdsurfSchema);
	}

	get isConnected(): boolean { return this.#sync.isConnected; }

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const cachedIds = await this.#store.listByModule('crowdsurf', 'prompts');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<CrowdSurfDoc>(docId, crowdsurfSchema, binary);
		}
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		const wsUrl = `${proto}//${location.host}/ws/${this.#space}`;
		try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[CrowdSurf] Working offline'); }
		this.#initialized = true;
	}

	async subscribe(): Promise<CrowdSurfDoc | null> {
		const docId = crowdsurfDocId(this.#space) as DocumentId;
		let doc = this.#documents.get<CrowdSurfDoc>(docId);
		if (!doc) {
			const binary = await this.#store.load(docId);
			doc = binary
				? this.#documents.open<CrowdSurfDoc>(docId, crowdsurfSchema, binary)
				: this.#documents.open<CrowdSurfDoc>(docId, crowdsurfSchema);
		}
		await this.#sync.subscribe([docId]);
		return doc ?? null;
	}

	getDoc(): CrowdSurfDoc | undefined {
		return this.#documents.get<CrowdSurfDoc>(crowdsurfDocId(this.#space) as DocumentId);
	}

	onChange(cb: (doc: CrowdSurfDoc) => void): () => void {
		return this.#sync.onChange(crowdsurfDocId(this.#space) as DocumentId, cb as (doc: any) => void);
	}

	onConnect(cb: () => void): () => void { return this.#sync.onConnect(cb); }

	// ── Prompt CRUD ──

	createPrompt(prompt: CrowdSurfPrompt): void {
		const docId = crowdsurfDocId(this.#space) as DocumentId;
		this.#sync.change<CrowdSurfDoc>(docId, `Create prompt: ${prompt.text}`, (d) => {
			d.prompts[prompt.id] = prompt;
		});
	}

	deletePrompt(promptId: string): void {
		const docId = crowdsurfDocId(this.#space) as DocumentId;
		this.#sync.change<CrowdSurfDoc>(docId, `Delete prompt`, (d) => {
			delete d.prompts[promptId];
		});
	}

	// ── Swiping ──

	swipe(promptId: string, participantDid: string, direction: 'right' | 'left', contribution?: Contribution): void {
		const docId = crowdsurfDocId(this.#space) as DocumentId;
		this.#sync.change<CrowdSurfDoc>(docId, `Swipe ${direction} on prompt`, (d) => {
			const prompt = d.prompts[promptId];
			if (!prompt) return;

			const swipeData: PromptSwipe = {
				direction,
				timestamp: Date.now(),
			};
			if (contribution) {
				swipeData.contribution = contribution;
			}

			prompt.swipes[participantDid] = swipeData;

			// Check trigger threshold
			const rightSwipes = Object.values(prompt.swipes).filter(s => s.direction === 'right').length;
			if (rightSwipes >= prompt.threshold && !prompt.triggered) {
				prompt.triggered = true;
			}
		});
	}

	getMySwipe(promptId: string, myDid: string): PromptSwipe | null {
		const doc = this.getDoc();
		return doc?.prompts?.[promptId]?.swipes?.[myDid] ?? null;
	}

	// ── Expiry ──

	markExpired(promptId: string): void {
		const docId = crowdsurfDocId(this.#space) as DocumentId;
		this.#sync.change<CrowdSurfDoc>(docId, `Mark prompt expired`, (d) => {
			if (d.prompts[promptId]) d.prompts[promptId].expired = true;
		});
	}

	async disconnect(): Promise<void> {
		await this.#sync.flush();
		this.#sync.disconnect();
	}
}
