/**
 * Demo community seeder for the r* ecosystem
 *
 * Creates/ensures a "demo" community with visibility: "public" (anon read+write)
 * and populates it with a welcome card + feature cards for each rApp.
 *
 * Shape IDs are deterministic so re-running is idempotent.
 */

import {
	addShapes,
	communityExists,
	createCommunity,
	getDocumentData,
	loadCommunity,
	markShapesSeeded,
	updateSpaceMeta,
} from "./community-store";

// ── Demo Space — Welcome + Feature Showcase ───────────────────────

// Grid layout: cards are 280px wide with 20px gap
const COL_W = 300; // card width + gap
const ROW_H = 260; // card height + gap
const CARD_W = 280;
const CARD_H = 240;
const START_X = 50;
const START_Y = 380; // below welcome card

/** Helper: grid position from col/row index */
function pos(col: number, row: number) {
	return { x: START_X + col * COL_W, y: START_Y + row * ROW_H };
}

const DEMO_SHAPES: Record<string, unknown>[] = [
	// ─── Welcome Card ───────────────────────────────────────────
	{
		id: "demo-welcome",
		type: "folk-markdown",
		x: 50, y: 50, width: 620, height: 300, rotation: 0,
		content: `# Welcome to rSpace

A **local-first operating system** for communities. Every tool syncs in real-time, works offline, and keeps your data under your control.

## How it works
- **Create a Space** — your community's home base
- **Add rApps** — modular tools that share data on the canvas
- **Invite members** — passkey login, no passwords or seed phrases
- **Everything syncs** — Automerge CRDTs, end-to-end encrypted

Drag shapes around, connect them with arrows, and build your community's workspace. Each card below is a tool you can use.`,
	},

	// ─── Category: Communicate ──────────────────────────────────
	{
		id: "demo-cat-communicate",
		type: "folk-markdown",
		x: START_X, y: START_Y - 40, width: 200, height: 30, rotation: 0,
		content: "## Communicate",
	},
	{
		id: "demo-tool-rchats",
		type: "folk-markdown",
		...pos(0, 0), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rChats
Real-time messaging for your space.

- **Channels** — topic-based group conversations
- **Direct messages** — private 1:1 threads
- **Reactions & threads** — keep discussions organized
- **File sharing** — drag-and-drop attachments`,
	},
	{
		id: "demo-tool-rforum",
		type: "folk-markdown",
		...pos(1, 0), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rForum
Threaded discussions for deeper topics.

- **Categories** — organize threads by topic
- **Rich text** — markdown formatting in posts
- **Threaded replies** — nested conversations
- **Search** — find past discussions`,
	},
	{
		id: "demo-tool-rinbox",
		type: "folk-markdown",
		...pos(2, 0), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rInbox
Shared email for your community.

- **Shared mailboxes** — team-readable inboxes
- **Multisig approval** — require sign-off before sending
- **Internal comments** — discuss emails before replying
- **Connect accounts** — link existing email`,
	},
	{
		id: "demo-tool-rmeets",
		type: "folk-markdown",
		...pos(3, 0), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rMeets
Video calls with built-in intelligence.

- **Instant meetings** — one-click video calls
- **Recordings** — auto-saved with transcripts
- **AI summaries** — key points from each meeting
- **Screen sharing** — present to your group`,
	},

	// ─── Category: Organize ─────────────────────────────────────
	{
		id: "demo-cat-organize",
		type: "folk-markdown",
		x: START_X, y: START_Y + ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Organize",
	},
	{
		id: "demo-tool-rtasks",
		type: "folk-markdown",
		...pos(0, 1), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rTasks
Kanban boards for project management.

- **Drag-and-drop** — move tasks across columns
- **Assignees & priority** — track who's doing what
- **Multiple boards** — separate projects per board
- **ClickUp sync** — import from external tools`,
	},
	{
		id: "demo-tool-rcal",
		type: "folk-markdown",
		...pos(1, 1), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rCal
Shared calendar with external sync.

- **Google Calendar sync** — two-way sync
- **ICS import** — upload from any calendar app
- **iCal subscriptions** — read-only feeds
- **Event creation** — shared community events`,
	},
	{
		id: "demo-tool-rschedule",
		type: "folk-markdown",
		...pos(2, 1), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSchedule
Automations and scheduled jobs.

- **Cron jobs** — recurring tasks on a schedule
- **Reminders** — email notifications
- **Visual workflows** — trigger-condition-action chains
- **Execution log** — full history of runs`,
	},
	{
		id: "demo-tool-rtime",
		type: "folk-markdown",
		...pos(3, 1), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rTime
Time banking for communities.

- **Pledge hours** — commit time to the pool
- **Track contributions** — log hours worked
- **Balance sheets** — see give/receive ratios
- **Community currency** — time as value exchange`,
	},

	// ─── Category: Create ───────────────────────────────────────
	{
		id: "demo-cat-create",
		type: "folk-markdown",
		x: START_X, y: START_Y + 2 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Create",
	},
	{
		id: "demo-tool-rdocs",
		type: "folk-markdown",
		...pos(0, 2), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rDocs
Rich-text collaborative notebooks.

- **Real-time editing** — multiple cursors, live sync
- **Import** — from Obsidian, Logseq, Notion, Google
- **Voice transcription** — dictate and auto-transcribe
- **AI assist** — writing help built in`,
	},
	{
		id: "demo-tool-rnotes",
		type: "folk-markdown",
		...pos(1, 2), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rNotes
Vault sync for Obsidian & Logseq.

- **ZIP upload** — import your entire vault
- **Browse & search** — explore notes by folder
- **Metadata sync** — tags, links, frontmatter
- **On-demand content** — files served from vault ZIP`,
	},
	{
		id: "demo-tool-rphotos",
		type: "folk-markdown",
		...pos(2, 2), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rPhotos
Photo albums and galleries.

- **Lightbox viewer** — full-screen with EXIF data
- **Albums** — organize by event or theme
- **Public galleries** — shareable links
- **Smart tags** — AI-powered face & object tagging`,
	},
	{
		id: "demo-tool-rtube",
		type: "folk-markdown",
		...pos(3, 2), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rTube
Video hosting for your community.

- **Upload & stream** — host your own videos
- **Playlists** — curate video collections
- **Channels** — organize by creator or topic
- **Embedded player** — share anywhere`,
	},

	// ─── Category: Govern ───────────────────────────────────────
	{
		id: "demo-cat-govern",
		type: "folk-markdown",
		x: START_X, y: START_Y + 3 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Govern",
	},
	{
		id: "demo-tool-rvote",
		type: "folk-markdown",
		...pos(0, 3), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rVote
Conviction voting and governance.

- **Proposals** — submit ideas for community vote
- **Conviction voting** — signal strength over time
- **Pairwise ranking** — Elo-style sortition
- **Results dashboard** — transparent outcomes`,
	},
	{
		id: "demo-tool-rgov",
		type: "folk-markdown",
		...pos(1, 3), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rGov
Governance decision circuits.

- **Visual circuits** — drag-and-drop governance flows
- **Multisig** — require multiple approvals
- **Quadratic voting** — diminishing returns voting
- **Amendment tracking** — version proposals`,
	},
	{
		id: "demo-tool-rchoices",
		type: "folk-markdown",
		...pos(2, 3), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rChoices
Group decision-making tools.

- **Spider charts** — multi-criteria radar visualization
- **Drag rankings** — drag-and-drop prioritization
- **Live polls** — real-time voting
- **CrowdSurf** — Tinder-style option swiping`,
	},
	{
		id: "demo-tool-rnetwork",
		type: "folk-markdown",
		...pos(3, 3), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rNetwork
CRM and relationship graphs.

- **Contact management** — people and organizations
- **Relationship graph** — visualize connections
- **Pipeline tracking** — manage opportunities
- **Delegations** — liquid democracy trust flows`,
	},

	// ─── Category: Finance ──────────────────────────────────────
	{
		id: "demo-cat-finance",
		type: "folk-markdown",
		x: START_X, y: START_Y + 4 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Finance",
	},
	{
		id: "demo-tool-rwallet",
		type: "folk-markdown",
		...pos(0, 4), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rWallet
Multi-chain crypto wallet.

- **Gnosis Safe** — multisig wallet abstraction
- **Token balances** — view across chains
- **DeFi positions** — Aave, Uniswap, etc.
- **Sankey flows** — transaction visualization`,
	},
	{
		id: "demo-tool-rflows",
		type: "folk-markdown",
		...pos(1, 4), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rFlows
Community funding and budgets.

- **Collective budgets** — participatory pie charts
- **Personal sliders** — auto-normalizing allocation
- **Community lending** — trust-backed pools
- **Yield projection** — compound interest calculator`,
	},
	{
		id: "demo-tool-rcart",
		type: "folk-markdown",
		...pos(2, 4), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rCart
Community storefront.

- **Group shopping** — shared carts
- **Print-on-demand** — catalog with production
- **Group buys** — volume discount campaigns
- **Order tracking** — fulfillment & invoices`,
	},
	{
		id: "demo-tool-rauctions",
		type: "folk-markdown",
		...pos(3, 4), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rAuctions
Live auction platform.

- **Create auctions** — list items for bidding
- **Real-time bids** — live bidding updates
- **Auction history** — completed results
- **Community trust** — reputation-backed bidding`,
	},

	// ─── Category: Travel & Share ───────────────────────────────
	{
		id: "demo-cat-travel",
		type: "folk-markdown",
		x: START_X, y: START_Y + 5 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Travel & Share",
	},
	{
		id: "demo-tool-rtrips",
		type: "folk-markdown",
		...pos(0, 5), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rTrips
Collaborative trip planning.

- **Itineraries** — day-by-day activity plans
- **Destinations** — multi-stop with map pins
- **Route planner** — optimal waypoint ordering
- **Expense splitting** — track who paid what`,
	},
	{
		id: "demo-tool-rmaps",
		type: "folk-markdown",
		...pos(1, 5), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rMaps
Location sharing and routing.

- **Live locations** — real-time participant map
- **Privacy controls** — precision fuzzing, ghost mode
- **Turn-by-turn routing** — OSRM + indoor nav
- **Meeting points** — coordinate group meetups`,
	},
	{
		id: "demo-tool-rbnb",
		type: "folk-markdown",
		...pos(2, 5), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rBnb
Community hospitality exchange.

- **List spaces** — share your home with members
- **Stay requests** — book within your community
- **Trust endorsements** — reputation from stays
- **No fees** — peer-to-peer, no platform cut`,
	},
	{
		id: "demo-tool-rvnb",
		type: "folk-markdown",
		...pos(3, 5), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rVnb
Community vehicle sharing.

- **List vehicles** — share cars, bikes, vans
- **Rental requests** — book within community
- **Trust endorsements** — reputation from trips
- **Usage tracking** — mileage and availability`,
	},

	// ─── Category: Publish ──────────────────────────────────────
	{
		id: "demo-cat-publish",
		type: "folk-markdown",
		x: START_X, y: START_Y + 6 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Publish",
	},
	{
		id: "demo-tool-rpubs",
		type: "folk-markdown",
		...pos(0, 6), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rPubs
Zine and book publishing.

- **MycroZines** — 8-page auto-generated zines
- **PDF output** — print-ready publications
- **Drafts** — work-in-progress documents
- **Community library** — share publications`,
	},
	{
		id: "demo-tool-rdesign",
		type: "folk-markdown",
		...pos(1, 6), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rDesign
Design tools and templates.

- **Layout editor** — visual design canvas
- **Templates** — reusable design patterns
- **Asset library** — shared design resources
- **Export** — PNG, SVG, PDF output`,
	},
	{
		id: "demo-tool-rswag",
		type: "folk-markdown",
		...pos(2, 6), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSwag
Merchandise design.

- **Product designer** — t-shirts, stickers, prints
- **Print-on-demand** — connect to production
- **Sell in rCart** — list directly in your store
- **Size variants** — manage product options`,
	},
	{
		id: "demo-tool-rsocials",
		type: "folk-markdown",
		...pos(3, 6), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSocials
Social media management.

- **Campaign builder** — multi-platform scheduling
- **Thread composer** — Twitter/X thread drafting
- **Newsletter editor** — email campaign drafts
- **Analytics** — track engagement metrics`,
	},

	// ─── Category: Data & AI ────────────────────────────────────
	{
		id: "demo-cat-data",
		type: "folk-markdown",
		x: START_X, y: START_Y + 7 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Data & AI",
	},
	{
		id: "demo-tool-rdata",
		type: "folk-markdown",
		...pos(0, 7), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rData
Space data explorer.

- **Content tree** — hierarchical CRDT document view
- **Data cloud** — 3D force-directed graph
- **Analytics** — usage metrics and engagement
- **Search** — find any object in your space`,
	},
	{
		id: "demo-tool-rbooks",
		type: "folk-markdown",
		...pos(1, 7), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rBooks
Shared PDF library.

- **Flipbook reader** — page-turning animations
- **Bookmarks & notes** — annotations that sync
- **Collections** — curated reading lists
- **Community library** — upload and share PDFs`,
	},
	{
		id: "demo-tool-rsplat",
		type: "folk-markdown",
		...pos(2, 7), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSplat
3D Gaussian splatting.

- **Interactive 3D** — orbit, pan, zoom in browser
- **Upload .ply/.splat** — share 3D captures
- **Multi-angle** — photorealistic reconstructions
- **Drawing mode** — 3D freehand sketching`,
	},
	{
		id: "demo-tool-ragents",
		type: "folk-markdown",
		...pos(3, 7), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rAgents
AI assistants for your space.

- **Canvas AI** — chat with context of your space
- **Image generation** — fal.ai Flux Pro
- **Video generation** — text-to-video
- **Multi-model** — Gemini, Ollama, Claude`,
	},

	// ─── Category: Infrastructure ───────────────────────────────
	{
		id: "demo-cat-infra",
		type: "folk-markdown",
		x: START_X, y: START_Y + 8 * ROW_H - 40, width: 200, height: 30, rotation: 0,
		content: "## Infrastructure",
	},
	{
		id: "demo-tool-rspace",
		type: "folk-markdown",
		...pos(0, 8), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSpace Canvas
The infinite collaborative canvas.

- **Drag & drop** — place any shape on the canvas
- **Arrows** — connect shapes to show relationships
- **Real-time sync** — see collaborators' cursors
- **Nested canvases** — embed spaces within spaces`,
	},
	{
		id: "demo-tool-rfiles",
		type: "folk-markdown",
		...pos(1, 8), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rFiles
File storage for your space.

- **Upload anything** — drag-and-drop file uploads
- **Public shares** — shareable download links
- **IPFS pinning** — decentralized backup
- **Version history** — track file changes`,
	},
	{
		id: "demo-tool-rsheets",
		type: "folk-markdown",
		...pos(2, 8), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rSheets
Collaborative spreadsheets.

- **Real-time editing** — multi-user spreadsheets
- **Formulas** — standard spreadsheet functions
- **Import/export** — CSV and Excel support
- **Embed** — use spreadsheet data in other rApps`,
	},
	{
		id: "demo-tool-rexchange",
		type: "folk-markdown",
		...pos(3, 8), width: CARD_W, height: CARD_H, rotation: 0,
		content: `### rExchange
Peer-to-peer exchange.

- **Post intents** — buy or sell anything
- **Add liquidity** — provide exchange liquidity
- **Order matching** — automated intent matching
- **Community trust** — reputation-backed trades`,
	},
];

/**
 * Ensure the demo community exists and is seeded with data.
 * Called on server startup and after demo reset.
 */
export async function ensureDemoCommunity(): Promise<void> {
	const exists = await communityExists("demo");

	if (!exists) {
		await createCommunity("r* Ecosystem Demo", "demo", null, "public", {
			description: "Public demo space — explore all rSpace tools on the canvas",
		});
		console.log("[Demo] Created demo community with visibility: public");
	} else {
		await loadCommunity("demo");
		// Ensure visibility stays "public" (older docs may have been created as "private")
		const doc = getDocumentData("demo");
		if (doc?.meta?.visibility !== "public") {
			updateSpaceMeta("demo", { visibility: "public" });
			console.log("[Demo] Fixed demo visibility → public");
		}
	}

	// Check if already seeded (has shapes or was previously seeded then cleared)
	const data = getDocumentData("demo");
	const shapeCount = data ? Object.keys(data.shapes || {}).length : 0;
	const alreadySeeded = (data?.meta as any)?.shapesSeeded === true;

	if (shapeCount === 0 && !alreadySeeded) {
		addShapes("demo", DEMO_SHAPES);
		markShapesSeeded("demo");
		console.log(`[Demo] Seeded ${DEMO_SHAPES.length} shapes into demo community`);
	} else {
		console.log(`[Demo] Demo community already has ${shapeCount} shapes (seeded=${alreadySeeded})`);
	}
}
