/** Progress 0–100 for logo loader during setup wizard. */

const STEP_WEIGHTS = {
  theme: 10,
  welcome: 5,
  device: 12,
  network: 18,
  sync: 18,
  users: 22,
  hardware: 10,
  kiosk: 10,
  bootstrap: 25,
  done: 8,
};

const FLOWS = {
  server: ["theme", "welcome", "device", "network", "users", "done"],
  client: ["theme", "welcome", "device", "sync", "hardware", "kiosk", "bootstrap", "done"],
};

export function getFlow(deviceRole) {
  return FLOWS[deviceRole] || FLOWS.server;
}

export function createSetupOrchestrator() {
  let deviceRole = "server";
  let currentStep = "welcome";
  let extraPercent = 0;

  function flow() {
    return getFlow(deviceRole);
  }

  function basePercent() {
    const steps = flow();
    const idx = steps.indexOf(currentStep);
    if (idx < 0) return 0;
    let total = 0;
    for (const s of steps) total += STEP_WEIGHTS[s] || 10;
    let done = 0;
    for (let i = 0; i < idx; i += 1) done += STEP_WEIGHTS[steps[i]] || 10;
    const curWeight = STEP_WEIGHTS[currentStep] || 10;
    return Math.min(100, Math.round(((done + curWeight * 0.35) / total) * 100));
  }

  return {
    get percent() {
      return Math.min(100, Math.max(basePercent(), extraPercent));
    },
    get currentStep() {
      return currentStep;
    },
    get deviceRole() {
      return deviceRole;
    },
    setDeviceRole(role) {
      deviceRole = role;
    },
    setStep(step) {
      currentStep = step;
      extraPercent = 0;
    },
    bumpExtra(delta) {
      extraPercent = Math.min(100, extraPercent + delta);
    },
    setBootstrapProgress(p) {
      const steps = flow();
      const idx = steps.indexOf("bootstrap");
      if (idx < 0) return;
      let total = 0;
      let before = 0;
      for (let i = 0; i < steps.length; i += 1) {
        const w = STEP_WEIGHTS[steps[i]] || 10;
        if (i < idx) before += w;
        total += w;
      }
      const w = STEP_WEIGHTS.bootstrap || 25;
      extraPercent = Math.round(((before + w * Math.min(1, p)) / total) * 100);
    },
    flow,
  };
}
