/**
 * rDesign Local-First Client — syncs design state (pages + frames) via Automerge.
 */

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 { designSchema, designDocId } from './schemas';
import type { DesignDoc, DesignFrame, DesignPage } from './schemas';

export class DesignLocalFirstClient {
	#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(designSchema);
	}

	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('design', 'doc');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<DesignDoc>(docId, designSchema, binary);
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		try { await this.#sync.connect(`${proto}//${location.host}/ws/${this.#space}`, this.#space); } catch {}
		this.#initialized = true;
	}

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

	getDoc(): DesignDoc | undefined { return this.#documents.get<DesignDoc>(designDocId(this.#space) as DocumentId); }
	onChange(cb: (doc: DesignDoc) => void): () => void { return this.#sync.onChange(designDocId(this.#space) as DocumentId, cb as (doc: any) => void); }

	// ── Frame CRUD ──

	addFrame(frame: DesignFrame): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Add frame ${frame.id}`, (d) => {
			d.document.frames[frame.id] = { ...frame, createdAt: frame.createdAt || Date.now(), updatedAt: Date.now() };
		});
	}

	updateFrame(frameId: string, updates: Partial<DesignFrame>): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Update frame ${frameId}`, (d) => {
			const existing = d.document.frames[frameId];
			if (existing) {
				Object.assign(existing, updates, { updatedAt: Date.now() });
			}
		});
	}

	deleteFrame(frameId: string): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Delete frame ${frameId}`, (d) => {
			delete d.document.frames[frameId];
		});
	}

	// ── Page CRUD ──

	addPage(page: DesignPage): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Add page ${page.number}`, (d) => {
			d.document.pages[page.id] = page;
		});
	}

	updatePage(pageId: string, updates: Partial<DesignPage>): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Update page ${pageId}`, (d) => {
			const existing = d.document.pages[pageId];
			if (existing) Object.assign(existing, updates);
		});
	}

	// ── Document metadata ──

	setTitle(title: string): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Set title`, (d) => {
			d.document.title = title;
		});
	}

	// ── Bulk update from bridge state ──

	applyBridgeState(pages: DesignPage[], frames: DesignFrame[]): void {
		this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Sync from Scribus`, (d) => {
			// Update pages
			for (const page of pages) {
				d.document.pages[page.id] = page;
			}
			// Update frames — merge, don't replace, to preserve CRDT metadata
			for (const frame of frames) {
				const existing = d.document.frames[frame.id];
				if (existing) {
					Object.assign(existing, frame, { updatedAt: Date.now() });
				} else {
					d.document.frames[frame.id] = { ...frame, createdAt: Date.now(), updatedAt: Date.now() };
				}
			}
		});
	}

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