export interface OnboardingInput {
  businessName: string;
  websiteUrl: string;
  /** Top-level taxonomy category, e.g. Healthcare, Home Services */
  industryCategory: string;
  /** Resolved industry record name, e.g. Medical Practice, HVAC Company */
  industry: string;
  /** Taxonomy label shown to user, e.g. Physicians, HVAC */
  businessSubtype?: string;
  location: string;
  businessType: string;
  monthlyRevenueRange: string;
  revenueGoal: string;
  biggestChallenge: string;
  productsServices: string;
  mainCompetitors?: string;
  targetCustomer: string;
}

/** How the signed-in user fits inside their company */
export interface UserWorkplaceRole {
  /** User's title, e.g. Owner / CEO, Founder, General Manager */
  title: string;
  /** When on, BrandLxft acts as an AI boss/leader to set priorities and drive execution */
  aiLeaderEnabled: boolean;
}

export interface BusinessProfile {
  companySummary: string;
  brandPositioning: string;
  targetAudience: string;
  productsServices: string;
  strengths: string[];
  weaknesses: string[];
  marketOpportunities: string[];
  suggestedCompetitors: string[];
  brandImprovements: string[];
}

export interface Competitor {
  id: string;
  name: string;
  website?: string;
  strengths: string[];
  weaknesses: string[];
  positioning?: string;
  pricingNotes?: string;
  customerComplaints: string[];
  beatOpportunity: string;
}

export type OpportunityType =
  | "buyer"
  | "competitor_weakness"
  | "market_gap"
  | "content"
  | "partnership"
  | "reputation"
  | "geographic"
  | "pricing"
  | "product"
  | "government_contract";

export type OpportunityStatus =
  | "new"
  | "saved"
  | "in_progress"
  | "completed"
  | "ignored";

export interface Opportunity {
  id: string;
  title: string;
  type: OpportunityType;
  description: string;
  source: string;
  estimatedValue: number;
  confidenceScore: number;
  urgencyScore: number;
  recommendedAction: string;
  aiOutreach?: string;
  status: OpportunityStatus;
  /** SAM.gov notice ID when sourced from federal contracts API */
  samNoticeId?: string;
  /** Direct link to sam.gov listing */
  externalUrl?: string;
  responseDeadline?: string;
}

export interface BrandScore {
  overall: number;
  visibility: number;
  trust: number;
  demand: number;
  conversion: number;
  advocacy: number;
  growthScore: number;
  marketOpportunityScore: number;
  competitiveRiskScore: number;
  suggestions: {
    visibility: string;
    trust: string;
    demand: string;
    conversion: string;
    advocacy: string;
  };
}

export interface Recommendation {
  id: string;
  title: string;
  whyItMatters: string;
  whatToDoNext: string;
  revenuePotential: number;
  priority: "low" | "medium" | "high";
  socialPost?: string;
  emailDraft?: string;
  dmMessage?: string;
  adConcept?: string;
  offerIdea?: string;
  landingHeadline?: string;
}

export interface AIMessage {
  id: string;
  role: "system" | "assistant" | "user";
  content: string;
  createdAt: string;
}

export interface DashboardMetrics {
  opportunitiesFound: number;
  recommendedActions: number;
  revenuePotential: number;
  topPriorityToday: string;
}

export interface RoleGroups {
  leadership: string[];
  revenue: string[];
  growth: string[];
  operations: string[];
  production: string[];
  compliance: string[];
  technology: string[];
}

export interface RoleIntelligence {
  industryId: string;
  industry: string;
  industryCategory: string;
  businessSubtype?: string;
  roleGroups: RoleGroups;
  firstHire: string;
  nextHire: string;
  revenueDrivers: string[];
  growthBottlenecks: string[];
  /** Roles the business already has (demo / user context) */
  currentTeam: string[];
  /** High-impact roles not yet filled */
  missingRoles: string[];
  /** Single role BrandLxft recommends hiring or assigning now */
  priorityHire: string;
  /** Plain-language explanation of how roles connect to growth */
  howBrandLxftUsesRoles: string[];
  /** Links top opportunity to a specific role gap */
  opportunityRoleLink?: string;
}

export type RoleTaskStatus = "completed" | "failed" | "skipped";

/** A single automated task a role can execute */
export interface RoleTaskDefinition {
  id: string;
  title: string;
  description: string;
  /** Future integration hook — e.g. google_ads, twilio_sms, hubspot */
  integrationTarget: string;
  estimatedMinutes: number;
}

/** Task shown in UI with business-specific preview before running */
export interface PersonalizedRoleTask extends RoleTaskDefinition {
  personalizedPreview: string;
  contextTags: string[];
}

/** One step in the automation pipeline shown before Run */
export interface AutomationFlowStep {
  id: string;
  label: string;
  detail: string;
}

/** How a task will be automated end-to-end */
export interface TaskAutomationFlow {
  trigger: string;
  steps: AutomationFlowStep[];
  integrationName: string;
  integrationAction: string;
  /** Demo simulates; live pushes when OAuth connected in Settings */
  mode: "demo" | "live";
  outputLabel: string;
  outputDetail: string;
  requiresApproval: boolean;
  approvalNote: string;
}

/** Receipt proving a task was executed */
export interface RoleTaskReceipt {
  taskId: string;
  taskTitle: string;
  status: RoleTaskStatus;
  summary: string;
  /** Deliverable output — copy, draft, list, config */
  artifact: string;
  integrationTarget: string;
  completedAt: string;
  metrics?: Record<string, string | number>;
}

/** Full run report when a role automates its task queue */
export interface RoleAutomationRun {
  id: string;
  roleName: string;
  roleGroup?: keyof RoleGroups;
  startedAt: string;
  completedAt: string;
  status: "completed" | "partial";
  executiveSummary: string;
  receipts: RoleTaskReceipt[];
  tasksCompleted: number;
  tasksTotal: number;
  estimatedRevenueImpact?: number;
  nextSteps: string[];
}

export type SocialPlatform =
  | "instagram"
  | "facebook"
  | "linkedin"
  | "tiktok"
  | "youtube"
  | "google"
  | "x";

export interface SocialProfile {
  platform: SocialPlatform;
  handle: string;
  url: string;
  followers?: string;
}

export interface ConnectedSoftware {
  name: string;
  category: string;
  url: string;
  /** What BrandLxft role agents push into this tool */
  usedByRoles: string[];
}

/** Website + social + software stack for demos and automation context */
export interface DigitalPresence {
  websiteUrl: string;
  websiteTitle: string;
  websiteDescription: string;
  socialProfiles: SocialProfile[];
  connectedSoftware: ConnectedSoftware[];
}

export type WebsiteAestheticDimension =
  | "typography"
  | "colorPalette"
  | "layout"
  | "imagery"
  | "trustSignals"
  | "mobileExperience"
  | "conversionPath";

export interface WebsiteDimensionScore {
  dimension: WebsiteAestheticDimension;
  label: string;
  yourScore: number;
  topPerformerAvg: number;
  gap: number;
  yourNote: string;
  topPerformerNote: string;
}

export interface WebsiteAestheticRecommendation {
  id: string;
  priority: "high" | "medium" | "low";
  category: WebsiteAestheticDimension | "identity";
  title: string;
  action: string;
  /** What top sellers in the industry do */
  industryPattern: string;
  /** How to adopt the pattern without copying competitors */
  preserveIndependence: string;
  estimatedImpact: string;
}

export interface IndustryWebsiteBenchmark {
  industryLabel: string;
  topPerformerTraits: string[];
  /** Anonymized reference businesses used for pattern matching */
  referenceProfiles: string[];
}

/** AI website aesthetic audit vs top performers in the category */
export interface WebsiteAestheticAnalysis {
  analyzedAt: string;
  websiteUrl: string;
  overallScore: number;
  industryBenchmarkScore: number;
  independenceScore: number;
  executiveSummary: string;
  identityAnchors: string[];
  dimensions: WebsiteDimensionScore[];
  benchmark: IndustryWebsiteBenchmark;
  recommendations: WebsiteAestheticRecommendation[];
  /** Latest upload to website host (CMS) */
  lastHostUpload?: WebsiteAestheticUploadReceipt;
}

export type WebsiteHostUploadStatus = "draft_saved" | "pending_approval" | "published";

export interface WebsiteHostConnection {
  name: string;
  category: string;
  adminUrl: string;
  websiteUrl: string;
  mode: "demo" | "live";
}

export interface WebsiteAestheticUploadItem {
  recommendationId: string;
  title: string;
  targetSection: string;
  cmsAction: string;
  payload: string;
}

/** Receipt when aesthetic updates are pushed to WordPress, Webflow, Wix, etc. */
export interface WebsiteAestheticUploadReceipt {
  id: string;
  hostName: string;
  hostAdminUrl: string;
  websiteUrl: string;
  uploadedAt: string;
  mode: "demo" | "live";
  status: WebsiteHostUploadStatus;
  summary: string;
  items: WebsiteAestheticUploadItem[];
  /** Draft preview on the live site (when published or staged) */
  previewUrl?: string;
  approvalNote: string;
}

export interface Business {
  id: string;
  ownerId?: string;
  createdAt: string;
  updatedAt: string;
  input: OnboardingInput;
  profile: BusinessProfile;
  opportunities: Opportunity[];
  competitors: Competitor[];
  recommendations: Recommendation[];
  brandScore: BrandScore;
  metrics: DashboardMetrics;
  aiSummary?: string;
  roleIntelligence?: RoleIntelligence;
  /** Completed role automation runs with summaries and receipts */
  roleAutomationRuns?: RoleAutomationRun[];
  /** User's role in the company + optional AI leader mode */
  userRole?: UserWorkplaceRole;
  /** Demo: sample website, social profiles, and connected software stack */
  digitalPresence?: DigitalPresence;
  /** Website aesthetic audit vs top industry performers */
  websiteAestheticAnalysis?: WebsiteAestheticAnalysis;
  /** History of CMS/host uploads from aesthetic analysis */
  websiteHostUploads?: WebsiteAestheticUploadReceipt[];
  /** Connected third-party integrations (CMS, CRM, etc.) */
  integrations?: BusinessIntegrations;
  /** Social visibility, competitor pick-share, and trust analysis */
  socialMediaAnalysis?: SocialMediaAnalysis;
}

export type IntegrationConnectionStatus = "disconnected" | "connected" | "error";

export interface WordPressIntegration {
  siteUrl: string;
  username: string;
  /** WordPress Application Password (Users → Profile → Application Passwords) */
  applicationPassword: string;
  status: IntegrationConnectionStatus;
  connectedAt?: string;
  lastTestedAt?: string;
  lastError?: string;
  siteName?: string;
  adminUrl?: string;
}

/** SAM.gov public API + optional entity UEI for federal bid sync */
export interface SamGovIntegration {
  /** Public API key from sam.gov → Account Details → Public API Key */
  apiKey: string;
  /** Unique Entity ID after SAM entity registration (optional) */
  uei?: string;
  status: IntegrationConnectionStatus;
  /** When true, BrandLxft pulls live bids on connect and on daily refresh */
  autoFetchLiveBids: boolean;
  connectedAt?: string;
  lastFetchedAt?: string;
  lastFetchCount?: number;
  lastError?: string;
}

export interface BusinessIntegrations {
  wordpress?: WordPressIntegration;
  samGov?: SamGovIntegration;
}

export type SocialMediaDimension =
  | "reach"
  | "consistency"
  | "engagement"
  | "socialProof"
  | "competitiveShare"
  | "trustSignal";

export interface SocialDimensionScore {
  dimension: SocialMediaDimension;
  label: string;
  yourScore: number;
  industryTopAvg: number;
  gap: number;
  insight: string;
}

export interface CompetitorPickShare {
  name: string;
  pickSharePercent: number;
  /** Why buyers choose them in a simulated local search / social discovery */
  reason: string;
  isYou?: boolean;
}

export interface TrustChannelAnalysis {
  websiteTrustScore: number;
  socialTrustScore: number;
  /** Which channel creates stronger trust today */
  strongerChannel: "website" | "social" | "balanced";
  websiteTrustNotes: string[];
  socialTrustNotes: string[];
  verdict: string;
}

export interface SocialPlatformInsight {
  platform: SocialPlatform;
  handle: string;
  followers?: string;
  visibilityScore: number;
  trustContribution: number;
  note: string;
}

export interface SocialMediaRecommendation {
  id: string;
  priority: "high" | "medium" | "low";
  title: string;
  action: string;
  expectedImpact: string;
}

/** Social visibility, competitor pick-share, and trust channel analysis */
export interface SocialMediaAnalysis {
  analyzedAt: string;
  visibilityScore: number;
  industryVisibilityBenchmark: number;
  /** Simulated % buyers pick you vs named competitors when comparing online */
  pickShare: CompetitorPickShare[];
  yourPickSharePercent: number;
  trust: TrustChannelAnalysis;
  dimensions: SocialDimensionScore[];
  platforms: SocialPlatformInsight[];
  recommendations: SocialMediaRecommendation[];
  executiveSummary: string;
}
