const STORAGE_KEY = 'prorank_internal_linking_workflow_state_v1';
const STORAGE_VERSION = 1;

const defaultState = () => ({
  version: STORAGE_VERSION,
  lastResetAt: null,
  actions: {},
});

const hasWindow = () => typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';

export const loadWorkflowState = () => {
  if (!hasWindow()) {
    return defaultState();
  }

  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) {
      return defaultState();
    }

    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object') {
      return defaultState();
    }

    return {
      version: STORAGE_VERSION,
      lastResetAt: parsed.lastResetAt || null,
      actions: parsed.actions && typeof parsed.actions === 'object' ? parsed.actions : {},
    };
  } catch (error) {
    return defaultState();
  }
};

export const saveWorkflowState = (state) => {
  if (!hasWindow()) {
    return state;
  }

  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
  } catch (error) {
    // Ignore persistence failures; workflow still runs from in-memory state.
  }

  return state;
};

export const markWorkflowAction = (stepId, prevState = null) => {
  const state = prevState || loadWorkflowState();
  const nextState = {
    ...state,
    actions: {
      ...(state.actions || {}),
      [stepId]: new Date().toISOString(),
    },
  };

  return saveWorkflowState(nextState);
};

export const resetWorkflowState = () => {
  const nextState = {
    ...defaultState(),
    lastResetAt: new Date().toISOString(),
  };

  return saveWorkflowState(nextState);
};

const normalizeSteps = (steps) =>
  steps.map((step) => ({
    ...step,
    prerequisites: Array.isArray(step.prerequisites) ? step.prerequisites : [],
  }));

export const buildWorkflowModel = (stepsInput = []) => {
  const steps = normalizeSteps(stepsInput);

  const completionById = new Map(
    steps.map((step) => [step.id, Boolean(step.complete)])
  );

  const withStatus = steps.map((step) => {
    const blockedBy = step.prerequisites.find((id) => !completionById.get(id)) || null;
    const complete = Boolean(step.complete);
    const status = complete ? 'complete' : blockedBy ? 'blocked' : 'ready';

    return {
      ...step,
      complete,
      status,
      blockedBy,
      canAct: !blockedBy && !Boolean(step.disabled),
    };
  });

  const completeCount = withStatus.filter((step) => step.complete).length;
  const progress = withStatus.length > 0
    ? Math.round((completeCount / withStatus.length) * 100)
    : 0;

  const nextReadyStep = withStatus.find((step) => step.status === 'ready') || null;
  const nextBlockedStep = withStatus.find((step) => step.status === 'blocked') || null;

  return {
    steps: withStatus,
    completeCount,
    progress,
    nextReadyStep,
    nextBlockedStep,
    isComplete: withStatus.length > 0 && completeCount === withStatus.length,
  };
};

