{"slug":"internal/architecture/GENSPARK_OPUS_INTEGRATEWISE_APP_PROMPT","title":"GENSPARK OPUS: IntegrateWise Core App Completion & Integration Prompt","section":"internal","sectionLabel":"Internal","status":"unclassified","type":"document","path":"internal/architecture/GENSPARK_OPUS_INTEGRATEWISE_APP_PROMPT.mdx","bytes":37495,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n**Project:** IntegrateWise AI Workspace Platform  \n**Version:** Production Ready v1.0  \n**Date:** January 2026  \n**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)\n\n---\n\n## 🎯 MISSION OVERVIEW\n\nYou 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:\n\n1. **Consolidate** all separated app parts into ONE unified Next.js application\n2. **Complete** the remaining 48% of core functionality\n3. **Apply dual-theme design system** (MailerLite for individuals, Corporate Blue for enterprise)\n4. **Ensure production readiness** with proper error handling, loading states, and responsive design\n\n---\n\n## 🎨 DESIGN SYSTEM SPECIFICATION\n\n### Theme 1: Individual/Freelancer Mode (MailerLite-Inspired)\n\n**Philosophy:** Clean, friendly, approachable—\"Making the complex simple\"\n\n```css\n/* Individual Theme - MailerLite Style */\n:root[data-theme=\"individual\"] {\n  /* Primary Colors */\n  --primary-green: #09c269; /* MailerLite signature green */\n  --primary-green-light: #0ed47b; /* Hover state */\n  --primary-green-dark: #07a558; /* Active state */\n  --primary-green-subtle: #e8f8f0; /* Backgrounds */\n\n  /* Coral/Warm Accents */\n  --accent-coral: #ff6b6b; /* CTAs, notifications */\n  --accent-coral-light: #ff8787; /* Hover */\n  --accent-coral-subtle: #fff0f0; /* Light background */\n\n  /* Neutrals */\n  --background: #ffffff;\n  --background-secondary: #f9fafb;\n  --background-tertiary: #f3f4f6;\n  --text-primary: #1a1a2e;\n  --text-secondary: #6b7280;\n  --text-muted: #9ca3af;\n  --border: #e5e7eb;\n  --border-light: #f3f4f6;\n\n  /* Semantic */\n  --success: #09c269;\n  --warning: #f59e0b;\n  --error: #ef4444;\n  --info: #3b82f6;\n\n  /* Shadows */\n  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);\n  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);\n\n  /* Radius */\n  --radius-sm: 6px;\n  --radius-md: 8px;\n  --radius-lg: 12px;\n  --radius-xl: 16px;\n  --radius-full: 9999px;\n\n  /* Typography */\n  --font-primary: \"Inter\", -apple-system, BlinkMacSystemFont, sans-serif;\n  --font-display: \"Plus Jakarta Sans\", var(--font-primary);\n}\n```\n\n**Individual Theme UI Characteristics:**\n\n- Rounded buttons with generous padding (radius-lg)\n- Soft shadows, no hard edges\n- Generous whitespace\n- Friendly, conversational copy\n- Single-column layouts for simplicity\n- Warm, inviting illustrations\n- Animated micro-interactions (subtle bounces, fades)\n- Emojis acceptable in headers/CTAs\n\n### Theme 2: Corporate/Enterprise Mode\n\n**Philosophy:** Professional, trustworthy, powerful—\"Enterprise-grade reliability\"\n\n```css\n/* Enterprise Theme - Corporate Blue */\n:root[data-theme=\"enterprise\"] {\n  /* Primary Colors */\n  --primary-blue: #1e3a8a; /* Deep corporate blue */\n  --primary-blue-light: #2563eb; /* Hover state */\n  --primary-blue-dark: #1e40af; /* Active state */\n  --primary-blue-subtle: #eff6ff; /* Backgrounds */\n\n  /* Secondary Navy */\n  --secondary-navy: #0f172a; /* Headers, important text */\n  --secondary-slate: #334155; /* Body text */\n\n  /* Accent */\n  --accent-teal: #0891b2; /* Links, highlights */\n  --accent-teal-light: #22d3ee; /* Hover */\n  --accent-gold: #d97706; /* Premium features */\n\n  /* Neutrals */\n  --background: #ffffff;\n  --background-secondary: #f8fafc;\n  --background-tertiary: #f1f5f9;\n  --text-primary: #0f172a;\n  --text-secondary: #475569;\n  --text-muted: #94a3b8;\n  --border: #cbd5e1;\n  --border-light: #e2e8f0;\n\n  /* Semantic */\n  --success: #059669;\n  --warning: #d97706;\n  --error: #dc2626;\n  --info: #2563eb;\n\n  /* Shadows */\n  --shadow-sm: 0 1px 3px rgba(15, 23, 42, 0.08);\n  --shadow-md: 0 4px 8px -2px rgba(15, 23, 42, 0.1);\n  --shadow-lg: 0 12px 24px -4px rgba(15, 23, 42, 0.12);\n\n  /* Radius */\n  --radius-sm: 4px;\n  --radius-md: 6px;\n  --radius-lg: 8px;\n  --radius-xl: 12px;\n  --radius-full: 9999px;\n\n  /* Typography */\n  --font-primary: \"Inter\", -apple-system, BlinkMacSystemFont, sans-serif;\n  --font-display: \"IBM Plex Sans\", var(--font-primary);\n}\n```\n\n**Enterprise Theme UI Characteristics:**\n\n- Sharp, professional corners (radius-sm to radius-md)\n- Structured data tables with sorting\n- Dense information display\n- Formal, precise language\n- Multi-column dashboards\n- Detailed analytics charts\n- Subtle, professional animations\n- No emojis, icons only from professional icon sets (Lucide, Heroicons)\n\n---\n\n## 🏗️ APPLICATION ARCHITECTURE\n\n### Tech Stack\n\n```yaml\nFrontend:\n  framework: Next.js 14+ (App Router)\n  styling: Tailwind CSS 3.4+\n  components: Shadcn/ui\n  state: Zustand + React Query\n  forms: React Hook Form + Zod\n  charts: Recharts\n  icons: Lucide React\n\nBackend:\n  runtime: Cloudflare Workers (Edge)\n  database: Supabase (PostgreSQL + RLS)\n  auth: Supabase Auth + NextAuth.js\n  queue: Cloudflare Queues\n  storage: Cloudflare R2\n  cache: Cloudflare KV\n\nAI Layer:\n  orchestration: n8n (self-hosted)\n  llm_providers: [OpenAI, Anthropic, OpenRouter]\n  agents: Custom n8n workflows\n\nInfrastructure:\n  hosting: Vercel (Frontend) + Cloudflare (Edge)\n  monitoring: Better Stack\n  error_tracking: Sentry\n```\n\n### Directory Structure\n\n```\nintegratewise/\n├── apps/\n│   └── web/                          # Main Next.js application\n│       ├── app/\n│       │   ├── (auth)/               # Auth routes (login, signup, reset)\n│       │   │   ├── login/\n│       │   │   ├── signup/\n│       │   │   └── verify/\n│       │   ├── (dashboard)/          # Protected dashboard routes\n│       │   │   ├── layout.tsx        # Dashboard shell with sidebar\n│       │   │   ├── page.tsx          # Home/Overview\n│       │   │   ├── connect/          # Tool connections\n│       │   │   ├── sync/             # Data synchronization\n│       │   │   ├── automate/         # Automation workflows\n│       │   │   ├── create/           # Content creation\n│       │   │   ├── insights/         # AI insights & analytics\n│       │   │   ├── settings/         # Account settings\n│       │   │   └── admin/            # Admin panel (enterprise)\n│       │   ├── (marketing)/          # Public pages\n│       │   │   ├── page.tsx          # Landing page\n│       │   │   ├── pricing/\n│       │   │   ├── features/\n│       │   │   └── blog/\n│       │   ├── api/                  # API routes\n│       │   │   ├── auth/\n│       │   │   ├── webhooks/\n│       │   │   ├── connectors/\n│       │   │   └── ai/\n│       │   ├── layout.tsx\n│       │   └── globals.css\n│       ├── components/\n│       │   ├── ui/                   # Shadcn components\n│       │   ├── theme/                # Theme provider & switcher\n│       │   ├── dashboard/            # Dashboard-specific components\n│       │   ├── connectors/           # Integration cards & flows\n│       │   ├── automation/           # Workflow builder components\n│       │   └── shared/               # Shared components\n│       ├── lib/\n│       │   ├── supabase/\n│       │   ├── auth/\n│       │   ├── api/\n│       │   └── utils/\n│       ├── hooks/\n│       ├── stores/\n│       └── types/\n├── packages/\n│   ├── database/                     # Supabase schema & migrations\n│   ├── connectors/                   # Integration adapters\n│   └── shared/                       # Shared utilities\n├── workers/\n│   ├── webhooks/                     # Webhook processor\n│   ├── sync/                         # Data sync worker\n│   └── queue/                        # Queue consumer\n└── docs/\n```\n\n---\n\n## 📦 CORE FEATURES TO IMPLEMENT\n\n### 1. Authentication & Onboarding (Priority: Critical)\n\n```typescript\n// 60-Second AI-First Onboarding Flow\nconst onboardingSteps = [\n  {\n    step: 1,\n    name: \"signup\",\n    duration: \"15s\",\n    component: \"SignupForm\",\n    fields: [\"email\", \"password\", \"company_name\"],\n    theme_detection: true, // Auto-detect individual vs enterprise\n  },\n  {\n    step: 2,\n    name: \"profile\",\n    duration: \"10s\",\n    component: \"ProfileSetup\",\n    ai_assist: true, // AI suggests based on email domain\n    fields: [\"role\", \"team_size\", \"primary_goal\"],\n  },\n  {\n    step: 3,\n    name: \"connect_first_tool\",\n    duration: \"20s\",\n    component: \"QuickConnect\",\n    suggested_tools: [\"HubSpot\", \"Salesforce\", \"Slack\", \"Google Workspace\"],\n    oauth_popup: true,\n  },\n  {\n    step: 4,\n    name: \"ai_insights_preview\",\n    duration: \"15s\",\n    component: \"InsightsPreview\",\n    show_sample_data: true,\n    cta: \"Start Free Trial\",\n  },\n];\n```\n\n**Implementation Requirements:**\n\n- Supabase Auth with email/password + OAuth (Google, Microsoft)\n- Magic link login option\n- SSO/SAML ready for enterprise (config-based)\n- Theme auto-detection based on email domain (corporate = enterprise theme)\n- Progress indicator showing time remaining\n- Skip option at each step\n\n### 2. Connection Hub (Priority: Critical)\n\n```typescript\n// Supported Integrations - Phase 1\nconst connectors = {\n  crm: [\n    { id: \"hubspot\", name: \"HubSpot\", oauth: true, status: \"ready\" },\n    { id: \"salesforce\", name: \"Salesforce\", oauth: true, status: \"ready\" },\n    { id: \"pipedrive\", name: \"Pipedrive\", oauth: true, status: \"beta\" },\n  ],\n  communication: [\n    { id: \"slack\", name: \"Slack\", oauth: true, status: \"ready\" },\n    { id: \"teams\", name: \"Microsoft Teams\", oauth: true, status: \"ready\" },\n    { id: \"gmail\", name: \"Gmail\", oauth: true, status: \"ready\" },\n  ],\n  productivity: [\n    { id: \"notion\", name: \"Notion\", oauth: true, status: \"ready\" },\n    { id: \"asana\", name: \"Asana\", oauth: true, status: \"ready\" },\n    { id: \"monday\", name: \"Monday.com\", oauth: true, status: \"beta\" },\n  ],\n  data: [\n    { id: \"google_sheets\", name: \"Google Sheets\", oauth: true, status: \"ready\" },\n    { id: \"airtable\", name: \"Airtable\", api_key: true, status: \"ready\" },\n  ],\n};\n\n// Connection Card Component Props\ninterface ConnectorCardProps {\n  connector: Connector;\n  status: \"connected\" | \"disconnected\" | \"syncing\" | \"error\";\n  lastSync?: Date;\n  recordCount?: number;\n  onConnect: () => void;\n  onDisconnect: () => void;\n  onSync: () => void;\n}\n```\n\n**UI Requirements:**\n\n- Grid layout showing all available connectors\n- Status badges (Connected/Disconnected/Syncing/Error)\n- OAuth popup flow with loading states\n- Connection health indicators\n- \"Last synced\" timestamps\n- Record count display\n- Quick actions (Sync Now, Disconnect, Configure)\n\n### 3. Data Synchronization Engine (Priority: High)\n\n```typescript\n// Sync Configuration Schema\ninterface SyncConfig {\n  id: string;\n  source: {\n    connector_id: string;\n    objects: string[]; // [\"contacts\", \"deals\", \"companies\"]\n    filters?: Record<string, any>;\n  };\n  destination: \"atlas_spine\"; // Internal unified database\n  schedule: {\n    type: \"realtime\" | \"scheduled\" | \"manual\";\n    interval?: \"5m\" | \"15m\" | \"1h\" | \"6h\" | \"24h\";\n    timezone?: string;\n  };\n  mapping: {\n    field_mappings: FieldMapping[];\n    conflict_resolution: \"source_wins\" | \"dest_wins\" | \"most_recent\";\n  };\n  status: \"active\" | \"paused\" | \"error\";\n}\n\n// ATLAS SPINE - Unified Data Model\ninterface AtlasSpineSchema {\n  // Core Entities\n  accounts: {\n    id: string;\n    external_ids: Record<string, string>; // {\"hubspot\": \"123\", \"salesforce\": \"abc\"}\n    name: string;\n    domain: string;\n    industry: string;\n    employee_count: number;\n    arr: number;\n    health_score: number;\n    custom_fields: Record<string, any>;\n    created_at: Date;\n    updated_at: Date;\n  };\n\n  contacts: {\n    id: string;\n    external_ids: Record<string, string>;\n    account_id: string;\n    email: string;\n    first_name: string;\n    last_name: string;\n    title: string;\n    phone: string;\n    engagement_score: number;\n    custom_fields: Record<string, any>;\n  };\n\n  activities: {\n    id: string;\n    type: \"email\" | \"call\" | \"meeting\" | \"note\" | \"task\";\n    account_id: string;\n    contact_id: string;\n    subject: string;\n    body: string;\n    sentiment: \"positive\" | \"neutral\" | \"negative\";\n    timestamp: Date;\n  };\n\n  deals: {\n    id: string;\n    external_ids: Record<string, string>;\n    account_id: string;\n    name: string;\n    amount: number;\n    stage: string;\n    probability: number;\n    close_date: Date;\n    owner_id: string;\n  };\n}\n```\n\n**Sync Dashboard Requirements:**\n\n- Real-time sync status visualization\n- Record count comparisons (source vs destination)\n- Error log with retry functionality\n- Field mapping editor (drag-and-drop)\n- Sync history with diff viewer\n- Pause/Resume controls\n\n### 4. Automation Workflow Builder (Priority: High)\n\n```typescript\n// Workflow Definition\ninterface Workflow {\n  id: string;\n  name: string;\n  description: string;\n  trigger: WorkflowTrigger;\n  actions: WorkflowAction[];\n  conditions?: WorkflowCondition[];\n  status: \"active\" | \"draft\" | \"paused\";\n  runs_count: number;\n  last_run: Date;\n  created_by: string;\n}\n\n// Pre-built Templates\nconst workflowTemplates = [\n  {\n    id: \"welcome_sequence\",\n    name: \"New Customer Welcome Sequence\",\n    category: \"onboarding\",\n    trigger: { type: \"deal_closed_won\" },\n    actions: [\n      { type: \"send_slack_message\", delay: \"0m\" },\n      { type: \"create_task\", delay: \"1d\" },\n      { type: \"send_email\", delay: \"3d\" },\n    ],\n  },\n  {\n    id: \"churn_alert\",\n    name: \"Churn Risk Alert\",\n    category: \"retention\",\n    trigger: { type: \"health_score_drop\", threshold: 30 },\n    actions: [\n      { type: \"send_slack_alert\", channel: \"#cs-alerts\" },\n      { type: \"create_task\", assignee: \"account_owner\" },\n      { type: \"send_email\", template: \"churn_intervention\" },\n    ],\n  },\n  {\n    id: \"renewal_reminder\",\n    name: \"90-Day Renewal Reminder\",\n    category: \"renewals\",\n    trigger: { type: \"days_until_renewal\", days: 90 },\n    actions: [\n      { type: \"send_email\", template: \"renewal_notice\" },\n      { type: \"create_deal\", stage: \"renewal\" },\n    ],\n  },\n];\n```\n\n**Workflow Builder UI:**\n\n- Visual canvas with drag-and-drop nodes\n- Trigger selection panel (events from connected tools)\n- Action library with categorization\n- Condition builder with AND/OR logic\n- Test mode with sample data\n- Version history\n- Analytics (runs, success rate, avg duration)\n\n### 5. AI Insights Dashboard (Priority: High)\n\n```typescript\n// AI-Generated Insights\ninterface InsightCard {\n  id: string;\n  type: \"health_alert\" | \"opportunity\" | \"risk\" | \"trend\" | \"recommendation\";\n  priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n  title: string;\n  description: string;\n  data: {\n    accounts_affected?: number;\n    potential_impact?: number;\n    confidence: number;\n  };\n  actions: InsightAction[];\n  dismissed: boolean;\n  created_at: Date;\n}\n\n// Dashboard Widgets\nconst dashboardWidgets = [\n  {\n    id: \"health_overview\",\n    type: \"donut_chart\",\n    title: \"Portfolio Health\",\n    data_source: \"accounts.health_score\",\n    segments: [\"healthy\", \"at_risk\", \"critical\"],\n  },\n  {\n    id: \"arr_trend\",\n    type: \"area_chart\",\n    title: \"ARR Trend\",\n    data_source: \"accounts.arr\",\n    timeframe: \"12_months\",\n  },\n  {\n    id: \"engagement_heatmap\",\n    type: \"heatmap\",\n    title: \"Engagement Activity\",\n    data_source: \"activities\",\n    dimensions: [\"day_of_week\", \"hour\"],\n  },\n  {\n    id: \"upcoming_renewals\",\n    type: \"table\",\n    title: \"Upcoming Renewals\",\n    data_source: \"accounts\",\n    filters: { renewal_in_days: { lte: 90 } },\n  },\n];\n```\n\n**Dashboard Requirements:**\n\n- Customizable widget grid (draggable, resizable)\n- AI insights feed with dismiss/action options\n- Real-time data refresh\n- Export to PDF/CSV\n- Shareable dashboard links\n- Role-based widget visibility\n\n### 6. Content Creation (RENDER) (Priority: Medium)\n\n```typescript\n// Render Templates\ninterface RenderTemplate {\n  id: string;\n  name: string;\n  category: \"qbr\" | \"report\" | \"presentation\" | \"email\";\n  format: \"pdf\" | \"pptx\" | \"docx\" | \"html\";\n  variables: TemplateVariable[];\n  preview_url: string;\n}\n\n// Content Generation Request\ninterface RenderRequest {\n  template_id: string;\n  account_id?: string;\n  data_sources: string[]; // [\"health_scores\", \"activities\", \"deals\"]\n  date_range: { start: Date; end: Date };\n  custom_variables?: Record<string, any>;\n  output_format: \"pdf\" | \"pptx\" | \"docx\";\n}\n```\n\n---\n\n## 🗃️ DATABASE SCHEMA (Supabase)\n\n```sql\n-- Enable RLS\nALTER DATABASE postgres SET \"app.jwt_secret\" TO 'your-jwt-secret';\n\n-- Organizations (Workspaces)\nCREATE TABLE organizations (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  name TEXT NOT NULL,\n  slug TEXT UNIQUE NOT NULL,\n  plan TEXT DEFAULT 'free' CHECK (plan IN ('free', 'pro', 'enterprise')),\n  theme TEXT DEFAULT 'individual' CHECK (theme IN ('individual', 'enterprise')),\n  settings JSONB DEFAULT '{}',\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Users\nCREATE TABLE users (\n  id UUID PRIMARY KEY REFERENCES auth.users(id),\n  organization_id UUID REFERENCES organizations(id),\n  email TEXT NOT NULL,\n  full_name TEXT,\n  avatar_url TEXT,\n  role TEXT DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member', 'viewer')),\n  preferences JSONB DEFAULT '{}',\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Connections (Integrations)\nCREATE TABLE connections (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  connector_type TEXT NOT NULL,\n  name TEXT NOT NULL,\n  credentials JSONB NOT NULL,  -- Encrypted\n  config JSONB DEFAULT '{}',\n  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'paused', 'error', 'disconnected')),\n  last_sync_at TIMESTAMPTZ,\n  sync_error TEXT,\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- ATLAS SPINE: Accounts\nCREATE TABLE atlas_accounts (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  external_ids JSONB DEFAULT '{}',\n  name TEXT NOT NULL,\n  domain TEXT,\n  industry TEXT,\n  employee_count INTEGER,\n  arr DECIMAL(15,2),\n  health_score INTEGER CHECK (health_score >= 0 AND health_score <= 100),\n  lifecycle_stage TEXT,\n  owner_id UUID REFERENCES users(id),\n  custom_fields JSONB DEFAULT '{}',\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- ATLAS SPINE: Contacts\nCREATE TABLE atlas_contacts (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  account_id UUID REFERENCES atlas_accounts(id),\n  external_ids JSONB DEFAULT '{}',\n  email TEXT NOT NULL,\n  first_name TEXT,\n  last_name TEXT,\n  title TEXT,\n  phone TEXT,\n  engagement_score INTEGER DEFAULT 0,\n  custom_fields JSONB DEFAULT '{}',\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- ATLAS SPINE: Activities\nCREATE TABLE atlas_activities (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  account_id UUID REFERENCES atlas_accounts(id),\n  contact_id UUID REFERENCES atlas_contacts(id),\n  type TEXT NOT NULL CHECK (type IN ('email', 'call', 'meeting', 'note', 'task', 'chat')),\n  direction TEXT CHECK (direction IN ('inbound', 'outbound')),\n  subject TEXT,\n  body TEXT,\n  sentiment TEXT CHECK (sentiment IN ('positive', 'neutral', 'negative')),\n  source_connector TEXT,\n  external_id TEXT,\n  occurred_at TIMESTAMPTZ NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Workflows\nCREATE TABLE workflows (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  name TEXT NOT NULL,\n  description TEXT,\n  trigger JSONB NOT NULL,\n  actions JSONB NOT NULL,\n  conditions JSONB,\n  status TEXT DEFAULT 'draft' CHECK (status IN ('draft', 'active', 'paused')),\n  runs_count INTEGER DEFAULT 0,\n  last_run_at TIMESTAMPTZ,\n  created_by UUID REFERENCES users(id),\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- AI Insights\nCREATE TABLE insights (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  organization_id UUID REFERENCES organizations(id) NOT NULL,\n  type TEXT NOT NULL,\n  priority TEXT DEFAULT 'medium' CHECK (priority IN ('critical', 'high', 'medium', 'low')),\n  title TEXT NOT NULL,\n  description TEXT,\n  data JSONB DEFAULT '{}',\n  account_ids UUID[],\n  actions JSONB DEFAULT '[]',\n  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'dismissed', 'actioned')),\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Row Level Security Policies\nALTER TABLE organizations ENABLE ROW LEVEL SECURITY;\nALTER TABLE users ENABLE ROW LEVEL SECURITY;\nALTER TABLE connections ENABLE ROW LEVEL SECURITY;\nALTER TABLE atlas_accounts ENABLE ROW LEVEL SECURITY;\nALTER TABLE atlas_contacts ENABLE ROW LEVEL SECURITY;\nALTER TABLE atlas_activities ENABLE ROW LEVEL SECURITY;\nALTER TABLE workflows ENABLE ROW LEVEL SECURITY;\nALTER TABLE insights ENABLE ROW LEVEL SECURITY;\n\n-- RLS Policies (example for atlas_accounts)\nCREATE POLICY \"Users can view their org's accounts\"\n  ON atlas_accounts FOR SELECT\n  USING (organization_id IN (\n    SELECT organization_id FROM users WHERE id = auth.uid()\n  ));\n\nCREATE POLICY \"Users can insert accounts in their org\"\n  ON atlas_accounts FOR INSERT\n  WITH CHECK (organization_id IN (\n    SELECT organization_id FROM users WHERE id = auth.uid()\n  ));\n```\n\n---\n\n## 🎯 COMPONENT SPECIFICATIONS\n\n### 1. Theme Provider & Switcher\n\n```tsx\n// components/theme/theme-provider.tsx\n\"use client\";\n\n\ntype Theme = \"individual\" | \"enterprise\";\n\ninterface ThemeContextType {\n  theme: Theme;\n  setTheme: (theme: Theme) => void;\n  toggleTheme: () => void;\n}\n\nconst ThemeContext = createContext<ThemeContextType | undefined>(undefined);\n\n  const [theme, setTheme] = useState<Theme>(\"individual\");\n\n  useEffect(() => {\n    // Load from localStorage or user preferences\n    const saved = localStorage.getItem(\"iw-theme\") as Theme;\n    if (saved) setTheme(saved);\n  }, []);\n\n  useEffect(() => {\n    document.documentElement.setAttribute(\"data-theme\", theme);\n    localStorage.setItem(\"iw-theme\", theme);\n  }, [theme]);\n\n  const toggleTheme = () => {\n    setTheme(theme === \"individual\" ? \"enterprise\" : \"individual\");\n  };\n\n  return (\n    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>\n      {children}\n    </ThemeContext.Provider>\n  );\n}\n\n  const context = useContext(ThemeContext);\n  if (!context) throw new Error(\"useTheme must be used within ThemeProvider\");\n  return context;\n};\n```\n\n### 2. Dashboard Shell Layout\n\n```tsx\n// app/(dashboard)/layout.tsx\n\n  return (\n    <ThemeProvider>\n      <div className=\"flex h-screen bg-background\">\n        <Sidebar />\n        <div className=\"flex-1 flex flex-col overflow-hidden\">\n          <Header />\n          <main className=\"flex-1 overflow-y-auto p-6\">{children}</main>\n        </div>\n      </div>\n    </ThemeProvider>\n  );\n}\n```\n\n### 3. Connector Card Component\n\n```tsx\n// components/connectors/connector-card.tsx\n\"use client\";\n\n\ninterface ConnectorCardProps {\n  connector: {\n    id: string;\n    name: string;\n    icon: string;\n    category: string;\n  };\n  connection?: {\n    status: \"connected\" | \"disconnected\" | \"syncing\" | \"error\";\n    lastSync?: Date;\n    recordCount?: number;\n    error?: string;\n  };\n  onConnect: () => void;\n  onDisconnect: () => void;\n  onSync: () => void;\n  onConfigure: () => void;\n}\n\n  connector,\n  connection,\n  onConnect,\n  onDisconnect,\n  onSync,\n  onConfigure,\n}: ConnectorCardProps) {\n  const { theme } = useTheme();\n  const isConnected = connection?.status === \"connected\";\n  const isSyncing = connection?.status === \"syncing\";\n  const hasError = connection?.status === \"error\";\n\n  const statusConfig = {\n    connected: {\n      label: \"Connected\",\n      color: \"bg-success/10 text-success\",\n      icon: CheckCircle,\n    },\n    disconnected: {\n      label: \"Not Connected\",\n      color: \"bg-muted text-muted-foreground\",\n      icon: Unplug,\n    },\n    syncing: {\n      label: \"Syncing...\",\n      color: \"bg-info/10 text-info\",\n      icon: Loader2,\n    },\n    error: {\n      label: \"Error\",\n      color: \"bg-error/10 text-error\",\n      icon: AlertCircle,\n    },\n  };\n\n  const status = connection?.status || \"disconnected\";\n  const StatusIcon = statusConfig[status].icon;\n\n  return (\n    \n      <CardHeader className=\"flex flex-row items-center justify-between pb-2\">\n        <div className=\"flex items-center gap-3\">\n          <img src={connector.icon} alt={connector.name} className=\"w-10 h-10 rounded-lg\" />\n          <div>\n            <CardTitle className=\"text-lg\">{connector.name}</CardTitle>\n            <p className=\"text-sm text-muted-foreground capitalize\">{connector.category}</p>\n          </div>\n        </div>\n        \n          <StatusIcon className={cn(\"w-3 h-3 mr-1\", isSyncing && \"animate-spin\")} />\n          {statusConfig[status].label}\n        \n      </CardHeader>\n\n      <CardContent>\n        {isConnected && (\n          <div className=\"mb-4 space-y-1 text-sm text-muted-foreground\">\n            {connection.lastSync && <p>Last synced: {formatRelativeTime(connection.lastSync)}</p>}\n            {connection.recordCount !== undefined && (\n              <p>{connection.recordCount.toLocaleString()} records synced</p>\n            )}\n          </div>\n        )}\n\n        {hasError && connection?.error && (\n          <div className=\"mb-4 p-3 rounded-md bg-error/10 text-error text-sm\">\n            {connection.error}\n          </div>\n        )}\n\n        <div className=\"flex gap-2\">\n          {!isConnected ? (\n            <Button\n              onClick={onConnect}\n              className={cn(\n                \"flex-1\",\n                theme === \"individual\"\n                  ? \"bg-primary-green hover:bg-primary-green-light\"\n                  : \"bg-primary-blue hover:bg-primary-blue-light\"\n              )}\n            >\n              Connect\n            </Button>\n          ) : (\n            <>\n              <Button variant=\"outline\" size=\"sm\" onClick={onSync} disabled={isSyncing}>\n                <RefreshCw className={cn(\"w-4 h-4 mr-1\", isSyncing && \"animate-spin\")} />\n                Sync\n              </Button>\n              <Button variant=\"outline\" size=\"sm\" onClick={onConfigure}>\n                <Settings className=\"w-4 h-4 mr-1\" />\n                Configure\n              </Button>\n              <Button\n                variant=\"ghost\"\n                size=\"sm\"\n                onClick={onDisconnect}\n                className=\"text-error hover:text-error hover:bg-error/10\"\n              >\n                <Unplug className=\"w-4 h-4\" />\n              </Button>\n            </>\n          )}\n        </div>\n      </CardContent>\n    \n  );\n}\n```\n\n### 4. Insights Card Component\n\n```tsx\n// components/dashboard/insight-card.tsx\n\"use client\";\n\n\ninterface InsightCardProps {\n  insight: {\n    id: string;\n    type: \"health_alert\" | \"opportunity\" | \"risk\" | \"trend\" | \"recommendation\";\n    priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n    title: string;\n    description: string;\n    data: {\n      accounts_affected?: number;\n      potential_impact?: number;\n      confidence: number;\n    };\n    actions: Array<{\n      label: string;\n      action: string;\n    }>;\n  };\n  onDismiss: (id: string) => void;\n  onAction: (id: string, action: string) => void;\n}\n\n  const { theme } = useTheme();\n\n  const typeConfig = {\n    health_alert: { icon: AlertTriangle, color: \"text-error\" },\n    opportunity: { icon: TrendingUp, color: \"text-success\" },\n    risk: { icon: TrendingDown, color: \"text-warning\" },\n    trend: { icon: TrendingUp, color: \"text-info\" },\n    recommendation: { icon: Lightbulb, color: \"text-accent-coral\" },\n  };\n\n  const priorityColors = {\n    critical: \"bg-error text-white\",\n    high: \"bg-warning text-white\",\n    medium: \"bg-info text-white\",\n    low: \"bg-muted text-muted-foreground\",\n  };\n\n  const TypeIcon = typeConfig[insight.type].icon;\n\n  return (\n    \n      <CardContent className=\"p-4\">\n        <div className=\"flex items-start gap-3\">\n          <div\n            className={cn(\n              \"p-2 rounded-lg\",\n              theme === \"individual\" ? \"bg-primary-green-subtle\" : \"bg-primary-blue-subtle\"\n            )}\n          >\n            <TypeIcon className={cn(\"w-5 h-5\", typeConfig[insight.type].color)} />\n          </div>\n\n          <div className=\"flex-1 min-w-0\">\n            <div className=\"flex items-center gap-2 mb-1\">\n              \n                {insight.priority}\n              \n              {insight.data.accounts_affected && (\n                <span className=\"text-xs text-muted-foreground\">\n                  {insight.data.accounts_affected} accounts\n                </span>\n              )}\n            </div>\n\n            <h4 className=\"font-semibold text-text-primary mb-1\">{insight.title}</h4>\n            <p className=\"text-sm text-text-secondary mb-3\">{insight.description}</p>\n\n            {insight.data.potential_impact && (\n              <p className=\"text-sm font-medium mb-3\">\n                Potential impact: ${insight.data.potential_impact.toLocaleString()}\n              </p>\n            )}\n\n            <div className=\"flex items-center gap-2\">\n              {insight.actions.map((action, index) => (\n                <Button\n                  key={index}\n                  size=\"sm\"\n                  variant={index === 0 ? \"default\" : \"outline\"}\n                  onClick={() => onAction(insight.id, action.action)}\n                  className={cn(\n                    index === 0 &&\n                      theme === \"individual\" &&\n                      \"bg-primary-green hover:bg-primary-green-light\",\n                    index === 0 &&\n                      theme === \"enterprise\" &&\n                      \"bg-primary-blue hover:bg-primary-blue-light\"\n                  )}\n                >\n                  {action.label}\n                  <ChevronRight className=\"w-4 h-4 ml-1\" />\n                </Button>\n              ))}\n            </div>\n          </div>\n\n          <Button\n            variant=\"ghost\"\n            size=\"sm\"\n            className=\"text-muted-foreground hover:text-text-primary\"\n            onClick={() => onDismiss(insight.id)}\n          >\n            <X className=\"w-4 h-4\" />\n          </Button>\n        </div>\n\n        \n        <div className=\"mt-3 pt-3 border-t border-border\">\n          <div className=\"flex items-center gap-2\">\n            <span className=\"text-xs text-muted-foreground\">Confidence:</span>\n            <div className=\"flex-1 h-1.5 bg-muted rounded-full overflow-hidden\">\n              <div\n                className={cn(\n                  \"h-full rounded-full\",\n                  insight.data.confidence >= 80\n                    ? \"bg-success\"\n                    : insight.data.confidence >= 60\n                      ? \"bg-warning\"\n                      : \"bg-error\"\n                )}\n                style={{ width: `${insight.data.confidence}%` }}\n              />\n            </div>\n            <span className=\"text-xs font-medium\">{insight.data.confidence}%</span>\n          </div>\n        </div>\n      </CardContent>\n    \n  );\n}\n```\n\n---\n\n## 🚀 IMPLEMENTATION PRIORITY ORDER\n\n### Phase 1: Foundation (Week 1-2)\n\n1. ✅ Project scaffolding with Next.js 14\n2. ✅ Theme system implementation (Individual + Enterprise)\n3. ✅ Supabase setup with RLS policies\n4. ✅ Authentication flow (signup, login, magic link)\n5. ✅ Dashboard shell layout\n6. ✅ Basic navigation and routing\n\n### Phase 2: Core Integrations (Week 3-4)\n\n1. Connection Hub UI\n2. OAuth flow implementation (HubSpot, Salesforce, Slack)\n3. Connection management (CRUD)\n4. Basic sync engine (pull data to ATLAS SPINE)\n5. Sync status monitoring\n\n### Phase 3: Intelligence Layer (Week 5-6)\n\n1. AI Insights dashboard\n2. Health score calculation\n3. Widget system (charts, tables, metrics)\n4. Insight generation via n8n workflows\n5. Action handlers\n\n### Phase 4: Automation (Week 7-8)\n\n1. Workflow builder UI\n2. Trigger configuration\n3. Action library\n4. Workflow execution engine (n8n integration)\n5. Workflow templates\n\n### Phase 5: Polish & Launch (Week 9-10)\n\n1. RENDER (content generation)\n2. Settings & preferences\n3. Admin panel (enterprise)\n4. Performance optimization\n5. Error handling & edge cases\n6. Documentation\n\n---\n\n## 📋 ACCEPTANCE CRITERIA\n\n### Theme System\n\n- [ ] Theme toggle works instantly without page reload\n- [ ] All components respect current theme\n- [ ] Theme persists across sessions\n- [ ] Theme auto-detected from organization settings\n\n### Authentication\n\n- [ ] Signup completes in under 60 seconds\n- [ ] OAuth flows for Google/Microsoft\n- [ ] Magic link login works\n- [ ] Session management with refresh tokens\n- [ ] Protected routes redirect to login\n\n### Connections\n\n- [ ] At least 5 connectors working (HubSpot, Salesforce, Slack, Gmail, Notion)\n- [ ] OAuth popup flow with success/error states\n- [ ] Connection status real-time updates\n- [ ] Disconnect with data retention prompt\n\n### Data Sync\n\n- [ ] Initial sync pulls all records\n- [ ] Incremental sync only new/updated records\n- [ ] Conflict resolution working\n- [ ] Sync errors logged and retryable\n\n### Dashboard\n\n- [ ] Loads in under 2 seconds\n- [ ] All widgets render with real data\n- [ ] AI insights display and are dismissible\n- [ ] Responsive on tablet and desktop\n\n### Performance\n\n- [ ] Lighthouse score > 90\n- [ ] First Contentful Paint < 1.5s\n- [ ] Time to Interactive < 3s\n- [ ] No memory leaks\n\n---\n\n## 🔗 INTEGRATION POINTS\n\n### n8n Webhook Endpoints\n\n```\nPOST /webhooks/n8n/sync-complete\nPOST /webhooks/n8n/workflow-trigger\nPOST /webhooks/n8n/insight-generated\n```\n\n### External APIs\n\n```\nHubSpot API: https://api.hubapi.com/\nSalesforce API: https://login.salesforce.com/services/oauth2/\nSlack API: https://slack.com/api/\nGmail API: https://gmail.googleapis.com/\nNotion API: https://api.notion.com/\n```\n\n### Internal Services\n\n```\nEdge Workers: https://api.integratewise.com/\nn8n: https://n8n.integratewise.com/\n```\n\n---\n\n## 📝 NOTES FOR GENSPARK OPUS\n\n1. **Theme First**: Every component must check `useTheme()` and apply appropriate styles\n2. **Mobile Ready**: Use Tailwind responsive classes (md:, lg:) for all layouts\n3. **Loading States**: Every async operation needs skeleton/spinner\n4. **Error Boundaries**: Wrap major sections with error boundaries\n5. **Accessibility**: Use semantic HTML, ARIA labels, keyboard navigation\n6. **Type Safety**: Full TypeScript, no `any` types\n7. **Comments**: Add JSDoc comments for complex functions\n8. **Testing**: Include unit tests for critical business logic\n\n---\n\n## 🎨 VISUAL REFERENCE\n\n**Individual Theme (MailerLite-style):**\n\n- Clean white backgrounds with subtle green accents\n- Rounded corners everywhere\n- Friendly, approachable feel\n- Light shadows, generous padding\n- Single primary CTA per section\n\n**Enterprise Theme (Corporate Blue):**\n\n- Professional gray backgrounds with navy accents\n- Sharp corners, structured layouts\n- Dense information display\n- Multiple actions visible\n- Data-heavy dashboards\n\n---\n\n**END OF PROMPT**\n\nNow go build something amazing! 🚀\n"}