import type { NodedcTheme } from "@nodedc/ui-core";
import type { MapPageLayout, MapPageSettings } from "./MapFixturePreview.js";
import type { MapPresentationProfile } from "./mapPresentationProfile.js";

export const applicationManifestSchemaVersion = "0.1.0" as const;

export type ApplicationDraftStatus = "draft";
export type DesignProfileStatus = "draft" | "published";

export interface ApplicationPageManifest {
  id: string;
  title: string;
  path: string;
  template: {
    id: string;
    version: string;
  };
  navigation: {
    visible: boolean;
    label: string;
    order: number;
  };
  features: Record<string, boolean>;
  /** Runtime configuration belongs to the page instance, never to the visual template. */
  layout?: {
    map?: MapPageLayout;
  };
  /**
   * Design-only deviations from the selected Design Profile. Runtime camera,
   * data bindings and provider-neutral subjects remain in `layout.map`.
   */
  designOverrides?: {
    map?: {
      settings?: Partial<MapPageSettings>;
      presentationProfiles?: MapPresentationProfile[];
    };
  };
}

export interface ApplicationManifestV01 {
  schemaVersion: typeof applicationManifestSchemaVersion;
  id: string;
  status: ApplicationDraftStatus;
  version: string;
  metadata: {
    name: string;
    slug: string;
    description: string;
  };
  designProfile: {
    id: string;
    version: string;
    status: DesignProfileStatus;
    theme: NodedcTheme;
  };
  pages: ApplicationPageManifest[];
  favicon: {
    source: "design-profile";
  };
  timestamps: {
    createdAt: string;
    updatedAt: string;
  };
}

export interface ApplicationSummary {
  id: string;
  name: string;
  slug: string;
  status: ApplicationDraftStatus;
  version: string;
  theme: NodedcTheme;
  pageCount: number;
  updatedAt: string;
}

export interface DesignProfileSummary {
  id: string;
  name: string;
  version: string;
  status: DesignProfileStatus;
  theme: NodedcTheme;
  updatedAt: string;
  versions: DesignProfileVersionSummary[];
  latestPublishedVersion: string | null;
}

export interface DesignProfileVersionSummary {
  version: string;
  status: DesignProfileStatus;
  theme: NodedcTheme;
  publishedAt?: string;
}

export type ApplicationDraftSaveState = "idle" | "loading" | "saving" | "saved" | "error";

export function applicationViewId(id: string) {
  return `application:${id}` as const;
}

export function applicationPageViewId(applicationId: string, pageId: string) {
  return `application:${applicationId}/page:${pageId}` as const;
}

export function applicationIdFromView(view: string | null) {
  if (!view?.startsWith("application:")) return null;
  return view.slice("application:".length).split("/page:")[0] || null;
}

export function applicationPageIdFromView(view: string | null) {
  if (!view?.includes("/page:")) return null;
  return view.split("/page:")[1] || null;
}
