// app.jsx — DebtLift mobile app shell (PRODUCTION)
//
// Auth flow: signed-out → SignInScreen → (OTP) → unlocked → Home
// All data loaded from /api/me/* on sign-in.

const { useState, useMemo, useEffect } = React;

// ─── PRODUCTION FRAME ────────────────────────────────────────
// On mobile or in installed PWA: fullscreen.
// On desktop browser: phone-shaped column, centered, subtle shadow.
function MobileFrame({ children, theme }) {
  return (
    <div style={{
      width: '100%', minHeight: '100dvh',
      display: 'flex', alignItems: 'stretch', justifyContent: 'center',
      background: theme.canvas,
    }}>
      <div style={{
        width: '100%', maxWidth: 460, minHeight: '100dvh',
        background: theme.canvas, position: 'relative',
        boxShadow: 'var(--dl-frame-shadow, none)',
        overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        {children}
      </div>
    </div>
  );
}

// ─── BOTTOM TABS ─────────────────────────────────────────────
function BottomTabs({ tab, setTab, theme }) {
  const items = [
    { id: 'home',     label: 'Home',     icon: 'home' },
    { id: 'activity', label: 'Activity', icon: 'pulse' },
    { id: 'pay',      label: 'Pay',      icon: 'pay' },
    { id: 'docs',     label: 'Vault',    icon: 'doc' },
    { id: 'profile',  label: 'Account',  icon: 'user' },
  ];
  return (
    <div style={{
      position: 'sticky', bottom: 0, left: 0, right: 0,
      paddingBottom: 'max(env(safe-area-inset-bottom), 16px)', paddingTop: 8,
      background: 'rgba(245,240,230,0.92)',
      backdropFilter: 'blur(18px) saturate(180%)',
      WebkitBackdropFilter: 'blur(18px) saturate(180%)',
      borderTop: `1px solid ${theme.rule}`,
      zIndex: 30,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '0 8px' }}>
        {items.map(it => {
          const active = tab === it.id;
          return (
            <button key={it.id} onClick={() => setTab(it.id)} style={{
              flex: 1, padding: '6px 4px 2px',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
              color: active ? theme.ink : theme.inkMute,
            }}>
              <Icon name={it.icon} size={22} color={active ? theme.ink : theme.inkMute} strokeWidth={active ? 1.8 : 1.5}/>
              <span style={{ fontSize: 10.5, fontWeight: active ? 600 : 500, letterSpacing: 0.2 }}>{it.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─── DATA LOADER ─────────────────────────────────────────────
// Fetches all client data and populates window.DL_DATA (which the screens read).
function useClientStore(authed) {
  const [loaded, setLoaded] = useState(false);
  const [error, setError]   = useState(null);

  const reload = React.useCallback(async () => {
    if (!authed) return;
    setLoaded(false); setError(null);
    try {
      const [me, lenders, activity, payments, documents] = await Promise.all([
        api.client.me(),
        api.client.lenders(),
        api.client.activity(),
        api.client.payments(),
        api.client.documents(),
      ]);
      Object.assign(window.DL_DATA, me, {
        lenders: lenders.lenders,
        activity: activity.activity,
        payments: payments.payments,
        files: documents.files,
        documents: documents.documents,
      });
      setLoaded(true);
    } catch (e) {
      setError(e);
      setLoaded(true); // unblock UI so error can show
    }
  }, [authed]);

  useEffect(() => { reload(); }, [reload]);
  return { loaded, error, reload };
}

// ─── DEBT LIFT APP ───────────────────────────────────────────
function DLApp({ theme, serif }) {
  const auth = useAuth();
  const store = useClientStore(auth.authed);

  // Initial tab from ?tab= (manifest shortcuts)
  const initialTab = useMemo(() => {
    try {
      const p = new URLSearchParams(window.location.search).get('tab');
      if (p && ['home','activity','pay','docs','profile'].includes(p)) return p;
    } catch {}
    return 'home';
  }, []);
  const [tab, setTab] = useState(initialTab);
  const [lender, setLender] = useState(null);

  // ─── Signed out: show sign-in screen ───────────────────────
  if (!auth.authed) {
    return (
      <MobileFrame theme={theme}>
        <SignInScreen
          theme={theme}
          onLogin={auth.signIn}
          onVerifyOtp={auth.verifyOtp}
          onForgotPassword={async (email) => api.requestReset(email)}
        />
      </MobileFrame>
    );
  }

  // ─── Loading data ──────────────────────────────────────────
  if (!store.loaded) {
    return (
      <MobileFrame theme={theme}>
        <LoadingScreen theme={theme}/>
      </MobileFrame>
    );
  }

  // ─── Data load failed ──────────────────────────────────────
  if (store.error) {
    return (
      <MobileFrame theme={theme}>
        <ErrorScreen theme={theme} error={store.error} onRetry={store.reload} onSignOut={auth.signOut}/>
      </MobileFrame>
    );
  }

  let screen;
  if (tab === 'home') screen = (
    <HomeScreen
      theme={theme} serif={serif}
      onTab={setTab}
      onLender={setLender}
      onPay={() => setTab('pay')}
      onMsg={() => setTab('profile')}
      onProfile={() => setTab('profile')}
      onActivity={() => setTab('activity')}
      onDocs={() => setTab('docs')}
    />
  );
  else if (tab === 'activity') screen = <ActivityScreen theme={theme}/>;
  else if (tab === 'pay')      screen = <PayScreen theme={theme} serif={serif}/>;
  else if (tab === 'docs')     screen = <DocsScreen theme={theme}/>;
  else if (tab === 'profile')  screen = <ProfileScreen theme={theme} onSignOut={auth.signOut} onRefresh={store.reload}/>;

  return (
    <MobileFrame theme={theme}>
      <div style={{ flex: 1, minHeight: 0, position: 'relative', display: 'flex', flexDirection: 'column' }}>
        <div key={tab} style={{ flex: 1, minHeight: 0, overflowY: 'auto', WebkitOverflowScrolling: 'touch' }} className="scroll">
          {screen}
        </div>
        <BottomTabs tab={tab} setTab={setTab} theme={theme}/>
      </div>

      {lender && <SettlementSheet lender={lender} theme={theme} serif={serif} onClose={() => setLender(null)}/>}
    </MobileFrame>
  );
}

// ─── LOADING / ERROR SCREENS ─────────────────────────────────
function LoadingScreen({ theme }) {
  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: 40, color: theme.ink,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 99,
        border: `2.5px solid ${theme.rule}`, borderTopColor: theme.surface,
        animation: 'spin 0.8s linear infinite',
      }}/>
      <div className="serif" style={{ fontSize: 16, marginTop: 18, color: theme.inkDim }}>
        Loading your portal…
      </div>
    </div>
  );
}

function ErrorScreen({ theme, error, onRetry, onSignOut }) {
  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: 40, textAlign: 'center', color: theme.ink,
    }}>
      <Icon name="info" size={32} color={theme.inkDim}/>
      <h2 className="serif" style={{ fontSize: 22, margin: '20px 0 8px', fontWeight: 500 }}>Couldn't load your portal</h2>
      <div style={{ fontSize: 14, color: theme.inkMute, lineHeight: 1.5, maxWidth: 300 }}>
        {error?.message || 'Something went wrong.'}
      </div>
      <button onClick={onRetry} style={{
        marginTop: 24, padding: '12px 22px', borderRadius: 12,
        background: theme.surface, color: theme.onSurface, fontSize: 14, fontWeight: 600,
      }}>Try again</button>
      <button onClick={onSignOut} style={{
        marginTop: 10, padding: '10px 22px', fontSize: 13, color: theme.inkDim, fontWeight: 500,
      }}>Sign out</button>
    </div>
  );
}

// ─── STAGE ───────────────────────────────────────────────────
function Stage() {
  const theme = useTheme('brand', 'sage');
  const serif = true;
  return <DLApp theme={theme} serif={serif}/>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<Stage/>);
