/* ProHippo — main app shell */

/* ── Loading Screen ─────────────────────────────────── */
function LoadingScreen() {
  return (
    <div className="auth-loading-page">
      <div className="auth-logo-mark" style={{width:60,height:60,borderRadius:18,background:"var(--p-primary)"}}>
        <svg viewBox="0 0 24 24" fill="none" style={{width:30,height:30}}>
          <path d="M6 4c3 0 3 4 6 4s3-4 6-4v16c-3 0-3-4-6-4s-3 4-6 4V4z" fill="white"/>
        </svg>
      </div>
      <div className="auth-spinner"/>
      <p style={{color:"var(--p-text-3)",fontSize:13,marginTop:8}}>Loading your workspace…</p>
    </div>
  );
}

/* ── Main App ────────────────────────────────────────── */
function App() {
  /*
   * Auth state machine:
   *   loading → unauth | onboard | pin_setup | pin_entry | ready
   *
   *   loading    = checking Firebase auth
   *   unauth     = not logged in → show AuthScreen
   *   onboard    = logged in but no profile → show OnboardingScreen
   *   pin_setup  = profile exists, no PIN set → show PinSetupScreen
   *   pin_entry  = profile+PIN exist, not verified this session → show PinEntryScreen
   *   ready      = fully authenticated → show main app
   */
  const [authStatus,  setAuthStatus]  = React.useState("loading");
  const [currentUser, setCurrentUser] = React.useState(null);
  const [userProfile, setUserProfile] = React.useState(null);

  /* App navigation state */
  const [route,        setRoute]        = React.useState("dashboard");
  const [openAssessee, setOpenAssessee] = React.useState(null);
  const [showParsed,   setShowParsed]   = React.useState(false);
  const [toast,        setToast]        = React.useState(null);

  /* ── Auth listener ──────────────────────────────── */
  React.useEffect(() => {
    const unsub = firebase.auth().onAuthStateChanged(async (user) => {
      if (!user) {
        setAuthStatus("unauth");
        setCurrentUser(null);
        setUserProfile(null);
        return;
      }

      setCurrentUser(user);

      let profile = null;

      /* 1) Try Firestore */
      try {
        const doc = await firebase.firestore().collection("users").doc(user.uid).get();
        if (doc.exists) profile = doc.data();
      } catch (_) { /* Firestore may not be set up yet */ }

      /* 2) Fallback to localStorage */
      if (!profile) {
        try {
          const cached = localStorage.getItem("ph_profile_" + user.uid);
          if (cached) profile = JSON.parse(cached);
        } catch(_) {}
      }

      if (!profile) {
        /* First-time user — no profile at all */
        setAuthStatus("onboard");
        return;
      }

      setUserProfile(profile);

      /* Check PIN state */
      const pinOkThisSession = !!sessionStorage.getItem("ph_pin_ok_" + user.uid);

      if (!profile.pinHash) {
        /* Profile exists but no PIN set yet */
        if (pinOkThisSession) {
          setAuthStatus("ready");
        } else {
          setAuthStatus("pin_setup");
        }
      } else {
        /* PIN exists — require entry once per session */
        if (pinOkThisSession) {
          setAuthStatus("ready");
        } else {
          setAuthStatus("pin_entry");
        }
      }
    });

    return unsub;
  }, []);

  /* ── Toast auto-dismiss ─────────────────────────── */
  React.useEffect(() => {
    if (toast) {
      const t = setTimeout(() => setToast(null), 3500);
      return () => clearTimeout(t);
    }
  }, [toast]);

  /* ── Navigation handlers ────────────────────────── */
  const handleNav = (id) => {
    setRoute(id);
    setOpenAssessee(null);
    setShowParsed(false);
  };

  const handleOpenAssessee  = (a) => setOpenAssessee(a);
  const handleOpenParsed    = ()  => setShowParsed(true);

  const handleSaveAndCreate = () => {
    setShowParsed(false);
    setRoute("hearings");
    setToast({ msg: "Hearing created · Calendar synced · Client notified", icon: "check" });
  };

  const handleSignOut = async () => {
    if (currentUser) sessionStorage.removeItem("ph_pin_ok_" + currentUser.uid);
    await firebase.auth().signOut();
    setRoute("dashboard");
    setOpenAssessee(null);
    setShowParsed(false);
  };

  /* ── Auth gate ──────────────────────────────────── */
  if (authStatus === "loading") return <LoadingScreen/>;

  if (authStatus === "unauth")  return <AuthScreen/>;

  if (authStatus === "onboard") return (
    <OnboardingScreen
      user={currentUser}
      onComplete={(profile) => {
        setUserProfile(profile);
        setAuthStatus("pin_setup");   /* after onboarding → set PIN */
      }}
    />
  );

  if (authStatus === "pin_setup") return (
    <PinSetupScreen
      user={currentUser}
      onComplete={() => setAuthStatus("ready")}
    />
  );

  if (authStatus === "pin_entry") return (
    <PinEntryScreen
      user={currentUser}
      storedPinHash={userProfile?.pinHash}
      onUnlock={() => setAuthStatus("ready")}
      onSignOut={handleSignOut}
    />
  );

  /* ── Main content router ────────────────────────── */
  let content;
  if (showParsed) {
    content = <ParsedNoticeReview onClose={() => setShowParsed(false)} onSaveAndCreate={handleSaveAndCreate}/>;
  } else if (openAssessee) {
    content = <AssesseeProfile assessee={openAssessee} onBack={() => setOpenAssessee(null)} onNav={handleNav}/>;
  } else {
    switch (route) {
      case "dashboard":      content = <Dashboard onNav={handleNav} onOpenParsedNotice={handleOpenParsed}/>; break;
      case "assessees":      content = <Assessees onOpen={handleOpenAssessee}/>; break;
      case "matters":        content = <Matters/>; break;
      case "notices":        content = <Notices onOpenParsed={handleOpenParsed}/>; break;
      case "hearings":       content = <Hearings/>; break;
      case "invoices":       content = <Invoices/>; break;
      case "communications": content = <Communications/>; break;
      case "ai":             content = <AiParser onOpenParsed={handleOpenParsed}/>; break;
      case "reports":        content = <Reports/>; break;
      case "settings":       content = <SettingsPage/>; break;
      default:               content = <Dashboard onNav={handleNav} onOpenParsedNotice={handleOpenParsed}/>;
    }
  }

  return (
    <div className="app">
      <Sidebar
        active={route}
        onNav={handleNav}
        userProfile={userProfile}
        onSignOut={handleSignOut}
      />
      <main className="main">
        {content}
      </main>
      {toast && (
        <div className="toast animate-in">
          <div style={{width:22,height:22,borderRadius:"50%",background:"var(--p-success)",display:"grid",placeItems:"center"}}>
            <Icon name={toast.icon} size={13} stroke={3}/>
          </div>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

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