// Vanday DAM — sample data
// NOTE: the original prototype shipped with hardcoded "ASSETS" and richly
// populated folders for design demos. In the real beta build we strip those
// out: the library and sidebar should reflect only what the server returns
// for the signed-in user. Keep the two structural folders ("all", "raw") so
// the upload destination + "all assets" view continue to work.
const FOLDERS = [
  { id: "all", name: "All assets", count: 0, icon: "grid" },
  { id: "raw", name: "Inbox", count: 0, icon: "folder", parent: null },
];

// ----- Folder hierarchy helpers ---------------------------
// Top-level folders (excluding the synthetic "all").
function topLevelFolders() {
  return FOLDERS.filter((f) => f.id !== "all" && (f.parent === null || f.parent === undefined));
}
function childFolders(parentId) {
  return FOLDERS.filter((f) => f.parent === parentId);
}
function descendantFolderIds(rootId) {
  const out = [rootId];
  const walk = (p) => {
    childFolders(p).forEach((c) => { out.push(c.id); walk(c.id); });
  };
  walk(rootId);
  return out;
}
function folderPath(id) {
  const path = [];
  let cur = FOLDERS.find((f) => f.id === id);
  while (cur) {
    path.unshift(cur);
    cur = cur.parent ? FOLDERS.find((f) => f.id === cur.parent) : null;
  }
  return path;
}
Object.assign(window, { topLevelFolders, childFolders, descendantFolderIds, folderPath });

// Prototype Smart Collections removed for production beta.
const COLLECTIONS = [];

// PROTOTYPE ASSETS REMOVED for production beta — the library renders only
// what the server returns for the signed-in user. `ASSETS` stays declared
// as a mutable array (let, not const) so api.jsx can unshift server assets
// into it as they load.
let ASSETS = [];

// Mock workspace members removed for free beta — team workspaces aren't
// available yet. Each browser session gets a single "you" entry, populated
// from Clerk by app.jsx once the user signs in. Keeping USERS as a mutable
// array (let) so app.jsx can replace it after sign-in.
let USERS = [];

const FIELDS = [
  { name: "Status",           type: "Select",     category: "Essentials",     visible: true },
  { name: "Date uploaded",    type: "Date",       category: "Essentials",     visible: true },
  { name: "Uploader",         type: "Single user",category: "Essentials",     visible: true },
  { name: "Comment count",    type: "Number",     category: "Essentials",     visible: true },
  { name: "Rating",           type: "Rating",     category: "Essentials",     visible: true },
  { name: "Keywords (AI)",    type: "Multi-tag",  category: "Auto-generated", visible: true },
  { name: "Detected objects", type: "Multi-tag",  category: "Auto-generated", visible: true },
  { name: "Dominant color",   type: "Color",      category: "Auto-generated", visible: true },
  { name: "Caption (AI)",     type: "Text",       category: "Auto-generated", visible: true },
  { name: "File size",        type: "Number",     category: "File",           visible: true },
  { name: "Dimensions",       type: "Text",       category: "File",           visible: true },
  { name: "Color space",      type: "Text",       category: "File",           visible: false },
  { name: "Camera model",     type: "Text",       category: "EXIF",           visible: false },
  { name: "ISO",              type: "Number",     category: "EXIF",           visible: false },
  { name: "Shutter speed",    type: "Text",       category: "EXIF",           visible: false },
  { name: "Vanday",           type: "Text",       category: "EXIF",           visible: false },
];

// Social sites Vanday can publish to. Used by the crop-generation code even
// in beta (publishing UI is hidden but auto-crops are generated for the
// ratios listed here so they're ready when publishing unlocks).
const SITES = [
  { id: "instagram", name: "Instagram",  short: "IG", color: "oklch(0.62 0.18 18)",  caption: { max: 2200, allowed: true },
    ratios: [{ name: "Square",   r: "1:1",  w: 1080, h: 1080 },
             { name: "Portrait", r: "4:5",  w: 1080, h: 1350 },
             { name: "Story",    r: "9:16", w: 1080, h: 1920 }] },
  { id: "x",         name: "X",          short: "X",  color: "oklch(0.2 0.005 80)",   caption: { max: 280,  allowed: true },
    ratios: [{ name: "Landscape", r: "16:9", w: 1600, h: 900 }] },
  { id: "linkedin",  name: "LinkedIn",   short: "in", color: "oklch(0.42 0.13 240)",  caption: { max: 3000, allowed: true },
    ratios: [{ name: "Landscape", r: "1.91:1", w: 1200, h: 627 }] },
  { id: "facebook",  name: "Facebook",   short: "FB", color: "oklch(0.48 0.13 250)",  caption: { max: 5000, allowed: true },
    ratios: [{ name: "Landscape", r: "1.91:1", w: 1200, h: 630 }] },
  // TikTok removed for now — requires video for most posts, image-only
  // posting via Upload-Post is supported but the broader TikTok creator
  // experience is video-first. We'll add it back if there's demand.
  { id: "pinterest", name: "Pinterest",  short: "P",  color: "oklch(0.55 0.18 18)",   caption: { max: 500,  allowed: true },
    ratios: [{ name: "Pin", r: "2:3", w: 1000, h: 1500 }] },
];

Object.assign(window, { FOLDERS, COLLECTIONS, ASSETS, USERS, FIELDS, SITES });

// ---------------------------------------------------------
// FT-15 — Expiration / rights expiry
// ---------------------------------------------------------
// A handful of assets are tagged with an expiration date so the
// expiry surfaces (library badges, preview field, smart collection)
// have real data to render. `takedownOnExpiry` controls whether the
// system auto-removes published posts on the expiry date.
const EXPIRY = {
  a01: { date: "May 24, 2026", daysLeft: 5,   takedown: true,  license: "Rights-managed", status: "soon" },
  a08: { date: "May 21, 2026", daysLeft: 2,   takedown: true,  license: "Rights-managed", status: "soon" },
  a14: { date: "Dec 31, 2026", daysLeft: 226, takedown: false, license: "Licensed stock", status: "ok"   },
  a04: { date: "May 14, 2026", daysLeft: -5,  takedown: false, license: "Model release", status: "expired" },
  a21: { date: "Jun 30, 2026", daysLeft: 42,  takedown: true,  license: "Commercial — paid", status: "ok" },
};
ASSETS.forEach((a) => { if (EXPIRY[a.id]) a.expiry = EXPIRY[a.id]; });

// ---------------------------------------------------------
// FT-17 — Per-folder permissions
// ---------------------------------------------------------
// Each folder has a `members` list of { userId, role } plus a
// link-sharing policy. The library uses this to render which
// folders are "restricted" with a lock badge.
const FOLDER_ROLES = ["Owner", "Editor", "Contributor", "Commenter", "Viewer"];
const FOLDER_PERMS = {
  brand:     { members: [["u1","Owner"],["u2","Admin"],["u3","Editor"],["u4","Editor"]], link: "workspace" },
  products:  { members: [["u1","Owner"],["u2","Editor"],["u3","Editor"]],                link: "restricted" },
  marketing: { members: [["u1","Owner"],["u2","Editor"],["u3","Editor"],["u4","Editor"],["u5","Commenter"]], link: "workspace" },
  team:      { members: [["u1","Owner"],["u2","Admin"]],                                  link: "restricted" },
  raw:       { members: [["u1","Owner"],["u2","Editor"],["u3","Editor"],["u4","Editor"]], link: "workspace" },
};

// ---------------------------------------------------------
// GP-02 — External share portals
// ---------------------------------------------------------
const SHARE_PORTALS = [
  { id: "p1", name: "Spring '26 — Client review",  folder: "marketing", views: 14, downloads: 3,  expires: "Jun 12, 2026", password: true,  watermark: false, approval: true,  download: true,  brandColor: "oklch(0.58 0.16 32)" },
  { id: "p2", name: "Press kit — embargoed Q3",    folder: "brand",     views: 41, downloads: 7,  expires: "Sep 01, 2026", password: true,  watermark: true,  approval: false, download: true,  brandColor: "oklch(0.42 0.13 240)" },
  { id: "p3", name: "Headphone launch — Best Buy", folder: "products",  views: 6,  downloads: 0,  expires: "Jun 02, 2026", password: false, watermark: false, approval: false, download: false, brandColor: "oklch(0.55 0.14 155)" },
];

// ---------------------------------------------------------
// GP-11 — Activity audit log
// ---------------------------------------------------------
// Hand-seeded so QA can sanity-check the rendering of every action
// type. In production this comes from the audit backend.
const AUDIT_LOG = [
  { id: "l01", at: "May 19, 2026 · 10:42:18", actor: "u1", action: "login",         target: null,           ip: "98.207.10.4",  device: "macOS · Chrome 124" },
  { id: "l02", at: "May 19, 2026 · 10:44:02", actor: "u1", action: "upload",        target: "11 assets · Spring '26 shoot", ip: "98.207.10.4",  device: "macOS · Chrome 124" },
  { id: "l03", at: "May 19, 2026 · 10:48:55", actor: "u3", action: "publish",       target: "ceramics-flatlay.jpg → Instagram", ip: "172.18.4.91",  device: "iOS · Vanday 2.1" },
  { id: "l04", at: "May 19, 2026 · 11:02:11", actor: "u2", action: "permission",    target: "Folder 'Product shots' → restricted", ip: "73.40.215.8",  device: "macOS · Safari 17" },
  { id: "l05", at: "May 19, 2026 · 11:17:30", actor: "u4", action: "delete",        target: "branding-mockup-old.jpg", ip: "184.22.6.51",  device: "Windows · Edge 124" },
  { id: "l06", at: "May 19, 2026 · 12:01:09", actor: "u1", action: "share.create",  target: "Portal 'Spring '26 — Client review'", ip: "98.207.10.4",  device: "macOS · Chrome 124" },
  { id: "l07", at: "May 19, 2026 · 13:14:42", actor: "u2", action: "plan.change",   target: "Team → Business (annual)", ip: "73.40.215.8",  device: "macOS · Safari 17" },
  { id: "l08", at: "May 19, 2026 · 14:09:55", actor: "u5", action: "share.view",    target: "Portal 'Press kit — embargoed Q3'", ip: "201.45.118.3", device: "Windows · Chrome 124" },
  { id: "l09", at: "May 19, 2026 · 14:33:21", actor: "u3", action: "restore",       target: "campaign-billboard.jpg (from Trash)", ip: "172.18.4.91",  device: "iOS · Vanday 2.1" },
  { id: "l10", at: "May 18, 2026 · 17:28:00", actor: "u1", action: "integration",   target: "Connected Shopify (vanday-shop.myshopify.com)", ip: "98.207.10.4",  device: "macOS · Chrome 124" },
  { id: "l11", at: "May 18, 2026 · 16:51:33", actor: "u4", action: "expire.set",    target: "Set expiry on 5 assets · May 24, 2026", ip: "184.22.6.51",  device: "Windows · Edge 124" },
  { id: "l12", at: "May 18, 2026 · 15:02:14", actor: "u2", action: "permission",    target: "Invited jordan@partner.co · Viewer", ip: "73.40.215.8",  device: "macOS · Safari 17" },
  { id: "l13", at: "May 18, 2026 · 12:48:09", actor: "u1", action: "publish.fail",  target: "harbor-morning-fog.jpg → TikTok (token expired)", ip: "98.207.10.4",  device: "macOS · Chrome 124" },
  { id: "l14", at: "May 18, 2026 · 11:22:46", actor: "u3", action: "login",         target: null, ip: "172.18.4.91",  device: "iOS · Vanday 2.1" },
  { id: "l15", at: "May 18, 2026 · 09:14:30", actor: "u6", action: "invite.accept", target: "Joined workspace as Viewer", ip: "—",            device: "—" },
];

Object.assign(window, { EXPIRY, FOLDER_ROLES, FOLDER_PERMS, SHARE_PORTALS, AUDIT_LOG });

// ---------------------------------------------------------
// Wave 3 — Integrations & developer surface
// ---------------------------------------------------------
// Original lettermark glyphs (not real logos). Colors are recognisable
// hues but the marks are abstracted so nothing infringes.
const INTEGRATIONS = [
  // Publishing
  { id: "wordpress", name: "WordPress",  category: "Publishing", short: "Wp", color: "oklch(0.42 0.04 240)",
    status: "connected", account: "vanday.com",            connectedAt: "Apr 2, 2026",
    blurb: "Insert assets straight from the Vanday DAM into any WordPress post or page.",
    capabilities: ["Insert via Vanday-hosted URL", "Replace original to update live posts", "Block editor button"] },
  { id: "shopify",   name: "Shopify",    category: "Publishing", short: "Sh", color: "oklch(0.55 0.14 155)",
    status: "connected", account: "vanday-shop.myshopify.com", connectedAt: "May 18, 2026",
    blurb: "Push product photography to Shopify products as primary or additional images.",
    capabilities: ["Pick product + position", "Bulk send for a folder", "Updates appear in publishing dashboard"] },

  // Design tools
  { id: "figma",     name: "Figma",      category: "Design",    short: "Fg", color: "oklch(0.58 0.18 32)",
    status: "connected", account: "Vanday Studio team",  connectedAt: "Mar 14, 2026",
    blurb: "Browse and place Vanday assets directly on a Figma frame from the plugin.",
    capabilities: ["Asset browser inside Figma", "Respects folder permissions", "Live re-link on replace"] },
  { id: "canva",     name: "Canva",      category: "Design",    short: "Cv", color: "oklch(0.62 0.16 235)",
    status: "available", account: null,                    connectedAt: null,
    blurb: "Place Vanday assets into Canva designs from the Apps panel." },
  { id: "adobe",     name: "Adobe CC",   category: "Design",    short: "Ai", color: "oklch(0.5 0.18 24)",
    status: "available", account: null,                    connectedAt: null,
    blurb: "Open assets in Photoshop or Illustrator with live re-sync on save." },

  // Storage
  { id: "drive",     name: "Google Drive", category: "Storage", short: "Gd", color: "oklch(0.55 0.14 70)",
    status: "connected", account: "maya@vanday.com",  connectedAt: "Jan 22, 2026",
    blurb: "Two-way sync with a Drive folder. Run-once imports also supported.",
    capabilities: ["OAuth connect", "Preserves source folder structure", "Auto-tag on import"] },
  { id: "dropbox",   name: "Dropbox",    category: "Storage",   short: "Db", color: "oklch(0.45 0.14 240)",
    status: "available" },
  { id: "onedrive",  name: "OneDrive",   category: "Storage",   short: "Od", color: "oklch(0.5 0.13 240)",
    status: "available" },
  { id: "box",       name: "Box",        category: "Storage",   short: "Bx", color: "oklch(0.4 0.04 240)",
    status: "available" },

  // Productivity
  { id: "slack",     name: "Slack",      category: "Productivity", short: "Sl", color: "oklch(0.55 0.18 290)",
    status: "connected", account: "vandaystudio.slack.com", connectedAt: "Feb 4, 2026",
    blurb: "Notifications, share links, and asset previews unfurled inside Slack.",
    capabilities: ["Direct-message + channel routes", "Unfurl share links", "Approve from Slack"] },
  { id: "notion",    name: "Notion",     category: "Productivity", short: "No", color: "oklch(0.22 0.005 80)",
    status: "available" },
  { id: "linear",    name: "Linear",     category: "Productivity", short: "Ln", color: "oklch(0.4 0.13 290)",
    status: "available" },
];

const INTEGRATION_CATEGORIES = ["Publishing", "Design", "Storage", "Productivity"];

// API keys (GP-15)
const API_KEYS = [
  { id: "k1", name: "Production server",  prefix: "ap_live_8f2a", created: "Mar 04, 2026", lastUsed: "Just now",      scopes: ["read", "write", "publish"], revoked: false },
  { id: "k2", name: "WordPress plugin",   prefix: "ap_live_3c91", created: "Apr 10, 2026", lastUsed: "14 minutes ago", scopes: ["read", "publish"],          revoked: false },
  { id: "k3", name: "Internal dashboard", prefix: "ap_live_b04d", created: "Feb 18, 2026", lastUsed: "3 days ago",     scopes: ["read"],                     revoked: false },
  { id: "k4", name: "Old CI key",         prefix: "ap_live_7a12", created: "Jan 09, 2026", lastUsed: "Apr 22, 2026",   scopes: ["read", "write"],            revoked: true  },
];

const WEBHOOKS = [
  { id: "w1", url: "https://hooks.vanday.com/vanday/asset",     events: ["asset.created", "asset.replaced"], status: "healthy", last: "2 min ago" },
  { id: "w2", url: "https://flow.zapier.com/h/9k3jX7tQ",          events: ["publish.success", "publish.failed"], status: "healthy", last: "12 min ago" },
  { id: "w3", url: "https://internal.vanday.com/expire-hook", events: ["expiration.warning"],              status: "failing", last: "1 day ago" },
];

const WEBHOOK_EVENTS = [
  "asset.created", "asset.replaced", "asset.deleted",
  "publish.success", "publish.failed",
  "share.viewed", "share.downloaded",
  "expiration.warning", "expiration.reached",
  "permission.changed", "user.invited",
];

Object.assign(window, { INTEGRATIONS, INTEGRATION_CATEGORIES, API_KEYS, WEBHOOKS, WEBHOOK_EVENTS });

// ---------------------------------------------------------
// Auto-generated crop variants
// ---------------------------------------------------------
// For every uploaded original, Vanday generates a set of common
// social-media crops. Each variant is a first-class asset that:
//   • is searchable and lives in the library
//   • carries a `parentId` so its origin is always linkable
//   • inherits tags / folder / uploader from the parent
//
// We dedupe by ratio (Instagram square + X square share `1:1`)
// and tag each variant with every site that uses it.

const UNIQUE_RATIOS = [];
SITES.forEach((s) => {
  s.ratios.forEach((r) => {
    const existing = UNIQUE_RATIOS.find((u) => u.r === r.r);
    if (existing) {
      existing.sites.push(s.id);
    } else {
      UNIQUE_RATIOS.push({ ...r, sites: [s.id] });
    }
  });
});

// Crop variant slug — the suffix appended to a parent asset's id to make
// virtual ids for each ratio. Format is "WxH" so "1.91:1" → "1.91x1" and
// "16:9" → "16x9". (The original prototype produced digit-only slugs like
// "169" but that loses the separator and confuses anything that has to
// parse ratios back out — including the publish endpoint, which needs to
// generate the actual crop on demand.)
function shortRatioSlug(r) {
  return String(r).replace(":", "x");
}

const VARIANTS = [];
ASSETS.forEach((parent) => {
  UNIQUE_RATIOS.forEach((r) => {
    const slug = shortRatioSlug(r.r);
    const baseName = parent.name.replace(/\.[^.]+$/, "");
    const ext = parent.name.match(/\.[^.]+$/)?.[0] || ".jpg";
    const v = {
      id: `${parent.id}--${slug}`,
      parentId: parent.id,
      kind: "crop",
      name: `${baseName}—${slug}${ext}`,
      url: parent.url,
      folder: parent.folder,
      uploader: parent.uploader,
      date: parent.date,
      size: `${(parseFloat(parent.size) * (0.18 + (r.w * r.h) / (parent.w * parent.h) * 0.5)).toFixed(1)} MB`,
      w: r.w,
      h: r.h,
      ratio: r.r,
      ratioName: r.name,
      sites: [...r.sites],
      tags: parent.tags,
      aiTags: true,
      rating: parent.rating,
    };
    VARIANTS.push(v);
  });
  parent.variantIds = VARIANTS.filter((v) => v.parentId === parent.id).map((v) => v.id);
});

// Mark originals
ASSETS.forEach((a) => { a.kind = a.kind || "original"; });

// Combined library
let ALL_ASSETS = [...ASSETS, ...VARIANTS];

// Lookup helpers
function getAsset(id) { return ALL_ASSETS.find((a) => a.id === id); }
function getParent(asset) {
  if (!asset) return null;
  return asset.kind === "crop" ? ASSETS.find((p) => p.id === asset.parentId) : asset;
}
function getSiblings(asset) {
  const parent = getParent(asset);
  if (!parent) return [];
  return VARIANTS.filter((v) => v.parentId === parent.id);
}

Object.assign(window, {
  UNIQUE_RATIOS, VARIANTS, ALL_ASSETS, ASSETS, FOLDERS, COLLECTIONS,
  getAsset, getParent, getSiblings, shortRatioSlug,
});
