// Green Voice — App router (main container)
// 5 tabs: 홈 / 골프장 / 랭킹 / 라운드 / 클럽하우스
// Modal types:
//   - course          : 코스 상세
//   - verify          : 방문 인증 플로우
//   - review          : 리뷰 작성 플로우
//   - booking         : 일반 예약 폼 (누구나)
//   - membership      : Green Voice Premium 소개/가입
//   - concierge       : 프리미엄 전담 컨시어지 채팅 (연부킹)

function GVApp() {
  const persistedState = React.useMemo(() => {
    try {
      return JSON.parse(localStorage.getItem('gv-state') || 'null') || {};
    } catch (e) { return {}; }
  }, []);

  const validTabs = ['home', 'course', 'ranking', 'round', 'clubhouse'];
  const initialTab = validTabs.includes(persistedState.tab) ? persistedState.tab : 'home';
  const [tab, setTab] = React.useState(initialTab);
  const [modalStack, setModalStack] = React.useState([]);
  const [isPremium, setIsPremium] = React.useState(!!persistedState.isPremium);

  React.useEffect(() => {
    localStorage.setItem('gv-state', JSON.stringify({ tab, isPremium }));
  }, [tab, isPremium]);

  // Sync GV_USER for downstream reads
  React.useEffect(() => {
    if (window.GV_USER) window.GV_USER.isPremium = isPremium;
  }, [isPremium]);

  const nav = {
    isPremium,
    setPremium: (v) => setIsPremium(v),

    go: (t) => { setTab(t); setModalStack([]); },
    openCourse: (id) => setModalStack([...modalStack, { type: 'course', id }]),

    startVerify: () => setModalStack([...modalStack, { type: 'verify', id: modalStack[modalStack.length - 1]?.id }]),
    startReview: () => {
      const last = modalStack[modalStack.length - 1];
      const rest = modalStack.slice(0, -1);
      setModalStack([...rest, { type: 'review', id: last?.id }]);
    },

    // 일반 예약 (누구나)
    startBooking: (id) => setModalStack([...modalStack, { type: 'booking', id: id || modalStack[modalStack.length - 1]?.id }]),

    // 연부킹: 프리미엄 회원이면 컨시어지 채팅, 아니면 멤버십 가입 유도
    startAnnualBooking: (id) => {
      const cid = id || modalStack[modalStack.length - 1]?.id;
      if (isPremium) {
        setModalStack([...modalStack, { type: 'concierge', id: cid }]);
      } else {
        setModalStack([...modalStack, { type: 'membership', id: cid, intent: 'annual' }]);
      }
    },

    // 명시적으로 멤버십 화면 열기 (클럽하우스 등)
    startMembership: () => setModalStack([...modalStack, { type: 'membership', id: null }]),
    // 명시적으로 컨시어지 채팅 열기 (프리미엄 회원)
    startConcierge: (id) => setModalStack([...modalStack, { type: 'concierge', id: id || null }]),

    back: () => setModalStack(modalStack.slice(0, -1)),
    close: () => setModalStack([]),
  };

  const currentModal = modalStack[modalStack.length - 1];

  // Top bar per tab
  const topBar = () => {
    if (tab === 'home') return <GVTopBar title="GREEN_VOICE_LOGO" />;
    if (tab === 'course') return <GVTopBar title="골프장" actions={['tune', 'notifications']} />;
    if (tab === 'ranking') return <GVTopBar title="랭킹" actions={['history', 'help']} />;
    if (tab === 'round') return null; // round has custom header
    if (tab === 'clubhouse') return null; // clubhouse has custom centered header
    return null;
  };

  const handleSubscribe = () => {
    setIsPremium(true);
    // 가입 후 컨시어지 채팅으로 전환 (현재 membership modal이 top이라 pop+push)
    const cid = currentModal?.id;
    setModalStack([...modalStack.slice(0, -1), { type: 'concierge', id: cid }]);
  };

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      background: GV.color.surface,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      <ScrollbarStyle />

      {/* Main app body */}
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        visibility: currentModal ? 'hidden' : 'visible',
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 68,
      }}>
        {topBar()}
        <div className="gv-scroll" style={{ flex: 1, overflowY: 'auto', position: 'relative' }}>
          {tab === 'home' && <GVHomeScreen nav={nav} />}
          {tab === 'course' && <GVCourseScreen nav={nav} />}
          {tab === 'ranking' && <GVRankingScreen nav={nav} />}
          {tab === 'round' && <GVRoundScreen nav={nav} />}
          {tab === 'clubhouse' && <GVClubhouseScreen nav={nav} />}
        </div>
      </div>

      {/* Bottom nav — hidden during modals */}
      {!currentModal && (
        <div style={{
          position: 'absolute',
          bottom: 0,
          left: 0,
          right: 0,
          zIndex: 15,
        }}>
          <GVBottomNav tab={tab} onChange={setTab} />
        </div>
      )}

      {/* Modals — full screen overlays */}
      {currentModal && (
        <div style={{
          position: 'absolute',
          inset: 0,
          background: GV.color.surface,
          zIndex: 40,
          overflow: 'hidden',
          animation: 'gv-slide-up 0.3s ease-out',
        }}>
          <div
            className={currentModal.type === 'concierge' ? '' : 'gv-scroll'}
            style={{
              height: '100%',
              overflowY: currentModal.type === 'concierge' ? 'hidden' : 'auto',
              display: currentModal.type === 'concierge' ? 'flex' : 'block',
              flexDirection: 'column',
            }}
          >
            {currentModal.type === 'course' && <GVCourseDetail courseId={currentModal.id} nav={nav} />}
            {currentModal.type === 'verify' && <GVVerifyFlow initialCourseId={currentModal.id} nav={nav} />}
            {currentModal.type === 'review' && <GVReviewFlow initialCourseId={currentModal.id} nav={nav} />}
            {currentModal.type === 'booking' && <GVBookingFlow initialCourseId={currentModal.id} nav={nav} />}
            {currentModal.type === 'membership' && <GVMembershipFlow nav={nav} onSubscribe={handleSubscribe} />}
            {currentModal.type === 'concierge' && <GVConciergeFlow initialCourseId={currentModal.id} nav={nav} />}
          </div>
        </div>
      )}

      <style>{`
        @keyframes gv-slide-up {
          from { transform: translateY(20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { GVApp });
