Unclassified

GENSPARK OPUS: IntegrateWise Core App Completion & Integration Prompt

Project: IntegrateWise AI Workspace Platform
Version: Production Ready v1.0
Date: January 2026
Objective: Complete the core application, integrate all separated components into one cohesive platform, and apply dual-theme design system (MailerLite-style for Individual users, Corporate Blue for Enterprise)


🎯 MISSION OVERVIEW

You are tasked with completing the IntegrateWise AI Workspace platformβ€”a universal productivity platform that helps businesses connect their tools, sync data, automate workflows, and leverage AI intelligence. The application is currently ~52% complete with components scattered across multiple repositories. Your mission is to:

  1. Consolidate all separated app parts into ONE unified Next.js application
  2. Complete the remaining 48% of core functionality
  3. Apply dual-theme design system (MailerLite for individuals, Corporate Blue for enterprise)
  4. Ensure production readiness with proper error handling, loading states, and responsive design

🎨 DESIGN SYSTEM SPECIFICATION

Theme 1: Individual/Freelancer Mode (MailerLite-Inspired)

Philosophy: Clean, friendly, approachableβ€”"Making the complex simple"

/* Individual Theme - MailerLite Style */
:root[data-theme="individual"] {
  /* Primary Colors */
  --primary-green: #09c269; /* MailerLite signature green */
  --primary-green-light: #0ed47b; /* Hover state */
  --primary-green-dark: #07a558; /* Active state */
  --primary-green-subtle: #e8f8f0; /* Backgrounds */

  /* Coral/Warm Accents */
  --accent-coral: #ff6b6b; /* CTAs, notifications */
  --accent-coral-light: #ff8787; /* Hover */
  --accent-coral-subtle: #fff0f0; /* Light background */

  /* Neutrals */
  --background: #ffffff;
  --background-secondary: #f9fafb;
  --background-tertiary: #f3f4f6;
  --text-primary: #1a1a2e;
  --text-secondary: #6b7280;
  --text-muted: #9ca3af;
  --border: #e5e7eb;
  --border-light: #f3f4f6;

  /* Semantic */
  --success: #09c269;
  --warning: #f59e0b;
  --error: #ef4444;
  --info: #3b82f6;

  /* Shadows */
  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);

  /* Radius */
  --radius-sm: 6px;
  --radius-md: 8px;
  --radius-lg: 12px;
  --radius-xl: 16px;
  --radius-full: 9999px;

  /* Typography */
  --font-primary: "Inter", -apple-system, BlinkMacSystemFont, sans-serif;
  --font-display: "Plus Jakarta Sans", var(--font-primary);
}

Individual Theme UI Characteristics:

  • Rounded buttons with generous padding (radius-lg)
  • Soft shadows, no hard edges
  • Generous whitespace
  • Friendly, conversational copy
  • Single-column layouts for simplicity
  • Warm, inviting illustrations
  • Animated micro-interactions (subtle bounces, fades)
  • Emojis acceptable in headers/CTAs

Theme 2: Corporate/Enterprise Mode

Philosophy: Professional, trustworthy, powerfulβ€”"Enterprise-grade reliability"

/* Enterprise Theme - Corporate Blue */
:root[data-theme="enterprise"] {
  /* Primary Colors */
  --primary-blue: #1e3a8a; /* Deep corporate blue */
  --primary-blue-light: #2563eb; /* Hover state */
  --primary-blue-dark: #1e40af; /* Active state */
  --primary-blue-subtle: #eff6ff; /* Backgrounds */

  /* Secondary Navy */
  --secondary-navy: #0f172a; /* Headers, important text */
  --secondary-slate: #334155; /* Body text */

  /* Accent */
  --accent-teal: #0891b2; /* Links, highlights */
  --accent-teal-light: #22d3ee; /* Hover */
  --accent-gold: #d97706; /* Premium features */

  /* Neutrals */
  --background: #ffffff;
  --background-secondary: #f8fafc;
  --background-tertiary: #f1f5f9;
  --text-primary: #0f172a;
  --text-secondary: #475569;
  --text-muted: #94a3b8;
  --border: #cbd5e1;
  --border-light: #e2e8f0;

  /* Semantic */
  --success: #059669;
  --warning: #d97706;
  --error: #dc2626;
  --info: #2563eb;

  /* Shadows */
  --shadow-sm: 0 1px 3px rgba(15, 23, 42, 0.08);
  --shadow-md: 0 4px 8px -2px rgba(15, 23, 42, 0.1);
  --shadow-lg: 0 12px 24px -4px rgba(15, 23, 42, 0.12);

  /* Radius */
  --radius-sm: 4px;
  --radius-md: 6px;
  --radius-lg: 8px;
  --radius-xl: 12px;
  --radius-full: 9999px;

  /* Typography */
  --font-primary: "Inter", -apple-system, BlinkMacSystemFont, sans-serif;
  --font-display: "IBM Plex Sans", var(--font-primary);
}

Enterprise Theme UI Characteristics:

  • Sharp, professional corners (radius-sm to radius-md)
  • Structured data tables with sorting
  • Dense information display
  • Formal, precise language
  • Multi-column dashboards
  • Detailed analytics charts
  • Subtle, professional animations
  • No emojis, icons only from professional icon sets (Lucide, Heroicons)

πŸ—οΈ APPLICATION ARCHITECTURE

Tech Stack

Frontend:
  framework: Next.js 14+ (App Router)
  styling: Tailwind CSS 3.4+
  components: Shadcn/ui
  state: Zustand + React Query
  forms: React Hook Form + Zod
  charts: Recharts
  icons: Lucide React

Backend:
  runtime: Cloudflare Workers (Edge)
  database: Supabase (PostgreSQL + RLS)
  auth: Supabase Auth + NextAuth.js
  queue: Cloudflare Queues
  storage: Cloudflare R2
  cache: Cloudflare KV

AI Layer:
  orchestration: n8n (self-hosted)
  llm_providers: [OpenAI, Anthropic, OpenRouter]
  agents: Custom n8n workflows

Infrastructure:
  hosting: Vercel (Frontend) + Cloudflare (Edge)
  monitoring: Better Stack
  error_tracking: Sentry

Directory Structure

integratewise/
β”œβ”€β”€ apps/
β”‚   └── web/                          # Main Next.js application
β”‚       β”œβ”€β”€ app/
β”‚       β”‚   β”œβ”€β”€ (auth)/               # Auth routes (login, signup, reset)
β”‚       β”‚   β”‚   β”œβ”€β”€ login/
β”‚       β”‚   β”‚   β”œβ”€β”€ signup/
β”‚       β”‚   β”‚   └── verify/
β”‚       β”‚   β”œβ”€β”€ (dashboard)/          # Protected dashboard routes
β”‚       β”‚   β”‚   β”œβ”€β”€ layout.tsx        # Dashboard shell with sidebar
β”‚       β”‚   β”‚   β”œβ”€β”€ page.tsx          # Home/Overview
β”‚       β”‚   β”‚   β”œβ”€β”€ connect/          # Tool connections
β”‚       β”‚   β”‚   β”œβ”€β”€ sync/             # Data synchronization
β”‚       β”‚   β”‚   β”œβ”€β”€ automate/         # Automation workflows
β”‚       β”‚   β”‚   β”œβ”€β”€ create/           # Content creation
β”‚       β”‚   β”‚   β”œβ”€β”€ insights/         # AI insights & analytics
β”‚       β”‚   β”‚   β”œβ”€β”€ settings/         # Account settings
β”‚       β”‚   β”‚   └── admin/            # Admin panel (enterprise)
β”‚       β”‚   β”œβ”€β”€ (marketing)/          # Public pages
β”‚       β”‚   β”‚   β”œβ”€β”€ page.tsx          # Landing page
β”‚       β”‚   β”‚   β”œβ”€β”€ pricing/
β”‚       β”‚   β”‚   β”œβ”€β”€ features/
β”‚       β”‚   β”‚   └── blog/
β”‚       β”‚   β”œβ”€β”€ api/                  # API routes
β”‚       β”‚   β”‚   β”œβ”€β”€ auth/
β”‚       β”‚   β”‚   β”œβ”€β”€ webhooks/
β”‚       β”‚   β”‚   β”œβ”€β”€ connectors/
β”‚       β”‚   β”‚   └── ai/
β”‚       β”‚   β”œβ”€β”€ layout.tsx
β”‚       β”‚   └── globals.css
β”‚       β”œβ”€β”€ components/
β”‚       β”‚   β”œβ”€β”€ ui/                   # Shadcn components
β”‚       β”‚   β”œβ”€β”€ theme/                # Theme provider & switcher
β”‚       β”‚   β”œβ”€β”€ dashboard/            # Dashboard-specific components
β”‚       β”‚   β”œβ”€β”€ connectors/           # Integration cards & flows
β”‚       β”‚   β”œβ”€β”€ automation/           # Workflow builder components
β”‚       β”‚   └── shared/               # Shared components
β”‚       β”œβ”€β”€ lib/
β”‚       β”‚   β”œβ”€β”€ supabase/
β”‚       β”‚   β”œβ”€β”€ auth/
β”‚       β”‚   β”œβ”€β”€ api/
β”‚       β”‚   └── utils/
β”‚       β”œβ”€β”€ hooks/
β”‚       β”œβ”€β”€ stores/
β”‚       └── types/
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ database/                     # Supabase schema & migrations
β”‚   β”œβ”€β”€ connectors/                   # Integration adapters
β”‚   └── shared/                       # Shared utilities
β”œβ”€β”€ workers/
β”‚   β”œβ”€β”€ webhooks/                     # Webhook processor
β”‚   β”œβ”€β”€ sync/                         # Data sync worker
β”‚   └── queue/                        # Queue consumer
└── docs/

πŸ“¦ CORE FEATURES TO IMPLEMENT

1. Authentication & Onboarding (Priority: Critical)

// 60-Second AI-First Onboarding Flow
const onboardingSteps = [
  {
    step: 1,
    name: "signup",
    duration: "15s",
    component: "SignupForm",
    fields: ["email", "password", "company_name"],
    theme_detection: true, // Auto-detect individual vs enterprise
  },
  {
    step: 2,
    name: "profile",
    duration: "10s",
    component: "ProfileSetup",
    ai_assist: true, // AI suggests based on email domain
    fields: ["role", "team_size", "primary_goal"],
  },
  {
    step: 3,
    name: "connect_first_tool",
    duration: "20s",
    component: "QuickConnect",
    suggested_tools: ["HubSpot", "Salesforce", "Slack", "Google Workspace"],
    oauth_popup: true,
  },
  {
    step: 4,
    name: "ai_insights_preview",
    duration: "15s",
    component: "InsightsPreview",
    show_sample_data: true,
    cta: "Start Free Trial",
  },
];

Implementation Requirements:

  • Supabase Auth with email/password + OAuth (Google, Microsoft)
  • Magic link login option
  • SSO/SAML ready for enterprise (config-based)
  • Theme auto-detection based on email domain (corporate = enterprise theme)
  • Progress indicator showing time remaining
  • Skip option at each step

2. Connection Hub (Priority: Critical)

// Supported Integrations - Phase 1
const connectors = {
  crm: [
    { id: "hubspot", name: "HubSpot", oauth: true, status: "ready" },
    { id: "salesforce", name: "Salesforce", oauth: true, status: "ready" },
    { id: "pipedrive", name: "Pipedrive", oauth: true, status: "beta" },
  ],
  communication: [
    { id: "slack", name: "Slack", oauth: true, status: "ready" },
    { id: "teams", name: "Microsoft Teams", oauth: true, status: "ready" },
    { id: "gmail", name: "Gmail", oauth: true, status: "ready" },
  ],
  productivity: [
    { id: "notion", name: "Notion", oauth: true, status: "ready" },
    { id: "asana", name: "Asana", oauth: true, status: "ready" },
    { id: "monday", name: "Monday.com", oauth: true, status: "beta" },
  ],
  data: [
    { id: "google_sheets", name: "Google Sheets", oauth: true, status: "ready" },
    { id: "airtable", name: "Airtable", api_key: true, status: "ready" },
  ],
};

// Connection Card Component Props
interface ConnectorCardProps {
  connector: Connector;
  status: "connected" | "disconnected" | "syncing" | "error";
  lastSync?: Date;
  recordCount?: number;
  onConnect: () => void;
  onDisconnect: () => void;
  onSync: () => void;
}

UI Requirements:

  • Grid layout showing all available connectors
  • Status badges (Connected/Disconnected/Syncing/Error)
  • OAuth popup flow with loading states
  • Connection health indicators
  • "Last synced" timestamps
  • Record count display
  • Quick actions (Sync Now, Disconnect, Configure)

3. Data Synchronization Engine (Priority: High)

// Sync Configuration Schema
interface SyncConfig {
  id: string;
  source: {
    connector_id: string;
    objects: string[]; // ["contacts", "deals", "companies"]
    filters?: Record<string, any>;
  };
  destination: "atlas_spine"; // Internal unified database
  schedule: {
    type: "realtime" | "scheduled" | "manual";
    interval?: "5m" | "15m" | "1h" | "6h" | "24h";
    timezone?: string;
  };
  mapping: {
    field_mappings: FieldMapping[];
    conflict_resolution: "source_wins" | "dest_wins" | "most_recent";
  };
  status: "active" | "paused" | "error";
}

// ATLAS SPINE - Unified Data Model
interface AtlasSpineSchema {
  // Core Entities
  accounts: {
    id: string;
    external_ids: Record<string, string>; // {"hubspot": "123", "salesforce": "abc"}
    name: string;
    domain: string;
    industry: string;
    employee_count: number;
    arr: number;
    health_score: number;
    custom_fields: Record<string, any>;
    created_at: Date;
    updated_at: Date;
  };

  contacts: {
    id: string;
    external_ids: Record<string, string>;
    account_id: string;
    email: string;
    first_name: string;
    last_name: string;
    title: string;
    phone: string;
    engagement_score: number;
    custom_fields: Record<string, any>;
  };

  activities: {
    id: string;
    type: "email" | "call" | "meeting" | "note" | "task";
    account_id: string;
    contact_id: string;
    subject: string;
    body: string;
    sentiment: "positive" | "neutral" | "negative";
    timestamp: Date;
  };

  deals: {
    id: string;
    external_ids: Record<string, string>;
    account_id: string;
    name: string;
    amount: number;
    stage: string;
    probability: number;
    close_date: Date;
    owner_id: string;
  };
}

Sync Dashboard Requirements:

  • Real-time sync status visualization
  • Record count comparisons (source vs destination)
  • Error log with retry functionality
  • Field mapping editor (drag-and-drop)
  • Sync history with diff viewer
  • Pause/Resume controls

4. Automation Workflow Builder (Priority: High)

// Workflow Definition
interface Workflow {
  id: string;
  name: string;
  description: string;
  trigger: WorkflowTrigger;
  actions: WorkflowAction[];
  conditions?: WorkflowCondition[];
  status: "active" | "draft" | "paused";
  runs_count: number;
  last_run: Date;
  created_by: string;
}

// Pre-built Templates
const workflowTemplates = [
  {
    id: "welcome_sequence",
    name: "New Customer Welcome Sequence",
    category: "onboarding",
    trigger: { type: "deal_closed_won" },
    actions: [
      { type: "send_slack_message", delay: "0m" },
      { type: "create_task", delay: "1d" },
      { type: "send_email", delay: "3d" },
    ],
  },
  {
    id: "churn_alert",
    name: "Churn Risk Alert",
    category: "retention",
    trigger: { type: "health_score_drop", threshold: 30 },
    actions: [
      { type: "send_slack_alert", channel: "#cs-alerts" },
      { type: "create_task", assignee: "account_owner" },
      { type: "send_email", template: "churn_intervention" },
    ],
  },
  {
    id: "renewal_reminder",
    name: "90-Day Renewal Reminder",
    category: "renewals",
    trigger: { type: "days_until_renewal", days: 90 },
    actions: [
      { type: "send_email", template: "renewal_notice" },
      { type: "create_deal", stage: "renewal" },
    ],
  },
];

Workflow Builder UI:

  • Visual canvas with drag-and-drop nodes
  • Trigger selection panel (events from connected tools)
  • Action library with categorization
  • Condition builder with AND/OR logic
  • Test mode with sample data
  • Version history
  • Analytics (runs, success rate, avg duration)

5. AI Insights Dashboard (Priority: High)

// AI-Generated Insights
interface InsightCard {
  id: string;
  type: "health_alert" | "opportunity" | "risk" | "trend" | "recommendation";
  priority: "critical" | "high" | "medium" | "low";
  title: string;
  description: string;
  data: {
    accounts_affected?: number;
    potential_impact?: number;
    confidence: number;
  };
  actions: InsightAction[];
  dismissed: boolean;
  created_at: Date;
}

// Dashboard Widgets
const dashboardWidgets = [
  {
    id: "health_overview",
    type: "donut_chart",
    title: "Portfolio Health",
    data_source: "accounts.health_score",
    segments: ["healthy", "at_risk", "critical"],
  },
  {
    id: "arr_trend",
    type: "area_chart",
    title: "ARR Trend",
    data_source: "accounts.arr",
    timeframe: "12_months",
  },
  {
    id: "engagement_heatmap",
    type: "heatmap",
    title: "Engagement Activity",
    data_source: "activities",
    dimensions: ["day_of_week", "hour"],
  },
  {
    id: "upcoming_renewals",
    type: "table",
    title: "Upcoming Renewals",
    data_source: "accounts",
    filters: { renewal_in_days: { lte: 90 } },
  },
];

Dashboard Requirements:

  • Customizable widget grid (draggable, resizable)
  • AI insights feed with dismiss/action options
  • Real-time data refresh
  • Export to PDF/CSV
  • Shareable dashboard links
  • Role-based widget visibility

6. Content Creation (RENDER) (Priority: Medium)

// Render Templates
interface RenderTemplate {
  id: string;
  name: string;
  category: "qbr" | "report" | "presentation" | "email";
  format: "pdf" | "pptx" | "docx" | "html";
  variables: TemplateVariable[];
  preview_url: string;
}

// Content Generation Request
interface RenderRequest {
  template_id: string;
  account_id?: string;
  data_sources: string[]; // ["health_scores", "activities", "deals"]
  date_range: { start: Date; end: Date };
  custom_variables?: Record<string, any>;
  output_format: "pdf" | "pptx" | "docx";
}

πŸ—ƒοΈ DATABASE SCHEMA (Supabase)

-- Enable RLS
ALTER DATABASE postgres SET "app.jwt_secret" TO 'your-jwt-secret';

-- Organizations (Workspaces)
CREATE TABLE organizations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  slug TEXT UNIQUE NOT NULL,
  plan TEXT DEFAULT 'free' CHECK (plan IN ('free', 'pro', 'enterprise')),
  theme TEXT DEFAULT 'individual' CHECK (theme IN ('individual', 'enterprise')),
  settings JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Users
CREATE TABLE users (
  id UUID PRIMARY KEY REFERENCES auth.users(id),
  organization_id UUID REFERENCES organizations(id),
  email TEXT NOT NULL,
  full_name TEXT,
  avatar_url TEXT,
  role TEXT DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
  preferences JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Connections (Integrations)
CREATE TABLE connections (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  connector_type TEXT NOT NULL,
  name TEXT NOT NULL,
  credentials JSONB NOT NULL,  -- Encrypted
  config JSONB DEFAULT '{}',
  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'paused', 'error', 'disconnected')),
  last_sync_at TIMESTAMPTZ,
  sync_error TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- ATLAS SPINE: Accounts
CREATE TABLE atlas_accounts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  external_ids JSONB DEFAULT '{}',
  name TEXT NOT NULL,
  domain TEXT,
  industry TEXT,
  employee_count INTEGER,
  arr DECIMAL(15,2),
  health_score INTEGER CHECK (health_score >= 0 AND health_score <= 100),
  lifecycle_stage TEXT,
  owner_id UUID REFERENCES users(id),
  custom_fields JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- ATLAS SPINE: Contacts
CREATE TABLE atlas_contacts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  account_id UUID REFERENCES atlas_accounts(id),
  external_ids JSONB DEFAULT '{}',
  email TEXT NOT NULL,
  first_name TEXT,
  last_name TEXT,
  title TEXT,
  phone TEXT,
  engagement_score INTEGER DEFAULT 0,
  custom_fields JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- ATLAS SPINE: Activities
CREATE TABLE atlas_activities (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  account_id UUID REFERENCES atlas_accounts(id),
  contact_id UUID REFERENCES atlas_contacts(id),
  type TEXT NOT NULL CHECK (type IN ('email', 'call', 'meeting', 'note', 'task', 'chat')),
  direction TEXT CHECK (direction IN ('inbound', 'outbound')),
  subject TEXT,
  body TEXT,
  sentiment TEXT CHECK (sentiment IN ('positive', 'neutral', 'negative')),
  source_connector TEXT,
  external_id TEXT,
  occurred_at TIMESTAMPTZ NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Workflows
CREATE TABLE workflows (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  name TEXT NOT NULL,
  description TEXT,
  trigger JSONB NOT NULL,
  actions JSONB NOT NULL,
  conditions JSONB,
  status TEXT DEFAULT 'draft' CHECK (status IN ('draft', 'active', 'paused')),
  runs_count INTEGER DEFAULT 0,
  last_run_at TIMESTAMPTZ,
  created_by UUID REFERENCES users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- AI Insights
CREATE TABLE insights (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID REFERENCES organizations(id) NOT NULL,
  type TEXT NOT NULL,
  priority TEXT DEFAULT 'medium' CHECK (priority IN ('critical', 'high', 'medium', 'low')),
  title TEXT NOT NULL,
  description TEXT,
  data JSONB DEFAULT '{}',
  account_ids UUID[],
  actions JSONB DEFAULT '[]',
  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'dismissed', 'actioned')),
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Row Level Security Policies
ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE connections ENABLE ROW LEVEL SECURITY;
ALTER TABLE atlas_accounts ENABLE ROW LEVEL SECURITY;
ALTER TABLE atlas_contacts ENABLE ROW LEVEL SECURITY;
ALTER TABLE atlas_activities ENABLE ROW LEVEL SECURITY;
ALTER TABLE workflows ENABLE ROW LEVEL SECURITY;
ALTER TABLE insights ENABLE ROW LEVEL SECURITY;

-- RLS Policies (example for atlas_accounts)
CREATE POLICY "Users can view their org's accounts"
  ON atlas_accounts FOR SELECT
  USING (organization_id IN (
    SELECT organization_id FROM users WHERE id = auth.uid()
  ));

CREATE POLICY "Users can insert accounts in their org"
  ON atlas_accounts FOR INSERT
  WITH CHECK (organization_id IN (
    SELECT organization_id FROM users WHERE id = auth.uid()
  ));

🎯 COMPONENT SPECIFICATIONS

1. Theme Provider & Switcher

// components/theme/theme-provider.tsx
"use client";


type Theme = "individual" | "enterprise";

interface ThemeContextType {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

  const [theme, setTheme] = useState<Theme>("individual");

  useEffect(() => {
    // Load from localStorage or user preferences
    const saved = localStorage.getItem("iw-theme") as Theme;
    if (saved) setTheme(saved);
  }, []);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("iw-theme", theme);
  }, [theme]);

  const toggleTheme = () => {
    setTheme(theme === "individual" ? "enterprise" : "individual");
  };

  return (
    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

  const context = useContext(ThemeContext);
  if (!context) throw new Error("useTheme must be used within ThemeProvider");
  return context;
};

2. Dashboard Shell Layout

// app/(dashboard)/layout.tsx

  return (
    <ThemeProvider>
      <div className="flex h-screen bg-background">
        <Sidebar />
        <div className="flex-1 flex flex-col overflow-hidden">
          <Header />
          <main className="flex-1 overflow-y-auto p-6">{children}</main>
        </div>
      </div>
    </ThemeProvider>
  );
}

3. Connector Card Component

// components/connectors/connector-card.tsx
"use client";


interface ConnectorCardProps {
  connector: {
    id: string;
    name: string;
    icon: string;
    category: string;
  };
  connection?: {
    status: "connected" | "disconnected" | "syncing" | "error";
    lastSync?: Date;
    recordCount?: number;
    error?: string;
  };
  onConnect: () => void;
  onDisconnect: () => void;
  onSync: () => void;
  onConfigure: () => void;
}

  connector,
  connection,
  onConnect,
  onDisconnect,
  onSync,
  onConfigure,
}: ConnectorCardProps) {
  const { theme } = useTheme();
  const isConnected = connection?.status === "connected";
  const isSyncing = connection?.status === "syncing";
  const hasError = connection?.status === "error";

  const statusConfig = {
    connected: {
      label: "Connected",
      color: "bg-success/10 text-success",
      icon: CheckCircle,
    },
    disconnected: {
      label: "Not Connected",
      color: "bg-muted text-muted-foreground",
      icon: Unplug,
    },
    syncing: {
      label: "Syncing...",
      color: "bg-info/10 text-info",
      icon: Loader2,
    },
    error: {
      label: "Error",
      color: "bg-error/10 text-error",
      icon: AlertCircle,
    },
  };

  const status = connection?.status || "disconnected";
  const StatusIcon = statusConfig[status].icon;

  return (
    
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <div className="flex items-center gap-3">
          <img src={connector.icon} alt={connector.name} className="w-10 h-10 rounded-lg" />
          <div>
            <CardTitle className="text-lg">{connector.name}</CardTitle>
            <p className="text-sm text-muted-foreground capitalize">{connector.category}</p>
          </div>
        </div>
        
          <StatusIcon className={cn("w-3 h-3 mr-1", isSyncing && "animate-spin")} />
          {statusConfig[status].label}
        
      </CardHeader>

      <CardContent>
        {isConnected && (
          <div className="mb-4 space-y-1 text-sm text-muted-foreground">
            {connection.lastSync && <p>Last synced: {formatRelativeTime(connection.lastSync)}</p>}
            {connection.recordCount !== undefined && (
              <p>{connection.recordCount.toLocaleString()} records synced</p>
            )}
          </div>
        )}

        {hasError && connection?.error && (
          <div className="mb-4 p-3 rounded-md bg-error/10 text-error text-sm">
            {connection.error}
          </div>
        )}

        <div className="flex gap-2">
          {!isConnected ? (
            <Button
              onClick={onConnect}
              className={cn(
                "flex-1",
                theme === "individual"
                  ? "bg-primary-green hover:bg-primary-green-light"
                  : "bg-primary-blue hover:bg-primary-blue-light"
              )}
            >
              Connect
            </Button>
          ) : (
            <>
              <Button variant="outline" size="sm" onClick={onSync} disabled={isSyncing}>
                <RefreshCw className={cn("w-4 h-4 mr-1", isSyncing && "animate-spin")} />
                Sync
              </Button>
              <Button variant="outline" size="sm" onClick={onConfigure}>
                <Settings className="w-4 h-4 mr-1" />
                Configure
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={onDisconnect}
                className="text-error hover:text-error hover:bg-error/10"
              >
                <Unplug className="w-4 h-4" />
              </Button>
            </>
          )}
        </div>
      </CardContent>
    
  );
}

4. Insights Card Component

// components/dashboard/insight-card.tsx
"use client";


interface InsightCardProps {
  insight: {
    id: string;
    type: "health_alert" | "opportunity" | "risk" | "trend" | "recommendation";
    priority: "critical" | "high" | "medium" | "low";
    title: string;
    description: string;
    data: {
      accounts_affected?: number;
      potential_impact?: number;
      confidence: number;
    };
    actions: Array<{
      label: string;
      action: string;
    }>;
  };
  onDismiss: (id: string) => void;
  onAction: (id: string, action: string) => void;
}

  const { theme } = useTheme();

  const typeConfig = {
    health_alert: { icon: AlertTriangle, color: "text-error" },
    opportunity: { icon: TrendingUp, color: "text-success" },
    risk: { icon: TrendingDown, color: "text-warning" },
    trend: { icon: TrendingUp, color: "text-info" },
    recommendation: { icon: Lightbulb, color: "text-accent-coral" },
  };

  const priorityColors = {
    critical: "bg-error text-white",
    high: "bg-warning text-white",
    medium: "bg-info text-white",
    low: "bg-muted text-muted-foreground",
  };

  const TypeIcon = typeConfig[insight.type].icon;

  return (
    
      <CardContent className="p-4">
        <div className="flex items-start gap-3">
          <div
            className={cn(
              "p-2 rounded-lg",
              theme === "individual" ? "bg-primary-green-subtle" : "bg-primary-blue-subtle"
            )}
          >
            <TypeIcon className={cn("w-5 h-5", typeConfig[insight.type].color)} />
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              
                {insight.priority}
              
              {insight.data.accounts_affected && (
                <span className="text-xs text-muted-foreground">
                  {insight.data.accounts_affected} accounts
                </span>
              )}
            </div>

            <h4 className="font-semibold text-text-primary mb-1">{insight.title}</h4>
            <p className="text-sm text-text-secondary mb-3">{insight.description}</p>

            {insight.data.potential_impact && (
              <p className="text-sm font-medium mb-3">
                Potential impact: ${insight.data.potential_impact.toLocaleString()}
              </p>
            )}

            <div className="flex items-center gap-2">
              {insight.actions.map((action, index) => (
                <Button
                  key={index}
                  size="sm"
                  variant={index === 0 ? "default" : "outline"}
                  onClick={() => onAction(insight.id, action.action)}
                  className={cn(
                    index === 0 &&
                      theme === "individual" &&
                      "bg-primary-green hover:bg-primary-green-light",
                    index === 0 &&
                      theme === "enterprise" &&
                      "bg-primary-blue hover:bg-primary-blue-light"
                  )}
                >
                  {action.label}
                  <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              ))}
            </div>
          </div>

          <Button
            variant="ghost"
            size="sm"
            className="text-muted-foreground hover:text-text-primary"
            onClick={() => onDismiss(insight.id)}
          >
            <X className="w-4 h-4" />
          </Button>
        </div>

        
        <div className="mt-3 pt-3 border-t border-border">
          <div className="flex items-center gap-2">
            <span className="text-xs text-muted-foreground">Confidence:</span>
            <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
              <div
                className={cn(
                  "h-full rounded-full",
                  insight.data.confidence >= 80
                    ? "bg-success"
                    : insight.data.confidence >= 60
                      ? "bg-warning"
                      : "bg-error"
                )}
                style={{ width: `${insight.data.confidence}%` }}
              />
            </div>
            <span className="text-xs font-medium">{insight.data.confidence}%</span>
          </div>
        </div>
      </CardContent>
    
  );
}

πŸš€ IMPLEMENTATION PRIORITY ORDER

Phase 1: Foundation (Week 1-2)

  1. βœ… Project scaffolding with Next.js 14
  2. βœ… Theme system implementation (Individual + Enterprise)
  3. βœ… Supabase setup with RLS policies
  4. βœ… Authentication flow (signup, login, magic link)
  5. βœ… Dashboard shell layout
  6. βœ… Basic navigation and routing

Phase 2: Core Integrations (Week 3-4)

  1. Connection Hub UI
  2. OAuth flow implementation (HubSpot, Salesforce, Slack)
  3. Connection management (CRUD)
  4. Basic sync engine (pull data to ATLAS SPINE)
  5. Sync status monitoring

Phase 3: Intelligence Layer (Week 5-6)

  1. AI Insights dashboard
  2. Health score calculation
  3. Widget system (charts, tables, metrics)
  4. Insight generation via n8n workflows
  5. Action handlers

Phase 4: Automation (Week 7-8)

  1. Workflow builder UI
  2. Trigger configuration
  3. Action library
  4. Workflow execution engine (n8n integration)
  5. Workflow templates

Phase 5: Polish & Launch (Week 9-10)

  1. RENDER (content generation)
  2. Settings & preferences
  3. Admin panel (enterprise)
  4. Performance optimization
  5. Error handling & edge cases
  6. Documentation

πŸ“‹ ACCEPTANCE CRITERIA

Theme System

  • Theme toggle works instantly without page reload
  • All components respect current theme
  • Theme persists across sessions
  • Theme auto-detected from organization settings

Authentication

  • Signup completes in under 60 seconds
  • OAuth flows for Google/Microsoft
  • Magic link login works
  • Session management with refresh tokens
  • Protected routes redirect to login

Connections

  • At least 5 connectors working (HubSpot, Salesforce, Slack, Gmail, Notion)
  • OAuth popup flow with success/error states
  • Connection status real-time updates
  • Disconnect with data retention prompt

Data Sync

  • Initial sync pulls all records
  • Incremental sync only new/updated records
  • Conflict resolution working
  • Sync errors logged and retryable

Dashboard

  • Loads in under 2 seconds
  • All widgets render with real data
  • AI insights display and are dismissible
  • Responsive on tablet and desktop

Performance

  • Lighthouse score > 90
  • First Contentful Paint < 1.5s
  • Time to Interactive < 3s
  • No memory leaks

πŸ”— INTEGRATION POINTS

n8n Webhook Endpoints

POST /webhooks/n8n/sync-complete
POST /webhooks/n8n/workflow-trigger
POST /webhooks/n8n/insight-generated

External APIs

HubSpot API: https://api.hubapi.com/
Salesforce API: https://login.salesforce.com/services/oauth2/
Slack API: https://slack.com/api/
Gmail API: https://gmail.googleapis.com/
Notion API: https://api.notion.com/

Internal Services

Edge Workers: https://api.integratewise.com/
n8n: https://n8n.integratewise.com/

πŸ“ NOTES FOR GENSPARK OPUS

  1. Theme First: Every component must check useTheme() and apply appropriate styles
  2. Mobile Ready: Use Tailwind responsive classes (md:, lg:) for all layouts
  3. Loading States: Every async operation needs skeleton/spinner
  4. Error Boundaries: Wrap major sections with error boundaries
  5. Accessibility: Use semantic HTML, ARIA labels, keyboard navigation
  6. Type Safety: Full TypeScript, no any types
  7. Comments: Add JSDoc comments for complex functions
  8. Testing: Include unit tests for critical business logic

🎨 VISUAL REFERENCE

Individual Theme (MailerLite-style):

  • Clean white backgrounds with subtle green accents
  • Rounded corners everywhere
  • Friendly, approachable feel
  • Light shadows, generous padding
  • Single primary CTA per section

Enterprise Theme (Corporate Blue):

  • Professional gray backgrounds with navy accents
  • Sharp corners, structured layouts
  • Dense information display
  • Multiple actions visible
  • Data-heavy dashboards

END OF PROMPT

Now go build something amazing! πŸš€