import { useState, useEffect } from 'react'

const STORAGE_KEY = 'phase2_features'

// All Phase 2 features with their sidebar metadata.
// enabled: true = shown by default (feature is polished)
// enabled: false = hidden by default (still in development)
export const PHASE2_FEATURE_DEFS = [
  { id: 'online-orders', label: 'Online Orders',           route: '/online-orders', enabled: true },
  { id: 'notes',         label: 'Σημειώσεις & Εργασίες',  route: '/notes',         enabled: true },
  { id: 'expenses',      label: 'Έξοδα',                   route: '/expenses',      enabled: true },
  { id: 'contacts',      label: 'Επαφές / Προμηθευτές',    route: '/contacts',      enabled: true },
  { id: 'customers',     label: 'Πελάτες',                  route: '/customers',     enabled: true },
  { id: 'tabs',          label: 'Καρτέλες',                 route: '/tabs',          enabled: true },
  { id: 'waste',         label: 'Αποβλήτα / Φθορές',       route: '/waste',         enabled: true },
  { id: 'kds',           label: 'KDS — Κουζίνα',            route: '/kds',           enabled: true },
  { id: 'schedule',      label: 'Πρόγραμμα Βαρδιών',       route: '/schedule',      enabled: true },
]

function _load() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : {}
  } catch {
    return {}
  }
}

export function isFeatureEnabled(id) {
  const overrides = _load()
  if (id in overrides) return overrides[id]
  const def = PHASE2_FEATURE_DEFS.find(f => f.id === id)
  return def ? def.enabled : true
}

export function setFeatureEnabled(id, value) {
  const overrides = _load()
  overrides[id] = value
  localStorage.setItem(STORAGE_KEY, JSON.stringify(overrides))
  // Notify other components in this tab
  window.dispatchEvent(new Event('phase2features'))
}

export function usePhase2Features() {
  const [, tick] = useState(0)

  useEffect(() => {
    const handler = () => tick(n => n + 1)
    window.addEventListener('phase2features', handler)
    window.addEventListener('storage', handler)
    return () => {
      window.removeEventListener('phase2features', handler)
      window.removeEventListener('storage', handler)
    }
  }, [])

  return PHASE2_FEATURE_DEFS.map(f => ({
    ...f,
    enabled: isFeatureEnabled(f.id),
  }))
}
