'use client';
import { createContext, useContext, useState, ReactNode } from 'react';

export interface PerformanceComment {
  id: string;
  employeeId: string;
  itemType: 'workplan' | 'kpi' | 'ipi' | 'quarterly' | 'pip';
  itemId: string;
  itemTitle: string;
  commentBy: string;
  commentByRole: string;
  comment: string;
  createdAt: string;
  read: boolean;
}

export interface SharedDeptTarget {
  id: string;
  dept: string;
  title: string;
  description: string;
  quarter: string;
  expectedOutcomes: string;
  deadline: string;
  priority: 'High' | 'Medium' | 'Low';
  measurableObjectives: string;
  progress: number;
  status: 'Pending' | 'Ongoing' | 'Completed' | 'Delayed';
  createdAt: string;
}

export interface StoreEmployee {
  id: string;
  name: string;
  dept: string;
  role: string;
  employeeType: string;
  hod: string;
}

export interface StoreWorkPlan {
  id: string;
  employeeId: string;
  employee: string;
  department: string;
  role: string;
  employeeType: string;
  hod: string;
  objective: string;
  target: string;
  dueDate: string;
  linkedTarget?: string;
  status: string;
  progress: number;
}

export interface StoreKPI {
  id: string;
  employeeId: string;
  employee: string;
  department: string;
  role: string;
  employeeType: string;
  hod: string;
  kpiName: string;
  description: string;
  target: number;
  current: number;
  unit: string;
  period: string;
  status: string;
  progress: number;
}

export interface StoreQuarterlyTarget {
  id: string;
  employeeId: string;
  employee: string;
  department: string;
  role: string;
  employeeType: string;
  hod: string;
  quarter: string;
  title: string;
  description: string;
  target: string;
  unit?: string;
  dueDate: string;
  status: string;
  progress: number;
}

export interface StoreIPI {
  id: string;
  employeeId: string;
  employee: string;
  department: string;
  role: string;
  employeeType: string;
  hod: string;
  indicator: string;
  baseline: number;
  target: number;
  current: number;
  unit: string;
  workPlan?: { objective: string };
  progress: number;
}

export interface StorePIP {
  id: string;
  employeeId: string;
  employee: string;
  department: string;
  role: string;
  employeeType: string;
  hod: string;
  title: string;
  description: string;
  startDate: string;
  endDate: string;
  improvementAreas: string;
  status: string;
  progress: number;
}

export interface StoreAppraisal {
  id: string;
  employeeId: string;
  period: string;
  status: string;
  overallRating: number;
  selfAssessmentComments?: string;
  hodComments?: string;
  companyGoalRatings: { goalId: string; selfRating: number; hodRating?: number }[];
}

export interface StoreCompanyGoal {
  id: string;
  title: string;
}

interface PerformanceStore {
  comments: PerformanceComment[];
  deptTargets: SharedDeptTarget[];
  employees: StoreEmployee[];
  workPlans: StoreWorkPlan[];
  kpis: StoreKPI[];
  quarterlyTargets: StoreQuarterlyTarget[];
  ipis: StoreIPI[];
  pips: StorePIP[];
  appraisals: StoreAppraisal[];
  companyGoals: StoreCompanyGoal[];
  addComment: (c: Omit<PerformanceComment, 'id' | 'createdAt' | 'read'>) => void;
  markRead: (commentId: string) => void;
  getCommentsFor: (employeeId: string, itemType?: string) => PerformanceComment[];
  addDeptTarget: (target: Omit<SharedDeptTarget, 'id' | 'createdAt'>) => void;
  getDeptTargets: (dept: string) => SharedDeptTarget[];
  updateDeptTarget: (id: string, updates: Partial<SharedDeptTarget>) => void;
}

const PerformanceStoreContext = createContext<PerformanceStore | undefined>(undefined);

const INITIAL_EMPLOYEES: StoreEmployee[] = [
  { id: 'UF001', name: 'Jane Mwangi', dept: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei' },
  { id: 'UF002', name: 'Peter Otieno', dept: 'ICT', role: 'Systems Administrator', employeeType: 'Employee', hod: 'Mr. Brian Omondi' },
  { id: 'UF003', name: 'Mary Kamau', dept: 'Communications', role: 'Communications Officer', employeeType: 'Employee', hod: 'Mr. Robert Kariuki' },
  { id: 'UF004', name: 'David Njoroge', dept: 'Operations', role: 'Transport Officer', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku' },
  { id: 'UF005', name: 'Grace Wanjiku', dept: 'Operations', role: 'Operations Officer', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku' },
  { id: 'UF006', name: 'Samuel Kipchoge', dept: 'Operations', role: 'Driver', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku' },
  { id: 'UF007', name: 'Fatuma Hassan', dept: 'M&E', role: 'Data Analyst', employeeType: 'Employee', hod: 'Dr. Amina Osei' },
  { id: 'UF008', name: 'John Mutua', dept: 'Finance', role: 'Senior Finance Manager', employeeType: 'Employee', hod: 'Mr. John Mutua' },
  { id: 'UF009', name: 'Alice Odhiambo', dept: 'ICT', role: 'Software Developer', employeeType: 'Employee', hod: 'Mr. Brian Omondi' },
  { id: 'UF010', name: 'Robert Kariuki', dept: 'Communications', role: 'PR Specialist', employeeType: 'Employee', hod: 'Mr. Robert Kariuki' },
  { id: 'UF011', name: 'Esther Njeri', dept: 'HR', role: 'HR Officer', employeeType: 'Employee', hod: 'Ms. Esther Njeri' },
  { id: 'UF012', name: 'Brian Omondi', dept: 'ICT', role: 'Head of ICT', employeeType: 'Employee', hod: 'Mr. Brian Omondi' },
  { id: 'UF013', name: 'Kevin Maina', dept: 'Finance', role: 'Finance Intern', employeeType: 'Intern', hod: 'Mr. John Mutua' },
  { id: 'UF014', name: 'Amina Osei', dept: 'M&E', role: 'Head of M&E', employeeType: 'Employee', hod: 'Dr. Amina Osei' },
];

const INITIAL_WORK_PLANS: StoreWorkPlan[] = [
  { id: 'WP-UF001-1', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', objective: 'Improve M&E data collection accuracy', target: '95% accuracy rate', dueDate: '2026-06-30', linkedTarget: 'Complete mid-year M&E report', status: 'In Progress', progress: 78 },
  { id: 'WP-UF001-2', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', objective: 'Submit quarterly donor reports on time', target: '100% on-time submission', dueDate: '2026-03-31', linkedTarget: 'Conduct quarterly donor visits', status: 'Completed', progress: 100 },
  { id: 'WP-UF002-1', employeeId: 'UF002', employee: 'Peter Otieno', department: 'ICT', role: 'Systems Administrator', employeeType: 'Employee', hod: 'Mr. Brian Omondi', objective: 'Deploy new training portal', target: 'Fully functional portal by Q2', dueDate: '2026-06-30', linkedTarget: 'Digitize training management system', status: 'In Progress', progress: 55 },
  { id: 'WP-UF003-1', employeeId: 'UF003', employee: 'Mary Kamau', department: 'Communications', role: 'Communications Officer', employeeType: 'Employee', hod: 'Mr. Robert Kariuki', objective: 'Execute Q2 social media campaign', target: '40% visibility increase', dueDate: '2026-06-30', linkedTarget: 'Execute KSH 1.84M media budget', status: 'In Progress', progress: 65 },
  { id: 'WP-UF004-1', employeeId: 'UF004', employee: 'David Njoroge', department: 'Operations', role: 'Transport Officer', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', objective: 'Coordinate transport for all field events', target: 'Zero transport failures in Q2', dueDate: '2026-06-30', linkedTarget: 'Coordinate 7 beneficiary events', status: 'In Progress', progress: 80 },
  { id: 'WP-UF006-1', employeeId: 'UF006', employee: 'Samuel Kipchoge', department: 'Operations', role: 'Driver', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', objective: 'Improve punctuality and vehicle compliance', target: 'Zero late departures', dueDate: '2026-07-10', linkedTarget: 'Coordinate 7 beneficiary events', status: 'In Progress', progress: 30 },
  { id: 'WP-UF007-1', employeeId: 'UF007', employee: 'Fatuma Hassan', department: 'M&E', role: 'Data Analyst', employeeType: 'Employee', hod: 'Dr. Amina Osei', objective: 'Build Power BI dashboard for Q2 tracking', target: 'Dashboard live by April 30', dueDate: '2026-04-30', linkedTarget: 'Conduct quarterly donor visits', status: 'Completed', progress: 100 },
  { id: 'WP-UF013-1', employeeId: 'UF013', employee: 'Kevin Maina', department: 'Finance', role: 'Finance Intern', employeeType: 'Intern', hod: 'Mr. John Mutua', objective: 'Support payment processing and donor reporting', target: 'Process 50 payments within 30-day target', dueDate: '2026-06-30', linkedTarget: 'Process all payments within 30 days', status: 'In Progress', progress: 60 },
];

const INITIAL_KPIS: StoreKPI[] = [
  { id: 'KPI-UF001-1', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', kpiName: 'Data Quality Score', description: 'Accuracy of collected M&E data', target: 90, current: 82, unit: '%', period: 'Q2 2026', status: 'Active', progress: 82 },
  { id: 'KPI-UF001-2', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', kpiName: 'Report Submission Rate', description: 'Percentage of reports submitted on time', target: 100, current: 100, unit: '%', period: 'Q1 2026', status: 'Completed', progress: 100 },
  { id: 'KPI-UF002-1', employeeId: 'UF002', employee: 'Peter Otieno', department: 'ICT', role: 'Systems Administrator', employeeType: 'Employee', hod: 'Mr. Brian Omondi', kpiName: 'System Uptime', description: 'Percentage of system availability', target: 99.5, current: 98.8, unit: '%', period: 'Q2 2026', status: 'Active', progress: 70 },
  { id: 'KPI-UF003-1', employeeId: 'UF003', employee: 'Mary Kamau', department: 'Communications', role: 'Communications Officer', employeeType: 'Employee', hod: 'Mr. Robert Kariuki', kpiName: 'Media Budget Utilization', description: 'KSH 1.84M budget execution rate', target: 100, current: 75, unit: '%', period: 'Q2 2026', status: 'Active', progress: 75 },
  { id: 'KPI-UF004-1', employeeId: 'UF004', employee: 'David Njoroge', department: 'Operations', role: 'Transport Officer', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', kpiName: 'Event Transport Coverage', description: 'Events supported with zero transport failures', target: 7, current: 7, unit: 'events', period: 'Q1 2026', status: 'Completed', progress: 100 },
  { id: 'KPI-UF007-1', employeeId: 'UF007', employee: 'Fatuma Hassan', department: 'M&E', role: 'Data Analyst', employeeType: 'Employee', hod: 'Dr. Amina Osei', kpiName: 'Data Reports Delivered', description: 'Donor visit data reports produced on time', target: 4, current: 4, unit: 'reports', period: 'Q1 2026', status: 'Completed', progress: 100 },
  { id: 'KPI-UF013-1', employeeId: 'UF013', employee: 'Kevin Maina', department: 'Finance', role: 'Finance Intern', employeeType: 'Intern', hod: 'Mr. John Mutua', kpiName: 'Payment Requests Processed', description: 'Number of payments processed within 30 days', target: 50, current: 45, unit: 'payments', period: 'Q1 2026', status: 'Active', progress: 90 },
];

const INITIAL_QUARTERLY_TARGETS: StoreQuarterlyTarget[] = [
  { id: 'QT-UF001-1', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', quarter: 'Q1', title: 'Complete baseline data collection', description: 'Gather all Q1 M&E data across 47 counties', target: '100%', dueDate: '2026-03-31', status: 'Completed', progress: 100 },
  { id: 'QT-UF001-2', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', quarter: 'Q2', title: 'Submit mid-year M&E report', description: 'Comprehensive mid-year report with all annexes', target: '1 report', dueDate: '2026-06-30', status: 'In Progress', progress: 65 },
  { id: 'QT-UF002-1', employeeId: 'UF002', employee: 'Peter Otieno', department: 'ICT', role: 'Systems Administrator', employeeType: 'Employee', hod: 'Mr. Brian Omondi', quarter: 'Q2', title: 'Deploy training management portal', description: 'Fully digitize the training portal', target: '80% digital', dueDate: '2026-06-30', status: 'Delayed', progress: 40 },
  { id: 'QT-UF003-1', employeeId: 'UF003', employee: 'Mary Kamau', department: 'Communications', role: 'Communications Officer', employeeType: 'Employee', hod: 'Mr. Robert Kariuki', quarter: 'Q1', title: 'Execute Q1 media activities', description: 'Run Q1 media campaigns using allocated budget', target: 'KSH 460K utilized', unit: 'KSH', dueDate: '2026-03-31', status: 'Completed', progress: 100 },
  { id: 'QT-UF004-1', employeeId: 'UF004', employee: 'David Njoroge', department: 'Operations', role: 'Transport Officer', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', quarter: 'Q1', title: 'Support all 7 beneficiary events', description: 'Coordinate transport for all planned events', target: '7', unit: 'events', dueDate: '2026-03-31', status: 'Completed', progress: 100 },
  { id: 'QT-UF006-1', employeeId: 'UF006', employee: 'Samuel Kipchoge', department: 'Operations', role: 'Driver', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', quarter: 'Q2', title: 'PIP compliance — zero late departures', description: 'Meet all PIP targets for punctuality', target: '0', unit: 'late departures', dueDate: '2026-07-10', status: 'In Progress', progress: 30 },
  { id: 'QT-UF007-1', employeeId: 'UF007', employee: 'Fatuma Hassan', department: 'M&E', role: 'Data Analyst', employeeType: 'Employee', hod: 'Dr. Amina Osei', quarter: 'Q1', title: 'Deliver Q1 donor visit analysis', description: 'Produce data analysis reports for all donor visits', target: '4 reports', dueDate: '2026-03-31', status: 'Completed', progress: 100 },
];

const INITIAL_IPIS: StoreIPI[] = [
  { id: 'IPI-UF001-1', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', indicator: 'Forms submitted before Friday deadline', baseline: 70, target: 100, current: 85, unit: '%', workPlan: { objective: 'Design new data collection forms' }, progress: 85 },
  { id: 'IPI-UF001-2', employeeId: 'UF001', employee: 'Jane Mwangi', department: 'M&E', role: 'M&E Officer', employeeType: 'Employee', hod: 'Dr. Amina Osei', indicator: 'Training completion rate per officer', baseline: 60, target: 100, current: 70, unit: '%', workPlan: { objective: 'Train 15 field officers' }, progress: 70 },
  { id: 'IPI-UF002-1', employeeId: 'UF002', employee: 'Peter Otieno', department: 'ICT', role: 'Systems Administrator', employeeType: 'Employee', hod: 'Mr. Brian Omondi', indicator: 'System incident response time', baseline: 4, target: 1, current: 2, unit: 'hours', workPlan: { objective: 'Reduce system downtime to below 0.5%' }, progress: 50 },
  { id: 'IPI-UF003-1', employeeId: 'UF003', employee: 'Mary Kamau', department: 'Communications', role: 'Communications Officer', employeeType: 'Employee', hod: 'Mr. Robert Kariuki', indicator: 'Social media engagement rate', baseline: 3, target: 8, current: 6, unit: '%', workPlan: { objective: 'Execute Q2 social media campaign' }, progress: 75 },
  { id: 'IPI-UF007-1', employeeId: 'UF007', employee: 'Fatuma Hassan', department: 'M&E', role: 'Data Analyst', employeeType: 'Employee', hod: 'Dr. Amina Osei', indicator: 'Dashboard accuracy rate', baseline: 80, target: 98, current: 95, unit: '%', workPlan: { objective: 'Build Power BI dashboard for Q2 tracking' }, progress: 95 },
];

const INITIAL_PIPS: StorePIP[] = [
  { id: 'PIP-UF006-1', employeeId: 'UF006', employee: 'Samuel Kipchoge', department: 'Operations', role: 'Driver', employeeType: 'Employee', hod: 'Ms. Grace Wanjiku', title: 'Punctuality and Reliability Improvement Plan', description: 'Targeted plan to address recurring punctuality and vehicle compliance issues.', startDate: '2026-04-10', endDate: '2026-07-10', improvementAreas: 'Zero late departures; Vehicle maintenance compliance; Daily check-ins with supervisor', status: 'In Progress', progress: 30 },
];

const INITIAL_APPRAISALS: StoreAppraisal[] = [
  { id: 'AP001', employeeId: 'UF001', period: 'Q1 2026', status: 'Approved by HOD', overallRating: 4.2, selfAssessmentComments: 'Proud of M&E contribution. All donor visits facilitated on time.', hodComments: 'Jane has performed exceptionally well. Recommend for recognition.', companyGoalRatings: [{ goalId: 'CG2', selfRating: 4, hodRating: 4 }, { goalId: 'CG6', selfRating: 5, hodRating: 5 }] },
  { id: 'AP002', employeeId: 'UF002', period: 'Q1 2026', status: 'Approved by HOD', overallRating: 3.1, selfAssessmentComments: 'Maintained system stability. Acknowledge downtime target not fully met.', hodComments: 'Meets basic expectations but needs to improve system reliability.', companyGoalRatings: [{ goalId: 'CG2', selfRating: 3, hodRating: 3 }] },
  { id: 'AP003', employeeId: 'UF007', period: 'Q1 2026', status: 'Pending HOD Approval', overallRating: 0, selfAssessmentComments: 'Delivered all data products on time. Power BI dashboard well received.', companyGoalRatings: [{ goalId: 'CG2', selfRating: 4 }, { goalId: 'CG6', selfRating: 4 }] },
  { id: 'AP004', employeeId: 'UF003', period: 'Q1 2026', status: 'Submitted', overallRating: 0, selfAssessmentComments: 'Q1 communications activities executed successfully.', companyGoalRatings: [{ goalId: 'CG4', selfRating: 4 }] },
  { id: 'AP005', employeeId: 'UF006', period: 'Q1 2026', status: 'Approved by HOD', overallRating: 1.8, selfAssessmentComments: 'Faced some challenges with vehicle maintenance. Committed to improving.', hodComments: 'Performance below expectations. Punctuality issues persist. PIP initiated.', companyGoalRatings: [{ goalId: 'CG1', selfRating: 2, hodRating: 2 }] },
  { id: 'AP007', employeeId: 'UF013', period: 'Q1 2026', status: 'Approved by HOD', overallRating: 3.5, selfAssessmentComments: 'Learned a lot and contributed to payment processing.', hodComments: 'Hardworking intern showing great potential. Recommend continued attachment.', companyGoalRatings: [{ goalId: 'CG1', selfRating: 3, hodRating: 4 }] },
  { id: 'AP008', employeeId: 'UF004', period: 'Q1 2026', status: 'Completed', overallRating: 4.5, selfAssessmentComments: 'Proud of transport coordination. All events covered without major issues.', hodComments: 'David has shown excellent performance. Key enabler for field activities.', companyGoalRatings: [{ goalId: 'CG1', selfRating: 5, hodRating: 4 }] },
];

const INITIAL_COMPANY_GOALS: StoreCompanyGoal[] = [
  { id: 'CG1', title: 'Reach 6,000 beneficiaries with business development services' },
  { id: 'CG2', title: 'Train 10,870 youth online using digital tools' },
  { id: 'CG3', title: 'Issue certificates online and in paper format' },
  { id: 'CG4', title: 'Execute KSH 1.84M media and visibility budget' },
  { id: 'CG5', title: 'Build capacity of 44 board members' },
  { id: 'CG6', title: 'Conduct quarterly donor visits and M&E reporting' },
];

const INITIAL_COMMENTS: PerformanceComment[] = [
  { id: 'PC001', employeeId: 'UF001', itemType: 'kpi', itemId: 'K1', itemTitle: 'Data Quality Score', commentBy: 'Evans Oyaro', commentByRole: 'HOD', comment: 'Good progress on data quality. Please ensure all field officers are submitting validated data. Target 90% by end of Q2.', createdAt: '2026-04-10', read: false },
  { id: 'PC002', employeeId: 'UF001', itemType: 'workplan', itemId: 'WP1', itemTitle: 'Improve M&E data collection accuracy', commentBy: 'Evans Oyaro', commentByRole: 'HOD', comment: 'Work plan is on track. Please prioritize the pilot test in Kisumu and Nairobi counties first. Report back by May 20.', createdAt: '2026-04-12', read: false },
  { id: 'PC003', employeeId: 'UF002', itemType: 'quarterly', itemId: 'QT1', itemTitle: 'Deploy new training portal', commentBy: 'Gedion Njoroge', commentByRole: 'HOD', comment: 'The portal deployment is behind schedule. Please update the progress report and provide a revised timeline by end of week.', createdAt: '2026-04-15', read: false },
];

const INITIAL_DEPT_TARGETS: SharedDeptTarget[] = [
  { id: 'SDT-ICT-1', dept: 'ICT', title: 'Digitize 80% of internal processes', description: 'Migrate manual workflows to digital platforms across all departments.', quarter: 'Q2', expectedOutcomes: 'All departments using digital tools for reporting and communication.', deadline: '2026-06-30', priority: 'High', measurableObjectives: '80% of processes digitized; 100% staff trained on digital tools.', progress: 45, status: 'Ongoing', createdAt: '2026-04-01' },
  { id: 'SDT-ICT-2', dept: 'ICT', title: 'Reduce system downtime to below 0.5%', description: 'Improve IT infrastructure reliability across all systems.', quarter: 'Q2', expectedOutcomes: 'System uptime at 99.5% or better.', deadline: '2026-06-30', priority: 'Medium', measurableObjectives: 'Monthly uptime reports showing 99.5%+ availability.', progress: 30, status: 'Delayed', createdAt: '2026-04-01' },
  { id: 'SDT-ME-1', dept: 'M&E', title: 'Support 500 youth enterprises', description: 'Provide business development support to 500 youth enterprises in Q3.', quarter: 'Q3', expectedOutcomes: '500 beneficiaries trained and linked to banking partners.', deadline: '2026-09-30', priority: 'High', measurableObjectives: '500 enterprises registered; 80% accessing loans.', progress: 62, status: 'Ongoing', createdAt: '2026-04-01' },
  { id: 'SDT-ME-2', dept: 'M&E', title: 'Complete mid-year impact assessment', description: 'Conduct comprehensive M&E data collection across 47 counties.', quarter: 'Q2', expectedOutcomes: 'Impact assessment report published.', deadline: '2026-06-30', priority: 'High', measurableObjectives: '3,000 beneficiary interviews; report submitted by June 30.', progress: 55, status: 'Ongoing', createdAt: '2026-04-01' },
  { id: 'SDT-Finance-1', dept: 'Finance', title: 'Complete FY2026 budget reconciliation', description: 'Reconcile all departmental budgets by end of Q2.', quarter: 'Q2', expectedOutcomes: 'Zero outstanding reconciliation issues.', deadline: '2026-06-30', priority: 'High', measurableObjectives: '100% reconciliation rate; external audit passed.', progress: 40, status: 'Ongoing', createdAt: '2026-04-01' },
  { id: 'SDT-HR-1', dept: 'HR', title: 'Digitize all employee records', description: 'Complete migration of paper HR records to HRMS.', quarter: 'Q2', expectedOutcomes: '100% of employee files in digital format.', deadline: '2026-06-30', priority: 'Medium', measurableObjectives: 'All records uploaded and verified; zero paper dependencies.', progress: 70, status: 'Ongoing', createdAt: '2026-04-01' },
];

export function PerformanceStoreProvider({ children }: { children: ReactNode }) {
  const [comments, setComments] = useState<PerformanceComment[]>(INITIAL_COMMENTS);
  const [deptTargets, setDeptTargets] = useState<SharedDeptTarget[]>(INITIAL_DEPT_TARGETS);

  const addComment = (c: Omit<PerformanceComment, 'id' | 'createdAt' | 'read'>) => {
    const newComment: PerformanceComment = { ...c, id: `PC${Date.now()}`, createdAt: new Date().toISOString().split('T')[0], read: false };
    setComments(prev => [newComment, ...prev]);
  };

  const markRead = (commentId: string) => {
    setComments(prev => prev.map(c => c.id === commentId ? { ...c, read: true } : c));
  };

  const getCommentsFor = (employeeId: string, itemType?: string) => {
    return comments.filter(c => c.employeeId === employeeId && (!itemType || c.itemType === itemType));
  };

  const addDeptTarget = (target: Omit<SharedDeptTarget, 'id' | 'createdAt'>) => {
    const newTarget: SharedDeptTarget = { ...target, id: `SDT-${target.dept}-${Date.now()}`, createdAt: new Date().toISOString().split('T')[0] };
    setDeptTargets(prev => [newTarget, ...prev]);
  };

  const getDeptTargets = (dept: string): SharedDeptTarget[] => {
    return deptTargets.filter(t => t.dept === dept);
  };

  const updateDeptTarget = (id: string, updates: Partial<SharedDeptTarget>) => {
    setDeptTargets(prev => prev.map(t => t.id === id ? { ...t, ...updates } : t));
  };

  return (
    <PerformanceStoreContext.Provider value={{
      comments,
      deptTargets,
      employees: INITIAL_EMPLOYEES,
      workPlans: INITIAL_WORK_PLANS,
      kpis: INITIAL_KPIS,
      quarterlyTargets: INITIAL_QUARTERLY_TARGETS,
      ipis: INITIAL_IPIS,
      pips: INITIAL_PIPS,
      appraisals: INITIAL_APPRAISALS,
      companyGoals: INITIAL_COMPANY_GOALS,
      addComment,
      markRead,
      getCommentsFor,
      addDeptTarget,
      getDeptTargets,
      updateDeptTarget,
    }}>
      {children}
    </PerformanceStoreContext.Provider>
  );
}

export function usePerformanceStore() {
  const ctx = useContext(PerformanceStoreContext);
  if (!ctx) throw new Error('usePerformanceStore must be used within PerformanceStoreProvider');
  return ctx;
}