/* ============================================================
   My Dream Home — Global State Store (React Context + useReducer)
   ============================================================ */

const DEMO_PRESET = {
  household: 'family',
  lifestage: 'growing',
  priority: 'green-space',
  spaceStyle: 'bright-open',
  communityVibe: 'walkable-family',
};

const initialState = {
  // --- User journey state ---
  currentStep: 0,      // 0..5
  direction: 1,
  demoMode: false,
  demoProgress: 0,
  isDemoPreset: false, // true when answers come from demo preset

  // --- User preferences (from step 2) ---
  preferences: {
    household: null,     // 'single' | 'couple' | 'family' | 'multi-gen'
    lifestage: null,     // 'just-started' | 'growing' | 'nesting' | 'empty-nest'
    priority: null,      // 'green-space' | 'privacy' | 'entertaining' | 'proximity'
    spaceStyle: null,    // 'bright-open' | 'cozy-traditional' | 'modern-minimal' | 'outdoor-focused'
    communityVibe: null, // 'walkable-family' | 'quiet-suburban' | 'vibrant-urban' | 'nature-retreat'
  },

  // --- AI match results ---
  savedHomes: [],       // array of home ids
  comparedHomes: [],    // array of home ids (max 2)
  compareDrawerOpen: false,

  // --- AI life preview ---
  activeScene: 'family-time', // 'morning-light' | 'family-time' | 'evening-outdoors'
  visionSaved: false,
  shared: false,

  // --- Booking / lead capture ---
  selectedAction: null,  // 'advisor' | 'visit' | 'shortlist'
  formData: {
    name: '',
    email: '',
    phone: '',
    preferredTime: '',   // 'morning' | 'afternoon' | 'evening'
    consent: false,
  },
  formErrors: {},
  submitted: false,
};

// ─────────────────────────────────────────
// Matching logic (front-end only, deterministic)
// ─────────────────────────────────────────
const HOME_CATALOG = [
  {
    id: 'home-01',
    name: 'Al Reem Villa Collection',
    tagline: 'Spacious family living with green surroundings',
    type: 'Villa community',
    matchReason: 'Best match',
    highlights: ['Privacy', 'Green space', 'Room to grow'],
    vibeTags: ['walkable-family', 'nature-retreat'],
    priorityFit: ['green-space', 'privacy'],
    householdFit: ['family', 'multi-gen'],
    community: 'Al Reem Gardens',
  },
  {
    id: 'home-02',
    name: 'Nakheel Townhouse Series',
    tagline: 'Modern connected living for active households',
    type: 'Townhouse',
    matchReason: 'Great for entertaining',
    highlights: ['Open plan', 'Community pools', 'Near amenities'],
    vibeTags: ['vibrant-urban', 'walkable-family'],
    priorityFit: ['entertaining', 'proximity'],
    householdFit: ['family', 'couple'],
    community: 'Nakheel Residences',
  },
  {
    id: 'home-03',
    name: 'Jabal Heights Residence',
    tagline: 'Quiet retreat with panoramic views',
    type: 'Detached villa',
    matchReason: 'For those who value privacy',
    highlights: ['Panoramic views', 'Ultimate privacy', 'Nature access'],
    vibeTags: ['nature-retreat', 'quiet-suburban'],
    priorityFit: ['privacy', 'green-space'],
    householdFit: ['multi-gen', 'family'],
    community: 'Jabal Heights',
  },
];

function computeMatches(preferences) {
  const scored = HOME_CATALOG.map(home => {
    let score = 0;
    let reasons = [];

    if (preferences.household && home.householdFit.includes(preferences.household)) {
      score += 25;
      reasons.push('Fits your household size');
    }
    if (preferences.priority && home.priorityFit.includes(preferences.priority)) {
      score += 30;
      reasons.push('Aligns with your top priority');
    }
    if (preferences.communityVibe && home.vibeTags.includes(preferences.communityVibe)) {
      score += 25;
      reasons.push('Matches your community vibe');
    }
    if (preferences.spaceStyle && home.highlights.some(h =>
      (preferences.spaceStyle === 'bright-open' && h.includes('Open')) ||
      (preferences.spaceStyle === 'outdoor-focused' && h.includes('outdoor')) ||
      true
    )) {
      score += 10;
    }
    // Base score so every option shows a match
    score += 10;

    return { ...home, score, reasons };
  });

  scored.sort((a, b) => b.score - a.score);
  return scored;
}

function computeMatchPercentage(score) {
  // Normalize to 60-98% range for realism
  return Math.min(98, Math.max(60, Math.round(score * 1.1 + 55)));
}

// ─────────────────────────────────────────
// Reducer
// ─────────────────────────────────────────
function reducer(state, action) {
  switch (action.type) {
    case 'SET_STEP':
      return { ...state, currentStep: action.step, direction: action.step > state.currentStep ? 1 : -1, demoProgress: 0 };

    case 'NEXT_STEP':
      if (state.currentStep >= 5) return state;
      return { ...state, currentStep: state.currentStep + 1, direction: 1, demoProgress: 0 };

    case 'PREV_STEP':
      if (state.currentStep <= 0) return state;
      return { ...state, currentStep: state.currentStep - 1, direction: -1, demoProgress: 0 };

    case 'SET_DEMO_MODE':
      return { ...state, demoMode: action.enabled };

    case 'SET_DEMO_PROGRESS':
      return { ...state, demoProgress: action.progress };

    case 'APPLY_DEMO_PRESET':
      return {
        ...state,
        preferences: { ...DEMO_PRESET },
        isDemoPreset: true,
      };

    case 'SET_PREFERENCE':
      return {
        ...state,
        preferences: { ...state.preferences, [action.key]: action.value },
        isDemoPreset: false,
      };

    case 'TOGGLE_SAVE_HOME': {
      const exists = state.savedHomes.includes(action.homeId);
      return {
        ...state,
        savedHomes: exists
          ? state.savedHomes.filter(id => id !== action.homeId)
          : [...state.savedHomes, action.homeId],
      };
    }

    case 'TOGGLE_COMPARE_HOME': {
      const exists = state.comparedHomes.includes(action.homeId);
      if (exists) {
        return { ...state, comparedHomes: state.comparedHomes.filter(id => id !== action.homeId) };
      }
      if (state.comparedHomes.length >= 2) {
        return { ...state, comparedHomes: [state.comparedHomes[1], action.homeId] };
      }
      return { ...state, comparedHomes: [...state.comparedHomes, action.homeId] };
    }

    case 'TOGGLE_COMPARE_DRAWER':
      return { ...state, compareDrawerOpen: !state.compareDrawerOpen };

    case 'SET_ACTIVE_SCENE':
      return { ...state, activeScene: action.scene };

    case 'SAVE_VISION':
      return { ...state, visionSaved: true };

    case 'SHARE_VISION':
      return { ...state, shared: true };

    case 'SET_SELECTED_ACTION':
      return { ...state, selectedAction: action.action };

    case 'SET_FORM_DATA':
      return {
        ...state,
        formData: { ...state.formData, ...action.data },
        formErrors: {},
      };

    case 'SET_FORM_ERRORS':
      return { ...state, formErrors: action.errors };

    case 'SUBMIT_FORM':
      return { ...state, submitted: true, formErrors: {} };

    case 'RESET_ALL':
      return {
        ...initialState,
        currentStep: 0,
      };

    default:
      return state;
  }
}

// ─────────────────────────────────────────
// Context
// ─────────────────────────────────────────
const AppContext = React.createContext(null);

function AppProvider({ children }) {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  const value = React.useMemo(() => ({
    state,
    dispatch,
    computeMatches: () => computeMatches(state.preferences),
    computeMatchPercentage,
    DEMO_PRESET,
  }), [state]);

  return React.createElement(AppContext.Provider, { value }, children);
}

function useApp() {
  const ctx = React.useContext(AppContext);
  if (!ctx) throw new Error('useApp must be used within AppProvider');
  return ctx;
}

// Expose
window.AppContextProvider = AppProvider;
window.useApp = useApp;
window.computeMatches = computeMatches;
window.HOME_CATALOG = HOME_CATALOG;
