import React, { createContext, useContext, useState, useCallback } from "react";

const ScanContext = createContext(null);

export function useScan() {
  const ctx = useContext(ScanContext);
  if (!ctx) {
    throw new Error("useScan must be used within ScanProvider");
  }
  return ctx;
}

/**
 * ScanProvider – hält scanning + scanProgress für Scan-UI (Loader, Dashboard ausblenden, etc.)
 */
export function ScanProvider({ children }) {
  const [scanning, setScanning] = useState(false);
  const [scanProgress, setScanProgress] = useState({
    percent: 0,
    phase: "idle",
    total: 0,
    current: 0,
    complete: false,
  });

  const startScan = useCallback(() => {
    setScanning(true);
    setScanProgress({ percent: 0, phase: "listing", total: 0, current: 0, complete: false });
  }, []);

  const updateProgress = useCallback((data) => {
    setScanProgress((prev) => ({ ...prev, ...data }));
  }, []);

  const endScan = useCallback(() => {
    setScanning(false);
    setScanProgress({ percent: 0, phase: "idle", total: 0, current: 0, complete: false });
  }, []);

  const value = {
    scanning,
    setScanning,
    scanProgress,
    setScanProgress,
    startScan,
    updateProgress,
    endScan,
  };

  return <ScanContext.Provider value={value}>{children}</ScanContext.Provider>;
}
