/**
 * TypeScript types for ReviewIQ Dashboard.
 */

// ==================== API Response Types ====================

export interface OverviewStats {
  total_reviews: number;
  total_spans: number;
  open_issues: number;
  avg_rating: number | null;
  positive_count: number;
  negative_count: number;
  neutral_count: number;
  mixed_count: number;
}

export interface SentimentDataPoint {
  valence: string;
  count: number;           // Span count (mentions)
  review_count: number;    // Distinct reviews
  percentage: number;      // Based on review_count
}

export interface SentimentTrendPoint {
  period: string;
  positive: number;
  negative: number;
  neutral: number;
  mixed: number;
}

export interface SentimentData {
  distribution: SentimentDataPoint[];
  trend: SentimentTrendPoint[];
}

export interface URTDomainPoint {
  domain: string;
  domain_name: string;
  count: number;              // Span count (mentions)
  review_count: number;       // Distinct reviews affected
  percentage: number;         // Based on review_count
  positive_count: number;     // Positive spans
  negative_count: number;     // Negative spans
  neutral_count: number;      // Neutral spans
  positive_reviews: number;   // Reviews with positive sentiment
  negative_reviews: number;   // Reviews with negative sentiment
}

export interface IntensityPoint {
  domain: string;
  intensity: string;
  count: number;
}

export interface URTData {
  domains: URTDomainPoint[];
  intensity_heatmap: IntensityPoint[];
}

// ==================== Domain Scores ====================

export interface DomainScore {
  domain: string;
  name: string;
  score: number;
  status: 'good' | 'warning' | 'critical';
  trend: string | null;
  positive_count: number;
  negative_count: number;
  total_count: number;
}

// ==================== Insights ====================

export interface StrengthItem {
  rank: number;
  subcode: string;
  subcode_name: string;
  domain: string;
  domain_name: string;
  positive_percentage: number;
  span_count: number;
  marketing_angle: string | null;
}

export interface WeaknessItem {
  rank: number;
  issue_id: string | null;
  subcode: string;
  subcode_name: string;
  domain: string;
  domain_name: string;
  negative_percentage: number;
  span_count: number;
  intensity: string | null;
  solution: string | null;
  solution_complexity: string | null;
  projected_rating_impact: number | null;
  owner: string | null;
  // Optional: example quotes from reviews
  example_spans?: OpportunitySpan[];
}

export interface RatingSimulator {
  current_rating: number;
  if_fix_top_1: number | null;
  if_fix_top_3: number | null;
  potential_gain: number;
}

export interface OpportunitySpan {
  span_id: string;
  span_text: string;
  review_text: string | null;
  rating: number | null;
  review_id: string | null;
  review_date: string | null;
}

export interface OpportunityItem {
  subcode: string;
  name: string;  // Human-readable subcode name
  x: number;  // 0-1, frequency position within quadrant
  y: number;  // 0-1, effort position within quadrant
  // Detail data for hover/click
  domain: string;
  domain_name: string;
  negative_pct: number;
  span_count: number;
  solution: string | null;
  complexity: string;
  rating_impact: number | null;
  owner: string | null;
  example: string | null;
  spans: OpportunitySpan[];
}

export interface OpportunityMatrix {
  quick_wins: OpportunityItem[];
  critical: OpportunityItem[];
  nice_to_have: OpportunityItem[];
  strategic: OpportunityItem[];
}

export interface Insights {
  strengths: StrengthItem[];
  weaknesses: WeaknessItem[];
  rating_simulator: RatingSimulator | null;
  opportunity_matrix: OpportunityMatrix | null;
  executive_summary: string;
}

// ==================== Report Synthesis v2.0 (6-Section Business Report) ====================

// Section 1: Executive Summary
export interface ExecutiveSummary {
  health_score: number;           // 1-100 overall health
  health_label: string;           // "Needs Attention" | "Stable" | "Strong"
  one_liner: string;              // Single sentence verdict
  current_rating: number;         // 3.71
  potential_rating: number;       // 4.2
  rating_gap: number;             // 0.49
  estimated_revenue_at_risk: string;  // "€15,000/month"
  key_insight: string;            // The most important finding
  momentum: 'improving' | 'declining' | 'stable';
  momentum_detail: string;        // Explanation
}

// Section 2: Risk Scorecard
export interface RiskIndicator {
  name: string;              // "Staff Behavior"
  score: number;             // 1-10 (10 = excellent, 1 = critical)
  trend: 'improving' | 'declining' | 'stable';
  complaint_count: number;   // Number of related complaints
  color: 'green' | 'yellow' | 'red';
}

export interface RiskScorecard {
  overall_risk: 'low' | 'medium' | 'high' | 'critical';
  indicators: RiskIndicator[];
  highest_risk_area: string;      // "Value Perception"
  immediate_attention: string;    // What needs fixing NOW
}

// Section 3: Critical Issues
export interface CriticalIssue {
  rank: number;              // 1, 2, or 3
  title: string;             // "Hidden Fees Destroying Trust"
  urt_code: string;          // "V1.03"
  complaint_count: number;   // 94
  revenue_impact: string;    // "€12,000/month at risk"
  evidence: string[];        // 2-3 damning quotes
  root_cause: string;        // Why this keeps happening
  solution: string;          // Specific fix
  effort: 'quick_win' | 'moderate' | 'strategic';
  timeline: string;          // "1 week" | "2-4 weeks" | "1-2 months"
}

// Section 4: Strengths to Protect
export interface StrengthToProtect {
  title: string;             // "Exceptional Staff Service"
  mention_count: number;     // 168
  percentage: number;        // 42.0 (% of positive reviews)
  top_quotes: string[];      // 2-3 best quotes
  risk_of_loss: string;      // What could erode this strength
  leverage_action: string;   // How to amplify in marketing
}

// Section 5: Action Matrix
export interface ActionMatrixItem {
  action: string;            // What to do (imperative)
  owner: string;             // Who owns it
  effort: 'low' | 'medium' | 'high';
  impact: 'low' | 'medium' | 'high';
  quadrant: 'quick_win' | 'major_project' | 'fill_in' | 'deprioritize';
  expected_lift: string;     // "+0.3★"
  deadline: string;          // "Week 1" | "Week 2-4" | "Month 2-3"
  success_metric: string;    // Measurable KPI
}

// Section 6: 90-Day Tracking
export interface TrackingKPI {
  metric: string;            // "Deposit Complaints"
  current_value: string;     // "47/month"
  target_30_day: string;     // "< 25/month"
  target_60_day: string;     // "< 15/month"
  target_90_day: string;     // "< 5/month"
  measurement: string;       // How to measure this
}

// Chart Data Types
export interface ChartDataPoint {
  label: string;
  value: number;
  color?: string;
}

export interface TimeSeriesPoint {
  month: string;          // "Jan", "Feb", etc.
  month_date: string;     // "2025-01" for sorting
  value: number;
}

export interface DualSeriesPoint {
  month: string;
  month_date: string;
  positive: number;
  negative: number;
}

export interface ReportCharts {
  rating_gauge: {
    current: number;
    target: number;
    min: number;
    max: number;
  };
  sentiment_pie: ChartDataPoint[];
  issues_pie: ChartDataPoint[];
  rating_distribution: ChartDataPoint[];
  complaints_trend: TimeSeriesPoint[];
  rating_trend: TimeSeriesPoint[];
  momentum_trend: DualSeriesPoint[];
}

// Legacy types for backwards compatibility (v1.x reports)
export interface ReportAction {
  priority: 'critical' | 'high' | 'medium';
  action: string;
  owner: string;
  impact: string;
  impact_stars: number;
  effort: 'quick_win' | 'moderate' | 'strategic';
  evidence: string;
  complaint_count: number;
  success_metric: string;
}

export interface ReportEvidence {
  quote: string;
  context: string;
  sentiment: 'damaging' | 'praising';
  weight: 'critical' | 'notable';
}

export interface ReportStrength {
  title: string;
  mention_count: number;
  quote: string;
  marketing_angle: string;
}

// Legacy Synthesis Interface (v1.x - for backwards compatibility)
export interface LegacySynthesis {
  headline: string;
  verdict: string;
  current_rating: number;
  potential_rating: number;
  rating_gap: number;
  narrative: string;
  sentiment_headline: string;
  category_headline: string;
  timeline_headline: string;
  strengths_headline: string;
  primary_problem: string;
  primary_problem_code: string;
  root_cause: string;
  actions: ReportAction[];
  evidence: ReportEvidence[];
  strengths: ReportStrength[];
  momentum: 'improving' | 'declining' | 'stable';
  momentum_detail: string;
  generated_at: string;
  review_count: number;
  insight_count: number;
}

// New Synthesis Interface (v2.0 - 6-Section Report)
export interface SynthesisV2 {
  // Report metadata
  report_version?: string;        // "2.0"
  report_title: string;           // "Reputation Health Report: Soho Club"
  report_date: string;            // "January 2026"
  business_name: string;
  generated_at: string;
  review_count: number;
  insight_count: number;
  analysis_period: string;        // "Last 12 months"

  // Section 1: Executive Summary
  executive_summary: ExecutiveSummary;

  // Section 2: Risk Scorecard
  risk_scorecard: RiskScorecard;

  // Section 3: Critical Issues (Top 3)
  critical_issues: CriticalIssue[];

  // Section 4: Protect Your Strengths
  strengths: StrengthToProtect[];

  // Section 5: Action Matrix
  action_matrix: ActionMatrixItem[];

  // Section 6: 90-Day Tracking Framework
  tracking_kpis: TrackingKPI[];

  // Charts data for visualization
  charts?: ReportCharts;
}

// Union type that supports both formats
export type Synthesis = LegacySynthesis | SynthesisV2;

// Type guard to check if synthesis is v2 format
export function isSynthesisV2(synthesis: Synthesis): synthesis is SynthesisV2 {
  return 'executive_summary' in synthesis && synthesis.executive_summary !== undefined;
}

// ==================== Issues (Enriched) ====================

export interface IssueItem {
  issue_id: string;
  primary_subcode: string;
  subcode_name: string | null;
  subcode_definition: string | null;
  solution: string | null;
  solution_complexity: string | null;
  domain: string;
  domain_name: string | null;
  category_name: string | null;
  default_owner: string | null;
  negative_example: string | null;
  entity: string | null;
  state: string;
  priority_score: number;
  span_count: number;
  max_intensity: string | null;
  created_at: string | null;
}

export interface PaginatedIssues {
  items: IssueItem[];
  total: number;
  page: number;
  page_size: number;
}

// ==================== Spans ====================

export interface SpanItem {
  span_id: string;
  span_text: string;
  urt_primary: string | null;
  valence: string | null;
  intensity: string | null;
  review_time: string | null;
  source_review_id: string | null;
  entity: string | null;
}

export interface PaginatedSpans {
  items: SpanItem[];
  total: number;
  page: number;
  page_size: number;
}

// ==================== Full Review (Drill-Down) ====================

export interface ReviewSpan {
  span_id: string;
  span_text: string;
  start_offset: number | null;
  end_offset: number | null;
  urt_primary: string | null;
  urt_secondary: string[] | null;
  valence: string | null;
  intensity: string | null;
  entity: string | null;
}

export interface FullReview {
  review_id: string;
  source: string;
  rating: number | null;
  review_text: string | null;
  text_normalized: string | null;  // Text used for span offset calculation
  review_time: string | null;
  author_name: string | null;
  author_url: string | null;
  review_url: string | null;
  business_name: string | null;
  urt_primary: string | null;
  urt_secondary: string[] | null;
  spans: ReviewSpan[];
}

// ==================== Timeline ====================

export interface TimelinePoint {
  date: string;
  review_count: number;
  span_count: number;
  avg_rating: number | null;
  positive_count: number;
  negative_count: number;
}

// ==================== Main Response ====================

export interface ReviewIQAnalyticsResponse {
  overview: OverviewStats;
  sentiment: SentimentData;
  urt: URTData;
  domain_scores: DomainScore[];
  overall_experience_index: number | null;
  insights: Insights;
  issues: PaginatedIssues;
  spans: PaginatedSpans;
  timeline: TimelinePoint[];
  filters_applied: Record<string, unknown>;
  // NEW: AI-generated synthesis (optional, null if not generated yet)
  synthesis: Synthesis | null;
}

// ==================== Filter Types ====================

export type TimeRange = '7d' | '14d' | '30d' | '90d' | '1y' | 'all';
export type Granularity = 'day' | 'week' | 'month' | 'year';
export type Sentiment = 'positive' | 'neutral' | 'negative';
export type URTDomain = 'O' | 'P' | 'J' | 'E' | 'A' | 'V' | 'R';
export type Intensity = 'I1' | 'I2' | 'I3';
export type SentimentView = 'all' | 'positive' | 'negative' | 'mixed';

export interface ReviewIQFilters {
  timeRange: TimeRange;
  sentiment: Sentiment[];
  urtDomain: URTDomain | null;
  intensity: Intensity[];
  brushRange: { start: string; end: string } | null;
}

export interface ReviewIQFilterContextValue {
  filters: ReviewIQFilters;
  setFilters: React.Dispatch<React.SetStateAction<ReviewIQFilters>>;
  toggleSentiment: (s: Sentiment) => void;
  setURTDomain: (domain: URTDomain | null) => void;
  toggleIntensity: (i: Intensity) => void;
  setTimeRange: (range: TimeRange) => void;
  setBrushRange: (range: { start: string; end: string } | null) => void;
  clearFilters: () => void;
  hasActiveFilters: boolean;
}

// ==================== Chart Colors ====================

export const SENTIMENT_COLORS = {
  positive: '#22c55e',
  neutral: '#eab308',
  negative: '#ef4444',
  mixed: '#f97316',
} as const;

export const VALENCE_COLORS: Record<string, string> = {
  'V+': '#22c55e',
  'V0': '#eab308',
  'V-': '#ef4444',
  'V±': '#f97316',
};

export const DOMAIN_COLORS: Record<string, string> = {
  O: '#f97316', // Offering - orange
  P: '#3b82f6', // People - blue
  J: '#8b5cf6', // Journey - purple
  E: '#06b6d4', // Environment - cyan
  A: '#10b981', // Access - green
  V: '#ec4899', // Value - pink
  R: '#f59e0b', // Relationship - amber
};

export const INTENSITY_COLORS: Record<string, string> = {
  I1: '#fef08a', // Light yellow
  I2: '#fbbf24', // Yellow
  I3: '#f97316', // Orange
};

export const STATUS_COLORS: Record<string, string> = {
  good: '#22c55e',     // Green
  warning: '#eab308',  // Yellow
  critical: '#ef4444', // Red
};

// ==================== Display Mappings ====================

export const VALENCE_LABELS: Record<string, string> = {
  'V+': 'Positive',
  'V0': 'Neutral',
  'V-': 'Negative',
  'V±': 'Mixed',
};

export const DOMAIN_LABELS: Record<string, string> = {
  O: 'Offering',
  P: 'People',
  J: 'Journey',
  E: 'Environment',
  A: 'Access',
  V: 'Value',
  R: 'Relationship',
};

export const DOMAIN_FRIENDLY: Record<string, { emoji: string; label: string; description: string }> = {
  P: { emoji: '👥', label: 'Staff & Service', description: 'How staff treats customers' },
  V: { emoji: '💰', label: 'Pricing & Value', description: 'Price, fees, and value for money' },
  J: { emoji: '⏱️', label: 'Speed & Process', description: 'Wait times and procedures' },
  O: { emoji: '🛍️', label: 'Product Quality', description: 'Quality of goods/services' },
  A: { emoji: '📍', label: 'Availability', description: 'Hours, location, accessibility' },
  E: { emoji: '🏢', label: 'Facilities', description: 'Cleanliness, comfort, ambiance' },
  R: { emoji: '🤝', label: 'Trust & Ethics', description: 'Honesty, reliability, fairness' },
};

export const DOMAIN_OWNERS: Record<string, string> = {
  O: 'Operations / Product',
  P: 'HR / Training',
  J: 'Operations / Process',
  E: 'Facilities / IT',
  A: 'Compliance / Design',
  V: 'Finance / Pricing',
  R: 'Leadership / CX',
};

export const INTENSITY_LABELS: Record<string, string> = {
  I1: 'Low',
  I2: 'Medium',
  I3: 'High',
};

export const COMPLEXITY_LABELS: Record<string, string> = {
  quick: 'Quick Fix',
  medium: 'Moderate Effort',
  complex: 'Strategic Initiative',
};

// ==================== Domain Thresholds (from C2-KPI-Mapping-Guide) ====================

export const DOMAIN_THRESHOLDS: Record<string, { green: number; yellow: number }> = {
  O: { green: 80, yellow: 60 },
  P: { green: 85, yellow: 70 },
  J: { green: 75, yellow: 55 },
  E: { green: 80, yellow: 65 },
  A: { green: 85, yellow: 70 },
  V: { green: 70, yellow: 50 },
  R: { green: 80, yellow: 60 },
};

// ==================== OEI Weights (from C2-KPI-Mapping-Guide) ====================

export const DOMAIN_WEIGHTS: Record<string, number> = {
  O: 0.20,
  P: 0.18,
  J: 0.15,
  E: 0.12,
  A: 0.10,
  V: 0.12,
  R: 0.13,
};
