// Shapes of the plugin's REST responses (see includes/class-rest.php) and the
// Stand objects they pass through from the public API.

export type ShowWhen = 'either' | 'rep' | 'standin';

export interface VisibilityItem {
  type: 'post' | 'front' | 'post_type' | 'archives';
  id?: number;
  name?: string;
}

export interface Settings {
  site_id: string;
  chat_enabled: boolean;
  corner_button: boolean;
  visibility: { mode: 'all' | 'except' | 'only'; items: VisibilityItem[] };
  non_production: 'hide' | 'demo' | 'print';
  consent: { mode: 'immediate' | 'consent'; category: string };
  hide_for_admins: boolean;
  loader: boolean;
  identity: { enabled: boolean; roles: string[] };
  read_on_publish: boolean;
}

export interface ConnectionSummary {
  connected: boolean;
  /** Not connected yet: signed in, and the new Stand account is still being set up. */
  onboarding?: boolean;
  reconnect?: boolean;
  reconnectCause?: string;
  site?: { siteId: string; domain: string; name: string };
  user?: { email: string; name: string } | null;
  role?: 'owner' | 'member';
  isOwner?: boolean;
  /** The organization owner's first name. */
  ownerName?: string;
  scopes?: string[];
  connectedAt?: string;
  lastUsedAt?: string;
  /** Stand ends the connection then: unused for a while, or at its longest lifetime. */
  expiresAt?: string;
  connectedBy?: number;
}

export interface InstallCheck {
  status: 'found' | 'consent_loader' | 'missing' | 'wrong_site_id' | 'duplicate' | 'unreachable' | 'off';
  url: string;
  checkedAt: number;
  siteIds: string[];
  scripts: number;
}

export interface PluginNotice {
  id: string;
  status: 'success' | 'info' | 'warning' | 'error';
  message: string;
  action: { label: string; kind: string } | null;
  dismissible: boolean;
}

export interface PluginState {
  settings: Settings;
  connection: ConnectionSummary;
  setup: { account: boolean; brief: boolean; live: boolean };
  environment: {
    type: string;
    isProduction: boolean;
    homeDomain: string;
    siteDomain: string;
    mismatch: boolean;
    hiddenReason: '' | 'non_production' | 'domain_mismatch';
    subdirectory: boolean;
    addressDecision: string;
  };
  install: InstallCheck | null;
  primaryStandinId: string;
  knowledgeBaseId: string;
  notices: PluginNotice[];
  consent: { apiActive: boolean; banner: string };
  optimizers: Array<{ name: string; handled: boolean }>;
  permalinksPlain: boolean;
}

export interface StatusAction {
  label: string;
  kind: string;
  href: string;
}

export interface Status {
  state: 'setup' | 'live' | 'waiting' | 'printing' | 'hidden_environment' | 'nobody' | 'quota' | 'off' | 'reconnect' | 'unknown';
  title: string;
  message: string;
  action: StatusAction | null;
  notes: string[];
  stale: boolean;
}

export type WhoAnswersMode = 'you_first' | 'ai_every' | 'only_you' | 'nobody';

export interface WhoAnswers {
  mode: WhoAnswersMode;
  chatsHere: boolean;
  coverage: boolean;
  answering: string[];
}

export interface Responder {
  type: 'person' | 'ai';
  /** The connected person, or their own AI assistant. */
  mine: boolean;
  name: string;
  brandName: string;
  avatar: string;
  ownerName: string;
  pathPrefix: string;
  standinId: string;
}

export interface Week {
  chats: number;
  minutes: number;
  days: Array<{ day: string; chats: number }>;
}

export interface PlanInfo {
  plan: {
    planCode: string;
    name: string;
    chatQuota: number | null;
    periodType: string | null;
    priceCents?: number;
    promptCharacterLimit: number;
  };
  usage: {
    periodStart: string;
    periodEnd: string;
    chatCount: number;
    chatsBalance: number;
    chatQuota: number | null;
  };
}

export interface ApiErrorInfo {
  code: string;
  message: string;
}

export interface Overview {
  status: Status;
  site: Site | null;
  who: WhoAnswers | null;
  responders: Responder[];
  week: Week | null;
  plan: PlanInfo | null;
  knowledge: { pages: number; changed: Array<{ id: number; title: string; modified: string }> } | null;
  errors: Record<string, ApiErrorInfo>;
}

export interface BehaviorPresentation {
  noGreetings: boolean;
  halfSize: boolean;
  stepAside: boolean;
}

export interface BehaviorRule {
  ruleId: string;
  name: string;
  enabled: boolean;
  pathPrefix: string;
  hideButtonUntilTriggered: boolean;
  presentation: BehaviorPresentation;
  trigger: { type: 'immediate' | 'delay' | 'firstScroll' | 'scrollDepth' | 'none'; delayMs: number; scrollPercent: number };
  action: { type: 'showButton' | 'openChat' | 'openChatAfterGreeting'; initialMessage: string };
  /** Has custom JavaScript set in Stand: then the Site's rules change only in Stand. */
  customJavascriptSet?: boolean;
  where?: { kind: 'default' | 'front' | 'page' | 'subtree' | 'path'; label: string; postId: number };
}

export interface Site {
  siteId: string;
  domain: string;
  name: string;
  enabled: boolean;
  installed: boolean;
  installedAt: string;
  defaultLanguageCode: string | null;
  behaviorConfig: { advancedBehaviorEnabled: boolean; allowStandAdminBehavior: boolean; rules: BehaviorRule[] };
}

export interface PathChange {
  canUpdate: boolean;
  postId: number;
  title: string;
  oldPath: string;
  newPath: string;
}

export interface BehaviorPayload {
  rules: BehaviorRule[];
  revision: string;
  limit: number;
  isOwner: boolean;
  frontPath: string;
  pathChanges: PathChange[];
}

export interface Standin {
  standinProfileId: string;
  name: string;
  displayName: string;
  displayBrandName: string | null;
  avatarUrl: string | null;
  greeting: string | null;
  prompt: string;
  toolsEnabled: string | null;
  siteId: string | null;
  pathPrefix: string;
  enabled: boolean;
  hasSessions: boolean;
  createdAt: string;
  /** The plugin's fingerprint of what WordPress edits; saves send it back as expectedRevision. */
  revision?: string;
}

export interface Skill {
  skillKey: 'followup' | 'customerDiscovery' | 'labeling' | string;
  enabled: boolean;
  available: boolean;
  requiredPlan: string | null;
  config: { guidance?: string; recipientEmail?: string; labels?: unknown[] };
}

export interface StandinsPayload {
  standins: Standin[];
  others: Responder[];
  primaryId: string;
  who: WhoAnswers | null;
  siteId: string;
}

export interface StandinDetail {
  standin: Standin;
  skills: Skill[];
  knowledge: { knowledgeBaseIds: string[]; maxAttached: number } | null;
  siteKnowledgeBaseId: string;
}

export interface KnowledgePage {
  id: number;
  title: string;
  path: string;
  url: string;
  type: string;
  postStatus: string;
  modified: string;
  sourceId: string;
  status: 'read' | 'reading' | 'failed' | 'cancelled' | 'missing' | 'unknown';
  readAt: string;
  changed: boolean;
  taskId: string;
  error: string;
  addressMoved: boolean;
}

export interface KnowledgePayload {
  plan: {
    planCode: string;
    planName: string;
    pageLimit: number | null;
    sitemapAllowed: boolean;
    refreshAllowed: boolean;
    documentsAllowed: boolean;
    ingestionAllowed: boolean;
    graceReadOnly: boolean;
    unavailableReason: string;
    usage: { knowledgeBaseCount?: number; pageCount?: number };
  };
  knowledgeBase: { knowledgeBaseId: string; name: string; attachedAgentCount: number } | null;
  pages: KnowledgePage[];
  others: Array<{ sourceId: string; displayName: string; url: string; status: string; pageCount: number }>;
  sitemap: { url: string; source: { sourceId: string; status: string; pageCount: number; sitemapRefreshEnabled: boolean } | null };
  stale: boolean;
  readOnPublish: boolean;
  errors?: Array<{ id: number; title: string; message: string }>;
}

export interface ContentItem {
  id: number;
  title: string;
  path: string;
  pattern: string | null;
  url: string;
  type: string;
  parent: number;
  modified: string;
  reason: '' | 'front' | 'menu' | 'common' | 'not_recommended' | 'protected';
  selected: boolean;
  hasChildren: boolean;
}

export interface ContentPayload {
  items: ContentItem[];
  total: number;
  pages: number;
  types: Array<{ name: string; label: string }>;
}

export interface PrefillMenu {
  name: string;
  items: Array<{ label: string; url: string }>;
}

export interface WordPressInfo {
  siteName: string;
  tagline: string;
  website: string;
  domain: string;
  menus: PrefillMenu[];
  contact: { label: string; url: string } | null;
  siteIconUrl: string;
  hasSiteIcon: boolean;
  siteIconId: number;
  locale: string;
  language: string;
  blockTheme: boolean;
  roles: Array<{ key: string; name: string }>;
  wooCommerce: boolean;
  user: { email: string; firstName: string; lastName: string; displayName: string };
}
