export type Position = {
  id: string;
  title: string;
  department: string;
  location: string;
  openings: number;
  employmentType: "Full-time" | "Part-time" | "Contract" | "Internship";
};

export type Applicant = {
  id: string;
  name: string;
  role: string;
  stageId: string;
  email?: string;
  resumeFileName?: string;
  screeningEvaluation?: {
    candidate_name?: string;
    candidate_phone_number?: string;
    overall_fit_score?: number | string;
    matching_skills?: string[];
    skill_gaps?: string[];
    overall_summary?: string;
    raw?: string;
  };
  screeningPolicyId?: string;
  screeningCompletedAt?: string;
  scorecard?: {
    recommendation?: "hire" | "no_hire" | "strong_hire";
    rating?: 1 | 2 | 3 | 4 | 5;
    comments?: string;
    updatedAt?: string;
  };
  offerLetterEmbeddedSessionUrl?: string;
  offerLetterAuthorAccessUrl?: string;
  offerLetterFolderId?: string | number;
  offerLetterEsignStatus?: string;
  offerLetterSessionUpdatedAt?: string;
};

export type ApplicantWithPosition = Applicant & {
  positionId: string;
};

export const POSITIONS_STORAGE_KEY = "ats.positions.v1";
const APPLICANTS_BY_POSITION_KEY_PREFIX = "ats.applicantsByPosition.v1";
const ATS_SEED_VERSION_KEY = "ats.seedVersion";
const CURRENT_ATS_SEED_VERSION = "3";

export const initialPositions: Position[] = [
  {
    id: "pos_001",
    title: "Partner Sales Manager",
    department: "Sales",
    location: "San Francisco, CA",
    openings: 1,
    employmentType: "Full-time",
  },
  {
    id: "pos_002",
    title: "Product Designer",
    department: "Design",
    location: "Remote (US)",
    openings: 1,
    employmentType: "Full-time",
  },
  {
    id: "pos_003",
    title: "Technical Recruiter",
    department: "People",
    location: "Austin, TX",
    openings: 2,
    employmentType: "Full-time",
  },
  {
    id: "pos_004",
    title: "Data Analyst",
    department: "Operations",
    location: "New York, NY",
    openings: 1,
    employmentType: "Contract",
  },
];

export const initialApplicantsByPosition: Record<string, Applicant[]> = {
  pos_001: [
    { id: "app_001", name: "Aaliyah Carter", role: "Channel Account Executive", stageId: "new_applied" },
    {
      id: "app_002",
      name: "Miguel Santos",
      role: "Partner Development Representative",
      stageId: "resume_review_screening",
      screeningEvaluation: {
        candidate_name: "Miguel Santos",
        candidate_phone_number: "Unknown",
        overall_fit_score: 62,
        matching_skills: ["partner enablement", "pipeline development", "stakeholder communication"],
        skill_gaps: ["territory planning ownership", "executive-level forecasting cadence"],
        overall_summary:
          "Miguel Santos shows relevant partner-facing experience aligned with a Partner Sales Manager path, especially in partner development and cross-functional communication. He demonstrates strong collaboration and channel support fundamentals. The profile indicates moderate readiness with room to grow in full territory ownership and senior forecasting rigor.",
      },
      screeningPolicyId: "EvaluationPolicy#v1.1",
      screeningCompletedAt: "2026-02-20T00:02:15.000Z",
      scorecard: {
        recommendation: "hire",
        rating: 4,
        comments:
          "Strong relationship-building and partner communication skills. Recommend advancing with focus questions on forecast discipline and territory ownership.",
        updatedAt: "2026-02-20T00:02:45.000Z",
      },
    },
    {
      id: "app_003",
      name: "Daniel Kim",
      role: "Strategic Alliances Manager",
      stageId: "resume_review_screening",
      screeningEvaluation: {
        candidate_name: "Daniel Kim",
        candidate_phone_number: "Unknown",
        overall_fit_score: 30,
        matching_skills: [],
        skill_gaps: ["c++", "python", "aws"],
        overall_summary:
          "The candidate has a diverse background primarily in Strategic Alliances, Sales, and Business Development with deep partner-motion experience. However, the profile does not demonstrate software engineering competencies or required technical stack skills such as C++, Python, and AWS cloud services. This limits fit for a software-engineering-oriented evaluation policy and results in a low fit score.",
      },
      screeningPolicyId: "EvaluationPolicy#v1.0",
      screeningCompletedAt: "2026-02-20T00:03:10.000Z",
      scorecard: {
        recommendation: "no_hire",
        rating: 2,
        comments:
          "Strong alliances background but insufficient technical depth against current hard requirements.",
        updatedAt: "2026-02-20T00:03:40.000Z",
      },
    },
  ],
  pos_002: [
    { id: "app_004", name: "Priya Patel", role: "Product Designer", stageId: "new_applied" },
    {
      id: "app_005",
      name: "Elena Rossi",
      role: "Product Designer",
      stageId: "resume_review_screening",
      screeningEvaluation: {
        candidate_name: "Elena Rossi",
        candidate_phone_number: "Unknown",
        overall_fit_score: 41,
        matching_skills: ["cross-functional collaboration", "product thinking"],
        skill_gaps: ["channel sales strategy", "partner program operations"],
        overall_summary:
          "Elena Rossi demonstrates strong product collaboration and design-adjacent communication strengths. While these skills support teamwork and customer empathy, the profile only partially aligns with partner-sales-focused requirements and lacks direct channel program ownership evidence. Fit is moderate-low for this policy.",
      },
      screeningPolicyId: "EvaluationPolicy#v1.1",
      screeningCompletedAt: "2026-02-20T00:04:05.000Z",
      scorecard: {
        recommendation: "no_hire",
        rating: 2,
        comments:
          "Great collaboration profile, but role alignment is low for current partner-sales requirements.",
        updatedAt: "2026-02-20T00:04:28.000Z",
      },
    },
  ],
  pos_003: [
    { id: "app_006", name: "Jordan Lee", role: "Technical Recruiter", stageId: "new_applied" },
    {
      id: "app_007",
      name: "Noah Williams",
      role: "Technical Recruiter",
      stageId: "resume_review_screening",
      screeningEvaluation: {
        candidate_name: "Noah Williams",
        candidate_phone_number: "Unknown",
        overall_fit_score: 55,
        matching_skills: ["stakeholder communication", "pipeline management", "candidate qualification"],
        skill_gaps: ["quota-carrying sales experience", "partner ecosystem ownership"],
        overall_summary:
          "Noah Williams has solid process discipline and stakeholder management from technical recruiting, with strengths in qualification and pipeline handling. The profile overlaps with structured funnel management but has limited direct partner-sales execution or quota-based commercial ownership. Overall fit is moderate for the target role.",
      },
      screeningPolicyId: "EvaluationPolicy#v1.1",
      screeningCompletedAt: "2026-02-20T00:05:12.000Z",
      scorecard: {
        recommendation: "hire",
        rating: 3,
        comments:
          "Operationally strong and coachable. Consider for next round to test commercial and partner strategy depth.",
        updatedAt: "2026-02-20T00:05:37.000Z",
      },
    },
  ],
  pos_004: [
    { id: "app_010", name: "Liam Chen", role: "Data Analyst", stageId: "new_applied" },
    {
      id: "app_011",
      name: "Sofia Martinez",
      role: "Data Analyst",
      stageId: "resume_review_screening",
      screeningEvaluation: {
        candidate_name: "Sofia Martinez",
        candidate_phone_number: "Unknown",
        overall_fit_score: 36,
        matching_skills: ["data analysis", "reporting", "cross-team communication"],
        skill_gaps: ["partner account growth", "channel sales motion", "alliance negotiation"],
        overall_summary:
          "Sofia Martinez brings strong analytical strengths and structured reporting capability. These skills are valuable for decision support, but the current policy emphasizes partner-sales and alliance execution competencies that are not clearly demonstrated in the profile. Fit is limited for the evaluated role scope.",
      },
      screeningPolicyId: "EvaluationPolicy#v1.1",
      screeningCompletedAt: "2026-02-20T00:06:08.000Z",
      scorecard: {
        recommendation: "no_hire",
        rating: 2,
        comments:
          "Strong analyst profile; mismatch for partner-sales responsibilities in this requisition.",
        updatedAt: "2026-02-20T00:06:29.000Z",
      },
    },
  ],
};

function getInitialApplicantsForPosition(positionId: string) {
  return initialApplicantsByPosition[positionId] ?? [];
}

function getInitialApplicantById(applicantId: string): ApplicantWithPosition | undefined {
  for (const [positionId, applicants] of Object.entries(initialApplicantsByPosition)) {
    const applicant = applicants.find((item) => item.id === applicantId);
    if (applicant) {
      return { ...applicant, positionId };
    }
  }
  return undefined;
}

export function getPositionApplicantsStorageKey(positionId: string) {
  return `${APPLICANTS_BY_POSITION_KEY_PREFIX}:${positionId}`;
}

export function initializeAtsStorage() {
  if (typeof window === "undefined") {
    return;
  }

  const currentSeedVersion = window.localStorage.getItem(ATS_SEED_VERSION_KEY);
  if (currentSeedVersion !== CURRENT_ATS_SEED_VERSION) {
    resetAtsStorage();
    window.localStorage.setItem(ATS_SEED_VERSION_KEY, CURRENT_ATS_SEED_VERSION);
  }

  const existingPositions = window.localStorage.getItem(POSITIONS_STORAGE_KEY);
  if (!existingPositions) {
    window.localStorage.setItem(POSITIONS_STORAGE_KEY, JSON.stringify(initialPositions));
  }
}

export function resetAtsStorage() {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(POSITIONS_STORAGE_KEY);
  const keysToRemove: string[] = [];
  for (let i = 0; i < window.localStorage.length; i += 1) {
    const key = window.localStorage.key(i);
    if (key && key.startsWith(APPLICANTS_BY_POSITION_KEY_PREFIX)) {
      keysToRemove.push(key);
    }
  }
  for (const key of keysToRemove) {
    window.localStorage.removeItem(key);
  }
  window.localStorage.removeItem(ATS_SEED_VERSION_KEY);
}

export function readPositionsFromStorage() {
  if (typeof window === "undefined") {
    return initialPositions;
  }

  initializeAtsStorage();
  const raw = window.localStorage.getItem(POSITIONS_STORAGE_KEY);
  if (!raw) {
    return initialPositions;
  }

  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return parsed as Position[];
    }
  } catch {
    return initialPositions;
  }

  return initialPositions;
}

export function writePositionsToStorage(positions: Position[]) {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.setItem(POSITIONS_STORAGE_KEY, JSON.stringify(positions));
}

export function readApplicantsFromStorage(positionId: string) {
  const seededApplicants = getInitialApplicantsForPosition(positionId);

  if (typeof window === "undefined") {
    return seededApplicants;
  }

  const key = getPositionApplicantsStorageKey(positionId);
  const raw = window.localStorage.getItem(key);

  if (!raw) {
    window.localStorage.setItem(key, JSON.stringify(seededApplicants));
    return seededApplicants;
  }

  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return parsed as Applicant[];
    }
  } catch {
    return seededApplicants;
  }

  return seededApplicants;
}

export function writeApplicantsToStorage(positionId: string, applicants: Applicant[]) {
  if (typeof window === "undefined") {
    return;
  }

  const key = getPositionApplicantsStorageKey(positionId);
  window.localStorage.setItem(key, JSON.stringify(applicants));
}

export function readPositionByIdFromStorage(id: string) {
  const positions = readPositionsFromStorage();
  return positions.find((position) => position.id === id);
}

export function readAllApplicantsFromStorage() {
  const positions = readPositionsFromStorage();
  return positions.flatMap((position) =>
    readApplicantsFromStorage(position.id).map((applicant) => ({
      ...applicant,
      positionId: position.id,
    }))
  );
}

export function readApplicantByIdFromStorage(applicantId: string) {
  if (typeof window === "undefined") {
    return getInitialApplicantById(applicantId);
  }

  const applicants = readAllApplicantsFromStorage();
  return applicants.find((applicant) => applicant.id === applicantId);
}
