// Shared cross-module state + mock data
const StoreCtx = React.createContext(null);

const SEED = {
  // Stock
  stock: [
    {
      id: 'hq',
      name: 'Barras HQ',
      category: 'Barras',
      qty: 48,
      min: 30,
      unit: 'u',
      lastMove: '2026-03-28',
    },
    {
      id: 'casing',
      name: 'Cañerías de revestimiento',
      category: 'Revestimiento',
      qty: 22,
      min: 20,
      unit: 'u',
      lastMove: '2026-03-20',
    },
    {
      id: 'bits',
      name: 'Bits (mechas)',
      category: 'Consumible',
      qty: 11,
      min: 6,
      unit: 'u',
      lastMove: '2026-03-30',
    },
    {
      id: 'hoses',
      name: 'Mangueras alta presión',
      category: 'Repuesto',
      qty: 1,
      min: 4,
      unit: 'u',
      lastMove: '2026-03-12',
    },
    {
      id: 'bent',
      name: 'Bentonita',
      category: 'Químico',
      qty: 1850,
      min: 600,
      unit: 'kg',
      lastMove: '2026-03-25',
    },
    {
      id: 'pacr',
      name: 'Polímero PAC-R',
      category: 'Químico',
      qty: 180,
      min: 100,
      unit: 'kg',
      lastMove: '2026-03-22',
    },
    {
      id: 'lub',
      name: 'Lubricante de fluido',
      category: 'Químico',
      qty: 32,
      min: 40,
      unit: 'L',
      lastMove: '2026-03-18',
    },
    {
      id: 'inhib',
      name: 'Inhibidor de corrosión',
      category: 'Químico',
      qty: 95,
      min: 40,
      unit: 'L',
      lastMove: '2026-03-10',
    },
  ],
  // Mantenimiento plan
  maintenance: [
    {
      id: 'm1',
      equipment: 'Rig-1',
      task: 'Cambio de aceite · motor principal',
      intervalHs: 250,
      lastHs: 1400,
      currentHs: 1820,
      status: 'overdue',
    },
    {
      id: 'm2',
      equipment: 'Rig-1',
      task: 'Revisión bomba de lodo',
      intervalHs: 1000,
      lastHs: 840,
      currentHs: 1820,
      status: 'soon',
    },
    {
      id: 'm3',
      equipment: 'Rig-1',
      task: 'Cambio filtros hidráulicos',
      intervalHs: 500,
      lastHs: 1400,
      currentHs: 1820,
      status: 'ok',
    },
    {
      id: 'm4',
      equipment: 'Rig-1',
      task: 'Inspección cabezales',
      intervalHs: 2000,
      lastHs: 1610,
      currentHs: 1820,
      status: 'ok',
    },
  ],
  maintHistory: [
    {
      id: 'h1',
      date: '2026-03-15',
      equipment: 'Rig-1',
      type: 'Cambio filtros',
      tech: 'M. Álvarez',
      hours: 1600,
      notes: 'Reemplazo preventivo de 3 filtros hidráulicos.',
    },
    {
      id: 'h2',
      date: '2026-02-28',
      equipment: 'Rig-1',
      type: 'Service general',
      tech: 'J. Pereyra',
      hours: 1420,
      notes: 'Chequeo de presiones y niveles.',
    },
    {
      id: 'h3',
      date: '2026-02-10',
      equipment: 'Rig-1',
      type: 'Cambio de aceite',
      tech: 'M. Álvarez',
      hours: 1400,
      notes: 'Aceite SAE 15W-40 · 42 L.',
    },
    {
      id: 'h4',
      date: '2026-01-22',
      equipment: 'Rig-1',
      type: 'Inspección cabezales',
      tech: 'R. Ibáñez',
      hours: 1200,
      notes: 'Sin observaciones.',
    },
  ],
  // Daily reports
  dailyReports: [
    {
      id: 'd1',
      date: '2026-03-31',
      shift: 'Mañana',
      operator: 'J. Pereyra',
      rig: 'Rig-1',
      metersDrilled: 34,
      hoursOp: 7.5,
      events: 1,
      notes: 'Operación normal, leve pico de presión a las 11:20.',
    },
    {
      id: 'd2',
      date: '2026-03-31',
      shift: 'Tarde',
      operator: 'C. Godoy',
      rig: 'Rig-1',
      metersDrilled: 28,
      hoursOp: 6.8,
      events: 0,
      notes: 'Sin novedades.',
    },
    {
      id: 'd3',
      date: '2026-03-30',
      shift: 'Mañana',
      operator: 'J. Pereyra',
      rig: 'Rig-1',
      metersDrilled: 31,
      hoursOp: 7.2,
      events: 2,
      notes: 'Cambio de mecha 09:40.',
    },
  ],
  // Alerts derived
  alerts: [
    {
      id: 'a1',
      level: 'high',
      title: 'Pico de presión 612 PSI · bomba de lodo',
      when: '14 mar · 22:47',
      meta: 'umbral 550 PSI',
    },
    {
      id: 'a2',
      level: 'high',
      title: 'Torque elevado prolongado · cabezal',
      when: '21 mar · 03:12',
      meta: 'duración 18 min',
    },
    {
      id: 'a3',
      level: 'med',
      title: 'Gap de captura 7h 52m',
      when: '09 mar · 02:00',
      meta: 'sensor caudal',
    },
    {
      id: 'a4',
      level: 'med',
      title: 'Cambio de aceite pendiente',
      when: 'ahora',
      meta: 'excedió 420 hs',
    },
    {
      id: 'a5',
      level: 'info',
      title: 'Stock de mangueras bajo',
      when: 'hoy',
      meta: '1 unidad · 12%',
    },
  ],
};

function storeReducer(state, action) {
  switch (action.type) {
    case 'stock/adjust': {
      return {
        ...state,
        stock: state.stock.map((i) =>
          i.id === action.id
            ? {
                ...i,
                qty: Math.max(0, i.qty + action.delta),
                lastMove: new Date().toISOString().slice(0, 10),
              }
            : i,
        ),
      };
    }
    case 'stock/set': {
      return {
        ...state,
        stock: state.stock.map((i) =>
          i.id === action.id
            ? {
                ...i,
                qty: Math.max(0, action.qty),
                lastMove: new Date().toISOString().slice(0, 10),
              }
            : i,
        ),
      };
    }
    case 'stock/add': {
      return {
        ...state,
        stock: [
          {
            ...action.item,
            id: `new_${Math.random().toString(36).slice(2, 7)}`,
            lastMove: new Date().toISOString().slice(0, 10),
          },
          ...state.stock,
        ],
      };
    }
    case 'stock/remove': {
      return { ...state, stock: state.stock.filter((i) => i.id !== action.id) };
    }
    case 'maint/addHistory': {
      return {
        ...state,
        maintHistory: [
          { ...action.item, id: `h${Math.random().toString(36).slice(2, 7)}` },
          ...state.maintHistory,
        ],
      };
    }
    case 'maint/resolve': {
      // mark a planned task as freshly done
      return {
        ...state,
        maintenance: state.maintenance.map((m) =>
          m.id === action.id ? { ...m, lastHs: m.currentHs, status: 'ok' } : m,
        ),
        maintHistory: [
          {
            id: `h${Math.random().toString(36).slice(2, 7)}`,
            date: new Date().toISOString().slice(0, 10),
            equipment: action.equipment || 'Rig-1',
            type: action.task,
            tech: action.tech || '—',
            hours: action.hours || 0,
            notes: action.notes || '',
          },
          ...state.maintHistory,
        ],
      };
    }
    case 'parte/submit': {
      return {
        ...state,
        dailyReports: [
          { ...action.report, id: `d${Math.random().toString(36).slice(2, 7)}` },
          ...state.dailyReports,
        ],
      };
    }
    default:
      return state;
  }
}

function StoreProvider({ children }) {
  const [state, dispatch] = React.useReducer(storeReducer, SEED);
  return <StoreCtx.Provider value={{ state, dispatch }}>{children}</StoreCtx.Provider>;
}
function useStore() {
  return React.useContext(StoreCtx);
}

Object.assign(window, { StoreProvider, useStore });
