import { STORAGE_KEY, DEMO_PHONE, MOCK_SMS_CODE } from './constants';

export function createInitialState(overrides = {}) {
  const now = new Date().toISOString();
  return {
    trainingTask: {
      taskId: 'JC202607170023',
      projectName: '上海示范运营项目',
      vehiclePlate: '浙F·****8',
      vehicleType: '49吨氢能重卡',
      vehicleTonnage: 49,
      plannedDate: '2026-07-20',
      requiredVehicleClass: 'A2',
      ...overrides.trainingTask,
    },
    currentStep: 1,
    maxCompletedStep: 0,
    step1: {
      readProgress: 0,
      scrolledToBottom: false,
      confirmed: false,
      checked: false,
      startTime: null,
      endTime: null,
      confirmTime: null,
      documentVersion: null,
    },
    step2: {
      phone: DEMO_PHONE,
      code: MOCK_SMS_CODE,
      verified: false,
      verifiedAt: null,
    },
    step3: {
      certificates: {},
    },
    step4: {
      completed: false,
      watchedSeconds: 0,
      completedAt: null,
    },
    step5: {
      photoDataUrl: null,
      confirmed: false,
      capturedAt: null,
    },
    step6: {
      signatureDataUrl: null,
      checked: false,
      submitted: false,
      submittedAt: null,
    },
    step7: {
      pickupCode: null,
      numericCode: null,
      status: 'pending',
      generatedAt: null,
      completedAt: null,
      lockedAt: null,
    },
    debug: {
      vehicleTonnage: 49,
      ocrMode: 'success',
      cameraPermission: 'allow',
      videoStatus: 'incomplete',
      pickupStatus: 'pending',
    },
    createdAt: now,
    updatedAt: now,
  };
}

export function loadTrainingState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return createInitialState();
    const parsed = JSON.parse(raw);
    const merged = { ...createInitialState(), ...parsed };
    merged.trainingTask.vehicleTonnage = merged.debug?.vehicleTonnage ?? merged.trainingTask.vehicleTonnage;
    if (merged.step6?.submitted && merged.step7?.pickupCode && merged.currentStep < 8) {
      merged.currentStep = 8;
      merged.maxCompletedStep = Math.max(merged.maxCompletedStep || 0, 8);
    }
    if (merged.currentStep === 7 && merged.step7?.pickupCode && !merged.step6?.signatureDataUrl) {
      merged.currentStep = 8;
    }
    return merged;
  } catch {
    return createInitialState();
  }
}

export function saveTrainingState(state) {
  const toSave = { ...state, updatedAt: new Date().toISOString() };
  localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
  return toSave;
}

export function resetTrainingState() {
  localStorage.removeItem(STORAGE_KEY);
  return createInitialState();
}

export function generatePickupCode() {
  return String(Math.floor(100000 + Math.random() * 900000));
}
