/* ============================================================
   app.jsx — 루트 · 라우팅 · 앱 셸 (모바일 우선)
   ============================================================ */
const { useState: aS, useEffect: aE } = React;

window.askClaude = async function (prompt) {
  const out = await window.claude.complete(prompt);
  return (out || "").trim();
};

const NAV = [
  { r: "home",   ico: "today",   label: "오늘" },
  { r: "saju",   ico: "saju",    label: "사주" },
  { r: "compat", ico: "gunghap", label: "궁합" },
  { r: "analysis", ico: "saju",  label: "심층분석" },
  { r: "chat",   ico: "chat",    label: "상담" },
  { r: "diary",  ico: "diary",   label: "다이어리" },
];

function LoginModal({ onClose, onGoogle, onKakao }) {
  return (
    <div style={{position:"fixed", inset:0, zIndex:100, display:"grid", placeItems:"center", padding:20, background:"rgba(20,16,34,.48)", backdropFilter:"blur(8px)"}}>
      <div className="card" style={{width:"100%", maxWidth:360, padding:24, textAlign:"center", boxShadow:"var(--shadow)", borderRadius:"var(--r-xl)"}}>
        <div className="brand" style={{justifyContent:"center", marginBottom:18}}>
          <div className="moon"></div>
          <div className="wordmark"><b>월하</b><span>月下 · since fate</span></div>
        </div>
        <p style={{fontSize:14, color:"var(--text-dim)", lineHeight:1.6, marginBottom:20}}>내 인연의 흐름을 읽어드릴게요</p>
        <div style={{display:"flex", flexDirection:"column", gap:10}}>
          <button className="btn" style={{width:"100%", background:"#fff", color:"var(--text)", border:"1px solid var(--line-2)", boxShadow:"none"}} onClick={onGoogle}>
            G&nbsp;&nbsp;구글로 계속하기
          </button>
          <button className="btn" style={{width:"100%", background:"#FEE500", color:"#000", boxShadow:"none"}} onClick={onKakao}>
            💬&nbsp;&nbsp;카카오로 계속하기
          </button>
        </div>
        <button style={{marginTop:18, border:"none", background:"transparent", color:"var(--text-dim)", fontSize:13, fontWeight:700, cursor:"pointer"}} onClick={onClose}>
          로그인 없이 둘러보기
        </button>
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = window.useStore("wolha_route", "home");
  const [profile, setProfile] = window.useStore("wolha_profile", null);
  const [partner, setPartner] = window.useStore("wolha_partner", null);
  const [diary, setDiary] = aS([]);
  const [user, setUser] = aS(() => {
    try { return JSON.parse(localStorage.getItem("wolha_user")) || null; }
    catch { return null; }
  });
  const [showLogin, setShowLogin] = aS(false);
  const [showUserMenu, setShowUserMenu] = aS(false);
  const [authConfig, setAuthConfig] = aS(null);
  const [sessionPersona, setSessionPersona] = aS(null);
  const [selectedDiaryItem, setSelectedDiaryItem] = aS(null);
  const userMenuRef = React.useRef(null);
  window.appUser = user;

  aE(() => { window.scrollTo(0, 0); }, [route]);
  aE(() => {
    if (user) localStorage.setItem("wolha_user", JSON.stringify(user));
    else localStorage.removeItem("wolha_user");
  }, [user]);
  aE(() => { localStorage.removeItem("wolha_diary"); }, []);
  aE(() => {
    if (!user?.email) { setDiary([]); return; }
    fetch(`https://sajuproject-3uv2.onrender.com/api/diary/${encodeURIComponent(user.email)}`)
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) setDiary(data.map(d => d.entry));
      })
      .catch(() => setDiary([]));
  }, [user?.email]);
  aE(() => {
    fetch("https://sajuproject-3uv2.onrender.com/api/config")
      .then((res) => res.json())
      .then((config) => setAuthConfig(config))
      .catch(() => setAuthConfig({ googleClientId: "", kakaoAppKey: "" }));
  }, []);
  aE(() => {
    if (authConfig?.kakaoAppKey && window.Kakao && !Kakao.isInitialized()) {
      Kakao.init(authConfig.kakaoAppKey);
    }
  }, [authConfig?.kakaoAppKey]);
  aE(() => {
    function closeUserMenu(e) {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target)) setShowUserMenu(false);
    }
    document.addEventListener("mousedown", closeUserMenu);
    return () => document.removeEventListener("mousedown", closeUserMenu);
  }, []);

  function loginWithGoogle() {
    if (!authConfig?.googleClientId) return;
    google.accounts.oauth2.initCodeClient({
      client_id: authConfig.googleClientId,
      scope: "email profile",
      ux_mode: "popup",
      callback: (res) => {
        fetch("https://sajuproject-3uv2.onrender.com/api/auth/google", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ code: res.code })
        }).then(r => r.json()).then(data => {
          if (data.user) {
            setUser(data.user);
            setShowLogin(false);
          }
        });
      }
    }).requestCode();
  }

  function loginWithKakao() {
    if (!authConfig?.kakaoAppKey || !window.Kakao) return;
    Kakao.Auth.login({
      success: (authObj) => {
        Kakao.API.request({
          url: "/v2/user/me",
          success: (res) => {
            const kakao = res.kakao_account;
            setUser({
              name: kakao.profile?.nickname || "카카오 사용자",
              email: kakao.email || "",
              picture: kakao.profile?.profile_image_url || "",
              provider: "kakao"
            });
            fetch("https://sajuproject-3uv2.onrender.com/api/auth/save", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ email: kakao.email, name: kakao.profile?.nickname, picture: kakao.profile?.profile_image_url, provider: "kakao" })
            });
            setShowLogin(false);
          }
        });
      }
    });
  }

  function nav(r, data = null) {
    if (["saju", "compat", "analysis"].includes(r) && !user) {
      setShowLogin(true);
      return;
    }
    setSelectedDiaryItem(data || null);
    if (data?.kind === "compat" && data.savedPartner) setPartner(data.savedPartner);
    setRoute(r);
  }

  function addDiary(entry) {
    if (!window.appUser) return;
    setDiary((d) => {
      const i = d.findIndex((x) => x.id === entry.id);
      if (i >= 0) { const c = [...d]; c[i] = { ...c[i], ...entry }; return c; }
      return [entry, ...d].slice(0, 40);
    });
    if (window.appUser?.email) {
      fetch("https://sajuproject-3uv2.onrender.com/api/diary", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: window.appUser.email, entry })
      });
    }
  }
  function removeDiary(id) { setDiary((d) => d.filter((x) => x.id !== id)); }

  const screen = (() => {
    switch (route) {
      case "saju":   return <window.SajuScreen nav={nav} profile={profile} setProfile={setProfile} addDiary={addDiary} />;
      case "compat": return <window.CompatScreen nav={nav} profile={profile} setProfile={setProfile} partner={partner} setPartner={setPartner} addDiary={addDiary} diaryItem={selectedDiaryItem?.kind === "compat" ? selectedDiaryItem : null} />;
      case "analysis": return <window.AnalysisScreen nav={nav} profile={profile} addDiary={addDiary} diaryItem={selectedDiaryItem?.kind === "analysis" ? { ...selectedDiaryItem, result: selectedDiaryItem.fullResult || selectedDiaryItem.result } : selectedDiaryItem} />;
      case "chat":   return <window.ChatScreen nav={nav} profile={profile} partner={partner} addDiary={addDiary} sessionPersona={sessionPersona} setSessionPersona={setSessionPersona} />;
      case "diary":  return <window.DiaryScreen nav={nav} diary={diary} removeDiary={removeDiary} />;
      default:       return <window.Home nav={nav} profile={profile} diary={diary} />;
    }
  })();

  return (
    <div className="app">
      <header className="appbar">
        <div className="brand">
          <div className="moon"></div>
          <div className="wordmark"><b>월하</b><span>月下 · since fate</span></div>
        </div>
        <div style={{position:"relative"}} ref={userMenuRef}>
          {user ? (
            <>
              <div className="avatar" onClick={() => setShowUserMenu((v) => !v)}>
                {user.picture ? <img src={user.picture} alt={user.name || "login user"} referrerPolicy="no-referrer" style={{width:"100%", height:"100%", borderRadius:"50%", objectFit:"cover"}} /> : user.name?.[0]}
              </div>
              {showUserMenu && (
                <div className="card" style={{position:"absolute", right:0, top:44, zIndex:50, width:220, padding:14}}>
                  <div style={{display:"flex", gap:10, alignItems:"center", marginBottom:12}}>
                    <div className="avatar" style={{width:38, height:38}}>
                      {user.picture ? <img src={user.picture} alt={user.name || "login user"} referrerPolicy="no-referrer" style={{width:"100%", height:"100%", borderRadius:"50%", objectFit:"cover"}} /> : user.name?.[0]}
                    </div>
                    <div style={{minWidth:0, flex:1}}>
                      <div style={{fontSize:12, fontWeight:800, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis", wordBreak:"break-all"}}>{user.name || "사용자"}</div>
                      <div style={{fontSize:12, color:"var(--text-dim)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis", wordBreak:"break-all"}}>{user.email || user.provider}</div>
                    </div>
                  </div>
                  <div style={{display:"flex", flexDirection:"column", gap:8}}>
                    <button className="btn ghost" style={{width:"100%", padding:"11px 14px"}} onClick={() => { nav("saju"); setShowUserMenu(false); }}>사주 설정</button>
                    <button className="btn ghost" style={{width:"100%", padding:"11px 14px"}} onClick={() => { setUser(null); setDiary([]); setShowUserMenu(false); }}>로그아웃</button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="avatar" onClick={() => setShowLogin(true)}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="1.8"
                strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="8" r="4"/>
                <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
              </svg>
            </div>
          )}
        </div>
      </header>

      <main className="main">{screen}</main>
      {showLogin && <LoginModal onClose={()=>setShowLogin(false)} onGoogle={loginWithGoogle} onKakao={loginWithKakao} />}

      <nav className="tabbar">
        {NAV.map((n) => (
          <button key={n.r} className={"tab " + (route === n.r ? "active" : "")} onClick={() => {
            if (["saju", "compat", "analysis"].includes(n.r) && !user) {
              setShowLogin(true);
              return;
            }
            nav(n.r);
          }}>
            <window.Icon name={n.ico} /> {n.label}
          </button>
        ))}
      </nav>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
