// src/reducers/commonReducer.js

import { types } from "../actions/actionTypes";
import { LOG_MENU } from "../utils/Config";

const initialState = {
  appStatus: {
    showLoadingPanel: { show: true, type: "launching" },
    isLoading: false,
    webOSVersion: "", //"5.0", "9.0" ...
    serverHOST: "", //"US.nextlgsdp.com",
    mbr_no: "", //X-User-Number : "US2401051532595"
    deviceId: "", //d87cedca-84e7-c05e-613d-39739bb7941f
    cursorVisible: false,
    loginUserData: {},
    toast: false,
    toastText: null,
    captionEnable: false,
    isInternetConnected: true,
  },
  broadcast: {},
  httpHeader: null,
  isGnbOpened: false,
  popup: {
    popupVisible: false,
    activePopup: null,
    secondaryPopup: null,
    secondaryPopupVisible: false,
    secondaryText: null,
    secondaryData: {},
    text: null,
    data: {},
    optionalTermsConfirmSelected: false,
  },
  termsFlag: null,
  termsLoading: false, // 25.06.16 추가
  introTermsAgree: undefined, // Y, N
  checkoutTermsAgree: undefined,
  useLog: true,
  useMockup: true,
  recents: [],
  phoneNumbers: [
    {
      number: "9999999999",
      regDt: "",
    },
  ],
  domain: "com.lgshop.app",
  _secretKey: "fy7BTKuM9eeTQqEC9sF3Iw5qG43Aaip",
  _lunaDB: "luna://com.palm.db",
  __alarmKind: ":1",
  // Language Code
  _languageKind: ":9",
  _languageKeyId: "languageCode",
  testRes: "",
  check: "",

  menu: {
    entryMenu: "App",
    nowMenu: "",
    menuMovSno: 0,
  },

  systemNotice: false,
  systemTermination: null,

  // test
  spotlightId: null,

  deepLinkInfo: {
    contentTarget: "",
    isDeepLink: false,
  },

  secondLayerInfo: {},
  macAddress: { wifi: "", wired: "", p2p: "" },
  connectionFailed: false,

  deviceRegistered: false,

  termsAgreementStatus: {
    MST00401: false, // 개인정보처리방침 (필수)
    MST00402: false, // 이용약관 (필수)
    MST00405: false, // 선택약관 (선택)
  },

  // 선택약관 팝업 상태 관리 (TV 환경 최적화)
  optionalTermsPopupFlow: {
    popupShown: false, // 팝업 표시 여부
    userDecision: null, // 'agreed' | 'declined' | null
    agreedInSession: false, // 세션 내 동의 여부 (로컬 상태 기반)
  },
};

export const commonReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.SET_DEVICE_REGISTERED:
      return {
        ...state,
        deviceRegistered: action.payload,
      };
    case types.CHANGE_APP_STATUS: {
      let isUpdated = false;

      for (let i in action.payload) {
        if (typeof action.payload[i] === "object") {
          if (
            JSON.stringify(action.payload[i]) !==
            JSON.stringify(state.appStatus[i])
          ) {
            isUpdated = true;

            break;
          }
        } else if (state.appStatus[i] !== action.payload[i]) {
          isUpdated = true;

          break;
        }
      }

      if (isUpdated) {
        return {
          ...state,
          appStatus: { ...state.appStatus, ...action.payload },
        };
      }
      return state;
    }
    case types.SEND_BROADCAST: {
      return {
        ...state,
        broadcast: action.payload,
      };
    }
    case types.GET_HTTP_HEADER:
      return {
        ...state,
        httpHeader: action.payload,
      };

    case types.GET_LOGIN_USER_DATA: {
      return {
        ...state,
        appStatus: {
          ...state.appStatus,
          loginUserData: action.payload,
        },
      };
    }
    case types.GNB_OPENED:
      return {
        ...state,
        isGnbOpened: action.payload,
      };
    case types.SET_SHOW_POPUP:
      return {
        ...state,
        popup: {
          ...state.popup,
          popupVisible: true,
          ...action.payload,
        },
      };
    case types.SET_SHOW_SECONDARY_POPUP:
      return {
        ...state,
        popup: {
          ...state.popup,
          secondaryPopupVisible: true,
          secondaryPopup: action.payload.activePopup,
          secondaryText: action.payload.secondaryText,
          secondaryData: {
            ...state.popup.secondaryData,
            ...action.payload.secondaryData,
          },
        },
      };
    case types.SET_HIDE_POPUP:
      return {
        ...state,
        popup: {
          popupVisible: false,
          activePopup: null,
          secondaryPopupVisible: false,
          secondaryPopup: null,
        },
      };
    case types.SET_HIDE_SECONDARY_POPUP:
      return {
        ...state,
        popup: {
          ...state.popup,
          secondaryPopupVisible: false,
          secondaryPopup: null,
        },
      };
    case types.SHOW_OPTIONAL_TERMS_CONFIRM_POPUP:
      return {
        ...state,
        popup: {
          ...state.popup,
          popupVisible: true,
          activePopup: "optionalTermsConfirmPopup",
        },
      };
    case types.HIDE_OPTIONAL_TERMS_CONFIRM_POPUP:
      return {
        ...state,
        popup: {
          ...state.popup,
          popupVisible: false,
          activePopup: null,
          optionalTermsConfirmSelected: false,
        },
      };
    case types.TOGGLE_OPTIONAL_TERMS_CONFIRM:
      return {
        ...state,
        popup: {
          ...state.popup,
          optionalTermsConfirmSelected: action.payload,
        },
      };
    case types.SET_EXIT_APP:
      return state;

    // 25.06.16 추가

    case types.GET_TERMS_AGREE_YN_START: {
      return {
        ...state,
        termsLoading: true,
      };
    }

    case types.GET_TERMS_AGREE_YN_SUCCESS: {
      const {
        privacyTerms,
        serviceTerms,
        purchaseTerms,
        paymentTerms,
        optionalTerms,
      } = action.payload;

      const introTermsAgree = privacyTerms === "Y" && serviceTerms === "Y";
      const checkoutTermsAgree = purchaseTerms === "Y" && paymentTerms === "Y";
      const optionalTermsAgree = optionalTerms == "Y";

      return {
        ...state,
        termsLoading: false,
        termsFlag: {
          ...action.payload,
        },
        introTermsAgree,
        checkoutTermsAgree,
        optionalTermsAgree,
      };
    }

    case types.GET_TERMS_AGREE_YN_FAILURE: {
      return {
        ...state,
        termsLoading: false,
      };
    }

    case types.GET_HOME_TERMS: {
      const newTermsStatus = { ...state.termsAgreementStatus };
      if (action.payload?.data?.terms) {
        action.payload.data.terms.forEach((term) => {
          if (
            Object.prototype.hasOwnProperty.call(newTermsStatus, term.trmsTpCd)
          ) {
            newTermsStatus[term.trmsTpCd] = term.trmsAgrFlag === "Y";
          }
        });
      }
      return {
        ...state,
        termsAgreementStatus: newTermsStatus,
        termsLoading: false,
      };
    }

    case types.SET_MYPAGE_TERMS_AGREE_SUCCESS: {
      const newTermsStatus = { ...state.termsAgreementStatus };
      // action payload에 담겨온 동의한 약관 코드 리스트를 기반으로 상태 업데이트
      if (action.payload?.agreedTermCodes) {
        action.payload.agreedTermCodes.forEach((termCode) => {
          if (Object.prototype.hasOwnProperty.call(newTermsStatus, termCode)) {
            newTermsStatus[termCode] = true;
          }
        });
      }
      return {
        ...state,
        termsLoading: false,
        termsAgreementStatus: newTermsStatus,
      };
    }
    case types.SET_MYPAGE_TERMS_AGREE_FAIL:
      return {
        ...state,
        termsLoading: false,
      };
    case types.REGISTER_DEVICE: {
      if (action.payload && action.payload.dvcIndex) {
        return {
          ...state,
          termsFlag: {
            ...state.termsFlag,
            privacyTerms: "Y",
            serviceTerms: "Y",
          },
          introTermsAgree: true,
          termsAgreementStatus: {
            ...state.termsAgreementStatus,
            MST00401: true,
            MST00402: true,
          },
        };
      } else {
        return state;
      }
    }

    case "loadingComplete": {
      return {
        ...state,
        loadingComplete: action.payload,
      };
    }

    case types.SET_GNB_MENU: {
      return {
        ...state,
        menu: {
          ...state.menu,
          entryMenu: state.menu.nowMenu,
          nowMenu: action.payload,
          menuMovSno: state.menu.menuMovSno + 1,
        },
      };
    }

    case types.SET_FOCUS: {
      return {
        ...state,
        spotlightId: action.payload,
      };
    }

    case types.SET_SYSTEM_NOTICE: {
      return {
        ...state,
        systemNotice: true,
      };
    }

    case types.SET_SYSTEM_TERMINATION: {
      return {
        ...state,
        systemTermination: action.payload,
      };
    }

    case types.SET_DEEP_LINK: {
      return {
        ...state,
        deepLinkInfo: action.payload,
      };
    }

    case types.SET_SECOND_LAYER_INFO: {
      return {
        ...state,
        secondLayerInfo: action.payload,
      };
    }
    case types.GET_DEVICE_MACADDRESS: {
      return {
        ...state,
        macAddress: {
          wifi: action.payload.wifiInfo.macAddress,
          wired: action.payload.wiredInfo.macAddress,
          p2p: action.payload.p2pInfo.macAddress,
        },
      };
    }

    // 선택약관 팝업 상태 관리 액션들
    case types.SET_OPTIONAL_TERMS_POPUP_SHOWN: {
      return {
        ...state,
        optionalTermsPopupFlow: {
          ...state.optionalTermsPopupFlow,
          popupShown: action.payload,
        },
      };
    }

    case types.SET_OPTIONAL_TERMS_USER_DECISION: {
      return {
        ...state,
        optionalTermsPopupFlow: {
          ...state.optionalTermsPopupFlow,
          userDecision: action.payload,
          agreedInSession: action.payload === "agreed",
        },
      };
    }

    case types.RESET_OPTIONAL_TERMS_SESSION: {
      return {
        ...state,
        optionalTermsPopupFlow: {
          popupShown: false,
          userDecision: null,
          agreedInSession: false,
        },
      };
    }

    // 선택약관 직접 상태 업데이트 케이스들 (API 호출 없이 즉시 반영)
    case types.UPDATE_OPTIONAL_TERMS_AGREE_DIRECT: {
      return {
        ...state,
        optionalTermsAgree: action.payload, // 직접 업데이트 (API 호출 없이)
      };
    }

    case types.UPDATE_TERMS_AGREEMENT_STATUS_DIRECT: {
      return {
        ...state,
        termsAgreementStatus: {
          ...state.termsAgreementStatus,
          ...action.payload, // { MST00405: true/false }
        },
      };
    }

    default:
      return state;
  }
};

export default commonReducer;
