# 🌐 Velo Site Content & SEO Engine API Documentation

This document serves as the absolute source of truth for AI coding agents (Claude Code, Antigravity, Cursor) and human engineers tasked with converting bespoke marketing websites into client-editable platforms managed directly from the Velo Dashboard.

---

## 🎯 Architecture Overview

```mermaid
flowchart LR
    A["Client Edits in Velo Cockpit (/dashboard/site-editor)"] --> B["Sanity Content Lake (Global CDN)"]
    B --> C["Client Website (Next.js / Astro)"]
    C -->|Fallback if empty or offline| D["Hardcoded Codebase Defaults"]
```

- **Zero Layout Breakage**: The client edits text, buttons, images, and lists in Velo. The layout, styling, and animations remain 100% protected in the codebase.
- **Sub-50ms Edge Performance**: The frontend queries Sanity's Edge CDN (`cdn.sanity.io`) with `useCdn: true`.
- **Zero-Flicker Code Fallbacks**: If Sanity is empty, offline, or experiencing network latency, the site instantly renders the original hardcoded code default.
- **Tenant Isolation**: Each client organization in Velo has its own isolated Sanity project dataset. Org A can never see or touch Org B's content.

---

## 📋 The 4-Layer Content Model

Every marketing website managed by Velo breaks down into 4 simple layers:

| Layer | What It Manages | Client Controls in Velo | Codebase Behavior |
| :--- | :--- | :--- | :--- |
| **1. Page Content** | Page-specific headlines, paragraphs, CTA buttons, images, and FAQs. | Text inputs, textarea, image dropzone, button `{ label, href }`, dynamic Q&A list. | Rendered inline via `content['page.section.field'] ?? 'Code Default'`. Non-empty page tabs appear automatically. |
| **2. Collections & Catalogs** | Deep multi-item catalog entities (Treatments, Doctors, Products, Vehicles, Properties, Team Members). | Dedicated catalog manager with collection switcher pills, real-time search, table view, image uploading, and add/edit/delete modals. | Rendered via `await getVeloCollection<T>('collectionId', fallbackItems)`. Schema is 100% dynamic and tenant-agnostic. |
| **3. SEO & Social** | Bulk spreadsheet matrix for `<title>`, `<meta description>`, OpenGraph preview images, and `noIndex` flags. | Full Google search live preview, bulk table editing, status filters (`Missing Meta`, `Missing Title`, `NoIndex`). | Fed directly into Next.js App Router `generateMetadata()` or SSR `<head>`. |
| **4. Local & Branches** | Physical branch locations, NAP consistency, GeoCoordinates, and Google Maps routing. | Clean branch cards with address, phone, WhatsApp, opening hours, and primary HQ toggle. | Injected into LocalBusiness / MedicalClinic multi-branch Google Rich Results JSON-LD. |

---

## 🛠️ Step-by-Step AI Conversion Workflow

When asked to make a website editable via Velo, execute these 3 simple steps:

### Step 1: Add the Universal Client Helper (`lib/velo-content.ts`)
Create `lib/velo-content.ts` in the client's repository:

```typescript
import { createClient } from '@sanity/client';

export interface VeloContentResponse {
  content: Record<string, any>;
  seo: Record<string, { title?: string; description?: string; ogImage?: string; noIndex?: boolean }>;
  businessProfile: {
    archetype?: 'corporate_digital' | 'local_business';
    businessType?: string;
    name?: string;
    phone?: string;
    whatsapp?: string;
    email?: string;
    address?: string;
    locations?: Array<{
      id: string;
      name: string;
      address: string;
      locality?: string;
      city?: string;
      region?: string;
      postalCode?: string;
      country?: string;
      phone?: string;
      whatsapp?: string;
      googleMapsUrl?: string;
      openingHours?: string;
      isPrimary?: boolean;
    }>;
    socials?: Record<string, string>;
  };
  announcement?: {
    enabled?: boolean;
    message?: string;
    badge?: string;
    link?: string;
  };
  lists: Record<string, any[]>;
  collections?: Array<{
    id: string;
    name: string;
    singularName?: string;
    description?: string;
    fields: Array<{
      key: string;
      label: string;
      type: string;
      required?: boolean;
      options?: string[];
      placeholder?: string;
    }>;
    items: Array<Record<string, any>>;
  }>;
}

const VELO_API_URL = process.env.NEXT_PUBLIC_VELO_URL || 'https://velo.baseworks.in';
const ORG_KEY = process.env.NEXT_PUBLIC_VELO_ORG_KEY;

// Cache the resolved Sanity client across requests
let cachedSanityClient: ReturnType<typeof createClient> | null = null;

async function getSanityClient() {
  if (cachedSanityClient) return cachedSanityClient;

  // 1. Direct environment variable override (fastest path)
  if (process.env.NEXT_PUBLIC_SANITY_PROJECT_ID) {
    cachedSanityClient = createClient({
      projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
      dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || 'production',
      apiVersion: '2024-05-15',
      useCdn: true,
    });
    return cachedSanityClient;
  }

  // 2. Dynamic resolution via Velo Gateway using ORG_KEY
  if (!ORG_KEY) return null;

  try {
    const res = await fetch(`${VELO_API_URL}/api/public/site-config?key=${ORG_KEY}`, {
      next: { revalidate: 3600 }, // Cache gateway lookup for 1 hour
    });
    const data = await res.json();
    if (data.success && data.config?.sanity_project_id) {
      cachedSanityClient = createClient({
        projectId: data.config.sanity_project_id,
        dataset: data.config.sanity_dataset || 'production',
        apiVersion: '2024-05-15',
        useCdn: true,
      });
      return cachedSanityClient;
    }
  } catch (err) {
    console.warn('[Velo Content] Gateway lookup failed, using local code fallbacks:', err);
  }
  return null;
}

/**
 * Fetches the site's live content document from Sanity Edge CDN.
 * Returns empty structures if Sanity is not provisioned or offline,
 * allowing code defaults to render without crashing.
 */
export async function getVeloContent(): Promise<VeloContentResponse> {
  const defaultResponse: VeloContentResponse = {
    content: {},
    seo: {},
    businessProfile: {},
    announcement: { enabled: false },
    lists: {},
  };

  try {
    const client = await getSanityClient();
    if (!client) return defaultResponse;

    const doc = await client.fetch(`*[_id == "siteContent"][0]`);
    if (!doc) return defaultResponse;

    // Map both sanitized keys (home__hero__title) and dot-notation (home.hero.title) for frictionless access
    const normalizedContent: Record<string, any> = {};
    for (const [k, v] of Object.entries(doc.content || {})) {
      normalizedContent[k] = v;
      normalizedContent[k.replace(/__/g, '.')] = v;
    }

    const normalizedLists: Record<string, any[]> = {};
    for (const [k, v] of Object.entries(doc.lists || {})) {
      const arr = Array.isArray(v) ? v : [];
      normalizedLists[k] = arr;
      normalizedLists[k.replace(/__/g, '.')] = arr;
    }

    return {
      content: normalizedContent,
      seo: doc.seo || {},
      businessProfile: doc.businessProfile || {},
      announcement: doc.announcement || { enabled: false },
      lists: normalizedLists,
      collections: doc.collections || [],
    };
  } catch (err) {
    console.warn('[Velo Content] Fetch failed, using local code defaults:', err);
    return defaultResponse;
  }
}

/**
 * Fetches items from a registered Velo dynamic collection (e.g. 'treatments', 'doctors', 'products', 'gallery').
 * Returns fallback items if Sanity is unprovisioned, empty, or offline.
 */
export async function getVeloCollection<T = Record<string, any>>(
  collectionId: string,
  fallbackItems: T[] = []
): Promise<T[]> {
  try {
    const data = await getVeloContent();
    const collection = data.collections?.find((c) => c.id === collectionId);
    if (collection && Array.isArray(collection.items) && collection.items.length > 0) {
      return collection.items as T[];
    }
  } catch (err) {
    console.warn('[Velo Collections] Failed to load ' + collectionId + ', using code defaults:', err);
  }
  return fallbackItems;
}

/**
 * Generates Google-compliant Organization JSON-LD markup from the business profile.
 */
export function generateOrganizationJsonLd(profile: VeloContentResponse['businessProfile'], siteUrl = '') {
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: profile.name || undefined,
    url: siteUrl || undefined,
    telephone: profile.phone || undefined,
    email: profile.email || undefined,
    address: profile.address
      ? {
          '@type': 'PostalAddress',
          streetAddress: profile.address,
        }
      : undefined,
    sameAs: profile.socials ? Object.values(profile.socials).filter(Boolean) : undefined,
  };
}
```

---

### Step 2: Use in Next.js Server Components
In your page components (e.g. `app/page.tsx`), call `getVeloContent()` and fall back to the existing code strings:

```tsx
import { getVeloContent, generateOrganizationJsonLd } from '@/lib/velo-content';

export async function generateMetadata() {
  const { seo } = await getVeloContent();
  const homeSeo = seo['home'] || {};

  return {
    title: homeSeo.title ?? 'Your Company — High Impact Results',
    description: homeSeo.description ?? 'Leading provider of enterprise services and solutions.',
    openGraph: homeSeo.ogImage ? { images: [homeSeo.ogImage] } : undefined,
    robots: homeSeo.noIndex ? { index: false, follow: false } : undefined,
  };
}

export default async function HomePage() {
  const { content, businessProfile, lists } = await getVeloContent();
  const jsonLd = generateOrganizationJsonLd(businessProfile);

  const faqs = lists['home.faq.items'] ?? [
    { question: 'What is your turnaround?', answer: 'We deliver in 48 hours.' },
    { question: 'Do you offer support?', answer: 'Yes, 24/7 client support.' },
  ];

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      {/* Hero Headline */}
      <h1>{content['home.hero.title'] ?? 'Scale Your Operations Faster'}</h1>

      {/* Hero Subtitle */}
      <p>{content['home.hero.subtitle'] ?? 'Streamlined operations built for modern businesses.'}</p>

      {/* Primary CTA Button */}
      <a href={content['home.hero.cta']?.href ?? '/contact'}>
        {content['home.hero.cta']?.label ?? 'Get Started'}
      </a>

      {/* Hero Banner Image */}
      <img
        src={content['home.hero.image'] ?? '/images/hero.webp'}
        alt={content['home.hero.image_alt'] ?? 'Hero banner'}
      />

      {/* Repeating FAQ List */}
      <div>
        {faqs.map((faq: any, i: number) => (
          <details key={i}>
            <summary>{faq.question}</summary>
            <p>{faq.answer}</p>
          </details>
        ))}
      </div>
    </>
  );
}
```

---

### Step 3: Run the 1-Line Inventory Sync (`scripts/velo-sync.ts`)
Create `scripts/velo-sync.ts` in the client repo to automatically catalog all fields in Velo:

```typescript
// scripts/velo-sync.ts
import fs from 'fs';
import path from 'path';

// Self-contained zero-dependency .env loader
try {
  const envPath = path.resolve(process.cwd(), '.env.local');
  if (fs.existsSync(envPath)) {
    const lines = fs.readFileSync(envPath, 'utf8').split('\n');
    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('#')) continue;
      const idx = trimmed.indexOf('=');
      if (idx !== -1) {
        const k = trimmed.slice(0, idx).trim();
        const v = trimmed.slice(idx + 1).trim().replace(/^['"](.*)['"]$/, '$1');
        process.env[k] = process.env[k] || v;
      }
    }
  }
} catch {
  // ignore
}

const VELO_URL = process.env.NEXT_PUBLIC_VELO_URL || 'https://velo.baseworks.in';
const ORG_KEY = process.env.NEXT_PUBLIC_VELO_ORG_KEY;

if (!ORG_KEY) {
  console.error('Error: NEXT_PUBLIC_VELO_ORG_KEY is required to sync.');
  process.exit(1);
}

const inventory = [
  {
    key: 'home.hero.title',
    label: 'Hero Main Headline',
    page: 'Home',
    section: 'Hero',
    type: 'text',
    defaultValue: 'Scale Your Operations Faster',
    order: 1,
  },
  {
    key: 'home.hero.subtitle',
    label: 'Hero Subtitle',
    page: 'Home',
    section: 'Hero',
    type: 'textarea',
    defaultValue: 'Streamlined operations built for modern businesses.',
    order: 2,
  },
  {
    key: 'home.hero.cta',
    label: 'Hero Primary CTA Button',
    page: 'Home',
    section: 'Hero',
    type: 'button',
    defaultValue: { label: 'Get Started', href: '/contact' },
    order: 3,
  },
  {
    key: 'home.hero.image',
    label: 'Hero Banner Image',
    page: 'Home',
    section: 'Hero',
    type: 'image',
    defaultValue: '/images/hero.webp',
    order: 4,
  },
  {
    key: 'home.faq.items',
    label: 'Frequently Asked Questions',
    page: 'Home',
    section: 'FAQ',
    type: 'list',
    itemSchema: { question: 'text', answer: 'textarea' },
    defaultValue: [
      { question: 'What is your turnaround?', answer: 'We deliver in 48 hours.' },
      { question: 'Do you offer support?', answer: 'Yes, 24/7 client support.' },
    ],
    order: 5,
  },
];

async function sync() {
  console.log(`Syncing ${inventory.length} fields to Velo Site Content Lake...`);
  const res = await fetch(`${VELO_URL}/api/webhooks/site-sync`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-org-key': ORG_KEY,
    },
    body: JSON.stringify({
      pages: [
        { path: '/', name: 'Home' },
        { path: '/services', name: 'Services', group: 'Offerings' },
        { path: '/about', name: 'About Us', group: 'Company' },
        { path: '/contact', name: 'Contact', group: 'Support' }
      ],
      inventory,
      businessProfile: {
        archetype: 'local_business',
        businessType: 'LocalBusiness',
        locations: [
          {
            id: 'loc_1',
            name: 'Main HQ',
            address: '123 Main St',
            city: 'Bangalore',
            phone: '+91 98450 00000',
            openingHours: 'Mon - Sat: 9:00 AM - 8:00 PM',
            isPrimary: true
          }
        ]
      }
    }),
  });

  const data = await res.json();
  if (data.success) {
    console.log(`✅ Success! ${data.registeredItems} fields registered for ${data.organization}.`);
  } else {
    console.error('❌ Sync failed:', data.error);
    process.exit(1);
  }
}

sync();
```

Add this script to `package.json`:
```json
"scripts": {
  "velo:sync": "npx tsx scripts/velo-sync.ts"
}
```

Run it once:
```bash
npm run velo:sync
```

Immediately, the client can log into Velo at `/dashboard/site-editor` and see their inputs ready to edit!

---

## 🤖 The Copy-Paste AI Agent Prompt

Copy and paste this prompt to Claude Code, Antigravity, or Cursor to convert any bespoke website in 60 seconds:

```markdown
Convert this website into a client-editable platform using the Velo Site Content Engine.

Follow the Velo Site Editor standard:
1. Inspect the codebase (e.g. `src/`, `app/`, `components/`) to inventory all hardcoded headlines, subtitles, CTA button labels & links, banner images, and repeating card lists (like FAQs or testimonials).
2. Create `lib/velo-content.ts` with `getVeloContent()` and `generateOrganizationJsonLd()` using `process.env.NEXT_PUBLIC_VELO_ORG_KEY`.
3. Wrap the existing JSX elements with `content['page.section.field'] ?? 'existing code fallback'` so the site never flickers or breaks if Sanity is empty.
4. Create `scripts/velo-sync.ts` containing the complete inventory array with keys, labels, pages, sections, types (`text`, `textarea`, `button`, `image`, `file`, or `list`), and default values. Add `"velo:sync": "npx tsx scripts/velo-sync.ts"` to `package.json`.
5. Run `npm run velo:sync` using the organization key in `.env.local` to register all fields in the Velo Dashboard.
```
