/**
 * Client-side record of the applicant's last successful submission so they can
 * reopen the review page and see status without relying on email/bookmarks alone.
 */
import type { ApplicationItem } from '@/data/mockApplications';
import type { SubmitInitiativeResponse } from '@/components/applicant/submitInitiativePdf';

const STORAGE_KEY = 'initiative:last-submission-v1';

export interface ApplicantSubmissionRecord {
  applicationId: string;
  caseId?: string;
  initiativeName: string;
  submittedAt: string;
  publicUrl?: string;
  /** Mirrors server `reviewStatus` when known */
  reviewStatus?: string;
  /** Mirrors server `status` when known */
  status?: string;
  updatedAt: string;
}

function safeParse(raw: string | null): ApplicantSubmissionRecord | null {
  if (!raw) return null;
  try {
    const v = JSON.parse(raw) as ApplicantSubmissionRecord;
    if (v && typeof v.applicationId === 'string' && typeof v.initiativeName === 'string') return v;
  } catch {
    /* ignore */
  }
  return null;
}

export function loadApplicantSubmissionRecord(): ApplicantSubmissionRecord | null {
  if (typeof window === 'undefined') return null;
  return safeParse(window.localStorage.getItem(STORAGE_KEY));
}

/** Clears last-submission shortcut (e.g. before starting a new registration). */
export function clearApplicantSubmissionRecord(): void {
  if (typeof window === 'undefined') return;
  try {
    window.localStorage.removeItem(STORAGE_KEY);
  } catch {
    /* ignore */
  }
}

export function saveApplicantSubmissionRecord(
  response: SubmitInitiativeResponse,
  extra: { caseId?: string; initiativeName: string },
): void {
  if (typeof window === 'undefined') return;
  const now = new Date().toISOString();
  const record: ApplicantSubmissionRecord = {
    applicationId: response.id,
    caseId: extra.caseId,
    initiativeName: extra.initiativeName,
    submittedAt: response.submittedDate,
    publicUrl: response.publicUrl,
    reviewStatus: 'not_reviewed',
    status: 'pending',
    updatedAt: now,
  };
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(record));
}

/** Call when `/api/applications/:id` returns so review status stays in sync. */
export function syncApplicantSubmissionFromApplicationItem(item: ApplicationItem): void {
  if (typeof window === 'undefined') return;
  const existing = loadApplicantSubmissionRecord();
  const now = new Date().toISOString();
  const record: ApplicantSubmissionRecord = {
    applicationId: item.id,
    caseId: existing?.applicationId === item.id ? existing.caseId : item.author.id,
    initiativeName: item.name,
    submittedAt: item.submittedDate,
    publicUrl: existing?.applicationId === item.id ? existing.publicUrl : undefined,
    reviewStatus: item.reviewStatus,
    status: item.status,
    updatedAt: now,
  };
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(record));
}
