/**
 * Campaign demo data — "MycoFi Earth Launch" campaign.
 *
 * Extracted from server/seed-campaign.ts. This data drives the
 * /campaign page in rSocials and the /api/campaigns endpoint.
 * Also exports buildDemoCampaignFlow() for the canvas planner.
 */

import type { CampaignFlow, CampaignPlannerNode, CampaignEdge, CampaignWorkflow, CampaignWorkflowNode, CampaignWorkflowEdge } from './schemas';

export interface CampaignPost {
	id: string;
	platform: string;
	postType: string;
	stepNumber: number;
	content: string;
	scheduledAt: string;
	status: string;
	hashtags: string[];
	phase: number;
	phaseLabel: string;
}

export interface Campaign {
	id: string;
	title: string;
	description: string;
	duration: string;
	platforms: string[];
	phases: { name: string; label: string; days: string }[];
	posts: CampaignPost[];
}

const PLATFORM_ICONS: Record<string, string> = {
	x: "𝕏",
	linkedin: "in",
	instagram: "📷",
	youtube: "▶️",
	threads: "🧵",
	bluesky: "🦋",
	newsletter: "📧",
};

const PLATFORM_COLORS: Record<string, string> = {
	x: "#000000",
	linkedin: "#0A66C2",
	instagram: "#E4405F",
	youtube: "#FF0000",
	threads: "#000000",
	bluesky: "#0085FF",
	newsletter: "#6366f1",
};

export { PLATFORM_ICONS, PLATFORM_COLORS };

export const MYCOFI_CAMPAIGN: Campaign = {
	id: "mycofi-earth-launch",
	title: "MycoFi Earth Launch Campaign",
	description: "Multi-platform product launch campaign for MycoFi Earth — a regenerative finance platform modeled on mycelial networks.",
	duration: "Feb 21–25, 2026 (5 days)",
	platforms: ["X", "LinkedIn", "Instagram", "YouTube", "Threads", "Bluesky"],
	phases: [
		{ name: "pre-launch", label: "Pre-Launch Hype", days: "Day -3 to -1" },
		{ name: "launch", label: "Launch Day", days: "Day 0" },
		{ name: "amplification", label: "Amplification", days: "Day +1" },
	],
	posts: [
		{
			id: "post-x-teaser",
			platform: "x",
			postType: "thread",
			stepNumber: 1,
			content: "Something is growing in the mycelium... 🍄\n\nFor the past 2 years, we've been building the infrastructure for a regenerative economy.\n\nOn Feb 24, we reveal everything.\n\nA thread on why the old financial system is composting itself 🧵👇",
			scheduledAt: "2026-02-21T09:00:00",
			status: "scheduled",
			hashtags: ["MycoFi", "RegenFinance", "Web3", "ComingSoon"],
			phase: 1,
			phaseLabel: "Pre-Launch Hype",
		},
		{
			id: "post-linkedin-thought",
			platform: "linkedin",
			postType: "article",
			stepNumber: 2,
			content: "The regenerative finance movement isn't just about returns — it's about redesigning incentive structures from the ground up.\n\nIn this article, I break down why mycelial network theory offers the best model for decentralized economic coordination.\n\n3 key insights from 2 years of building MycoFi Earth...",
			scheduledAt: "2026-02-22T11:00:00",
			status: "scheduled",
			hashtags: ["RegenerativeFinance", "DeFi", "SystemsThinking", "Leadership"],
			phase: 1,
			phaseLabel: "Pre-Launch Hype",
		},
		{
			id: "post-ig-carousel",
			platform: "instagram",
			postType: "carousel",
			stepNumber: 3,
			content: "5 Ways Mycelium Networks Mirror the Future of Finance 🌍🍄\n\nSlide 1: The problem with extractive finance\nSlide 2: How mycelium redistributes nutrients\nSlide 3: Token-weighted funding circles\nSlide 4: Community governance that actually works\nSlide 5: Join the launch — Feb 24",
			scheduledAt: "2026-02-23T14:00:00",
			status: "scheduled",
			hashtags: ["MycoFi", "RegenerativeEconomy", "Infographic", "Web3Education"],
			phase: 1,
			phaseLabel: "Pre-Launch Hype",
		},
		{
			id: "post-yt-launch",
			platform: "youtube",
			postType: "video",
			stepNumber: 4,
			content: "MycoFi Earth — Official Launch Video\n\nThe regenerative economy starts here. Watch how mycelial intelligence is reshaping finance, governance, and community coordination.\n\nFeaturing interviews with 12 builders from the ecosystem.\n\n[18:42]",
			scheduledAt: "2026-02-24T10:00:00",
			status: "draft",
			hashtags: ["MycoFiLaunch", "RegenerativeFinance", "Documentary", "Web3"],
			phase: 2,
			phaseLabel: "Launch Day",
		},
		{
			id: "post-x-launch",
			platform: "x",
			postType: "thread",
			stepNumber: 5,
			content: "🍄 MycoFi Earth is LIVE 🍄\n\nAfter 2 years of building, the regenerative finance platform is here.\n\nWhat is it?\n• Token-weighted funding circles\n• Mycelial governance (no whales)\n• Composting mechanism for failed proposals\n• 100% on-chain, 100% community-owned\n\n👇 Full breakdown thread",
			scheduledAt: "2026-02-24T10:15:00",
			status: "draft",
			hashtags: ["MycoFi", "Launch", "RegenFinance", "DeFi", "DAO"],
			phase: 2,
			phaseLabel: "Launch Day",
		},
		{
			id: "post-linkedin-launch",
			platform: "linkedin",
			postType: "text",
			stepNumber: 6,
			content: "Today we're launching MycoFi Earth — a regenerative finance platform modeled on mycelial networks.\n\nWhy it matters for the future of organizational design:\n\n1. Composting mechanism: Failed proposals return resources to the network\n2. Nutrient routing: Funds flow to where they're needed most\n3. No single point of failure: True decentralization\n\nFull video + docs in comments ↓",
			scheduledAt: "2026-02-24T11:00:00",
			status: "draft",
			hashtags: ["Launch", "RegenerativeFinance", "Innovation", "FutureOfWork"],
			phase: 2,
			phaseLabel: "Launch Day",
		},
		{
			id: "post-ig-reel",
			platform: "instagram",
			postType: "reel",
			stepNumber: 7,
			content: "60-second explainer: How MycoFi Earth works 🍄✨\n\nVisual breakdown of the token flow from contributor → funding circle → project → compost.\n\nSet to lo-fi beats with mycelium time-lapse footage.\n\nCTA: Link in bio to join the first funding circle.",
			scheduledAt: "2026-02-25T12:00:00",
			status: "draft",
			hashtags: ["MycoFi", "RegenFinance", "Explainer", "Web3", "Reels"],
			phase: 3,
			phaseLabel: "Amplification",
		},
		{
			id: "post-threads-xpost",
			platform: "threads",
			postType: "text",
			stepNumber: 8,
			content: "We just launched MycoFi Earth and the response has been incredible 🌟\n\nThe idea is simple: what if finance worked like mycelium?\n\nMycelium doesn't hoard — it redistributes. MycoFi applies that logic to community funding.\n\nEarly access is open. Come grow with us 🌱",
			scheduledAt: "2026-02-25T14:00:00",
			status: "draft",
			hashtags: ["MycoFi", "RegenEconomy", "Community"],
			phase: 3,
			phaseLabel: "Amplification",
		},
		{
			id: "post-bluesky-launch",
			platform: "bluesky",
			postType: "text",
			stepNumber: 9,
			content: "MycoFi Earth just went live 🍄\n\nIt's a regenerative finance platform where funding flows like nutrients through a mycelial network.\n\nNo VCs. No whales. Just communities funding what matters.\n\nmycofi.earth",
			scheduledAt: "2026-02-25T15:00:00",
			status: "draft",
			hashtags: ["MycoFi", "RegenFinance", "Bluesky"],
			phase: 3,
			phaseLabel: "Amplification",
		},
	],
};

// ── Build demo campaign flow for canvas planner ──

export function buildDemoCampaignFlow(): CampaignFlow {
	const nodes: CampaignPlannerNode[] = [];
	const edges: CampaignEdge[] = [];

	// Phase containers
	const phaseX = [50, 500, 950];
	const phaseColors = ['#6366f1', '#10b981', '#f59e0b'];
	const phasePosts: CampaignPost[][] = [[], [], []];

	for (const post of MYCOFI_CAMPAIGN.posts) {
		phasePosts[post.phase - 1].push(post);
	}

	for (let i = 0; i < MYCOFI_CAMPAIGN.phases.length; i++) {
		const phase = MYCOFI_CAMPAIGN.phases[i];
		const postCount = phasePosts[i].length;
		nodes.push({
			id: `phase-${i}`,
			type: 'phase',
			position: { x: phaseX[i], y: 20 },
			data: {
				label: phase.label,
				dateRange: phase.days,
				color: phaseColors[i],
				progress: i === 0 ? 100 : i === 1 ? 30 : 0,
				childNodeIds: phasePosts[i].map(p => p.id),
				size: { w: 400, h: 80 + postCount * 140 },
			},
		});
	}

	// Post nodes inside phases, stacked vertically
	for (let pi = 0; pi < phasePosts.length; pi++) {
		const posts = phasePosts[pi];
		for (let j = 0; j < posts.length; j++) {
			const post = posts[j];
			nodes.push({
				id: post.id,
				type: 'post',
				position: { x: phaseX[pi] + 80, y: 80 + j * 140 },
				data: {
					label: post.content.split('\n')[0].substring(0, 40),
					platform: post.platform,
					postType: post.postType,
					content: post.content,
					scheduledAt: post.scheduledAt,
					status: post.status as 'draft' | 'scheduled' | 'published',
					hashtags: post.hashtags,
				},
			});
		}
	}

	// Platform nodes on the right
	const platforms = [
		{ platform: 'x', handle: '@mycofi_earth' },
		{ platform: 'linkedin', handle: 'MycoFi Earth' },
		{ platform: 'instagram', handle: '@mycofi.earth' },
		{ platform: 'youtube', handle: 'MycoFi Earth' },
		{ platform: 'threads', handle: '@mycofi.earth' },
		{ platform: 'bluesky', handle: '@mycofi.earth' },
	];

	for (let i = 0; i < platforms.length; i++) {
		const p = platforms[i];
		nodes.push({
			id: `plat-${p.platform}`,
			type: 'platform',
			position: { x: 1450, y: 40 + i * 100 },
			data: {
				label: p.platform.charAt(0).toUpperCase() + p.platform.slice(1),
				platform: p.platform,
				handle: p.handle,
			},
		});
	}

	// Audience node below platforms
	nodes.push({
		id: 'audience-regen',
		type: 'audience',
		position: { x: 1450, y: 660 },
		data: {
			label: 'Regen Community',
			description: 'Web3, DeFi, ReFi builders and enthusiasts',
			sizeEstimate: '~50K',
		},
	});

	// Publish edges: each post → its platform
	for (const post of MYCOFI_CAMPAIGN.posts) {
		edges.push({
			id: `e-${post.id}-plat`,
			from: post.id,
			to: `plat-${post.platform}`,
			type: 'publish',
		});
	}

	// Sequence edges: posts within each phase in step order
	for (const posts of phasePosts) {
		for (let j = 1; j < posts.length; j++) {
			edges.push({
				id: `e-seq-${posts[j - 1].id}-${posts[j].id}`,
				from: posts[j - 1].id,
				to: posts[j].id,
				type: 'sequence',
			});
		}
	}

	// Target edges: a few posts → audience
	edges.push({ id: 'e-target-1', from: 'post-x-teaser', to: 'audience-regen', type: 'target' });
	edges.push({ id: 'e-target-2', from: 'post-x-launch', to: 'audience-regen', type: 'target' });
	edges.push({ id: 'e-target-3', from: 'post-bluesky-launch', to: 'audience-regen', type: 'target' });

	const now = Date.now();
	return {
		id: 'demo-mycofi-campaign',
		name: 'MycoFi Earth Launch',
		nodes,
		edges,
		createdAt: now,
		updatedAt: now,
		createdBy: null,
	};
}

// ── Build demo campaign workflow (n8n-style) ──
// Campaign Start → Post to X → Wait 2h → Cross-Post (LinkedIn + Threads) → Engagement Check → Send Newsletter

export function buildDemoCampaignWorkflow(): CampaignWorkflow {
	const nodes: CampaignWorkflowNode[] = [
		{
			id: 'cw-start',
			type: 'campaign-start',
			label: 'Campaign Start',
			position: { x: 50, y: 120 },
			config: { description: 'MycoFi Earth launch sequence' },
		},
		{
			id: 'cw-post-x',
			type: 'post-to-platform',
			label: 'Post to X',
			position: { x: 340, y: 100 },
			config: {
				platform: 'X',
				content: 'Something is growing in the mycelium... \uD83C\uDF44\n\nMycoFi Earth launches today. A regenerative finance platform modeled on mycelial networks.\n\nNo VCs. No whales. Just communities funding what matters.',
				hashtags: '#MycoFi #RegenFinance #Web3',
			},
		},
		{
			id: 'cw-wait',
			type: 'wait-duration',
			label: 'Wait 2 Hours',
			position: { x: 630, y: 120 },
			config: { amount: 2, unit: 'hours' },
		},
		{
			id: 'cw-crosspost',
			type: 'cross-post',
			label: 'Cross-Post',
			position: { x: 920, y: 80 },
			config: {
				platforms: 'LinkedIn, Threads',
				content: 'MycoFi Earth is live — a regenerative finance platform where funding flows like nutrients through a mycelial network.',
				adaptPerPlatform: 'yes',
			},
		},
		{
			id: 'cw-engage',
			type: 'engagement-check',
			label: 'Engagement Check',
			position: { x: 1210, y: 60 },
			config: { metric: 'likes', threshold: 50 },
		},
		{
			id: 'cw-newsletter',
			type: 'send-newsletter',
			label: 'Send Newsletter',
			position: { x: 1500, y: 40 },
			config: {
				subject: 'MycoFi Earth is Live!',
				listId: '1',
				bodyTemplate: '<h1>MycoFi Earth Launch</h1><p>The regenerative finance platform is now live. Join the first funding circle.</p>',
			},
		},
	];

	const edges: CampaignWorkflowEdge[] = [
		{ id: 'cwe-1', fromNode: 'cw-start', fromPort: 'trigger', toNode: 'cw-post-x', toPort: 'trigger' },
		{ id: 'cwe-2', fromNode: 'cw-post-x', fromPort: 'done', toNode: 'cw-wait', toPort: 'trigger' },
		{ id: 'cwe-3', fromNode: 'cw-wait', fromPort: 'done', toNode: 'cw-crosspost', toPort: 'trigger' },
		{ id: 'cwe-4', fromNode: 'cw-crosspost', fromPort: 'done', toNode: 'cw-engage', toPort: 'trigger' },
		{ id: 'cwe-5', fromNode: 'cw-engage', fromPort: 'above', toNode: 'cw-newsletter', toPort: 'trigger' },
	];

	const now = Date.now();
	return {
		id: 'demo-mycofi-workflow',
		name: 'MycoFi Launch Workflow',
		enabled: true,
		nodes,
		edges,
		lastRunAt: null,
		lastRunStatus: null,
		runCount: 0,
		createdAt: now,
		updatedAt: now,
	};
}
