// Main app entry — orchestrates state and lays out the page.
const { useState: useStateApp, useMemo: useMemoApp, useEffect: useEffectApp } = React;

window.DEFAULT_SCENARIO = {
  homePrice: 850000,
  downPayment: 170000,
  credit: 760,
  zip: "94568",
  state: "CA",
  propertyType: "sfh",
  loanPurpose: "purchase",
  occupancy: "primary",
  loanType: "Conventional",
  lockDays: "15",
  searchBy: "Rate",
  military: "no",
};

function App() {
  const [scenario, setScenario] = useStateApp(window.DEFAULT_SCENARIO);
  const [filter, setFilter] = useStateApp("all");
  const [rows, setRows] = useStateApp([]);
  const [mode, setMode] = useStateApp("idle"); // "idle" | "stub" | "mortech" | "stub-fallback" | "mortech-stub-blend" | "loading" | "error"
  const [pricingError, setPricingError] = useStateApp(null);
  const [fetchedAt, setFetchedAt] = useStateApp(null);
  const [authed, setAuthed] = useStateApp(null); // null=checking, true/false
  const [selectedRows, setSelectedRows] = useStateApp([]);
  const [view, setView] = useStateApp('launcher'); // 'launcher' | 'pricing' | 'comparison'

  const [currentUser, setCurrentUser] = useStateApp(null);

  // Auth gate — check on load
  useEffectApp(() => {
    fetch("/api/auth/me")
      .then(r => r.json())
      .then(j => {
        setAuthed(!!j.authed);
        if (j.authed && j.user) setCurrentUser(j.user);
      })
      .catch(() => setAuthed(false));
  }, []);

  // Google OAuth sign-in — redirect to backend which handles the OAuth flow
  const signIn = () => {
    window.location.href = '/api/auth/google/start';
  };

  const signOut = async () => {
    await fetch("/api/auth/sign-out", { method: "POST" });
    setAuthed(false);
    setView('launcher');
  };

  // Fetch function
  const fetchPricing = async (cancelledRef) => {
    setMode("loading");
    setPricingError(null);
    try {
      const res = await fetch("/api/scenarios/price", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(scenario),
      });
      const json = await res.json();
      if (cancelledRef && cancelledRef.current) return;
      if (!res.ok) {
        setMode("error");
        setPricingError(json?.error?.messages?.join(", ") || json?.error?.message || `HTTP ${res.status}`);
        setRows([]);
        return;
      }
      setRows(json.rows || []);
      setMode(json.source || "stub");
      setFetchedAt(json.fetched_at || null);

      // Auto-select the first product row if nothing selected yet or key doesn't match
      if (json.rows && json.rows.length > 0) {
        setSelectedRows(prev => prev.length === 0 ? [json.rows[0].key] : prev);
      } else {
        setSelectedRows([]);
      }
    } catch (err) {
      if (cancelledRef && cancelledRef.current) return;
      setMode("error");
      setPricingError(String(err));
      setRows([]);
    }
  };

  // Pricing is intentionally manual-trigger only. Editing fields does not fetch.

  // Handle manual "Generate Pricing" button click
  const handleGeneratePricing = () => {
    fetchPricing();
  };

  // Checkbox row toggler — multi-select, max 4 rows (1 baseline + 3 options)
  const handleToggleSelect = (key) => {
    setSelectedRows(prev =>
      prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
    );
  };

  // Tier selection — replaces oldKey with newKey so the deck shows the chosen rate tier
  const handleSelectTier = (oldKey, newKey) => {
    if (oldKey === newKey) return;
    setSelectedRows(prev => prev.map(k => k === oldKey ? newKey : k));
  };

  // When new pricing arrives, auto-select the first row only if nothing selected
  // (preserve existing selection after re-price)

  // Find active selected row details to feed into bottom comparison deck
  const activeScenarioRow = useMemoApp(() => {
    return rows.find((r) => selectedRows.includes(r.key)) || rows[0] || null;
  }, [rows, selectedRows]);

  // ─── Auth gate ─────────────────────────────────────────────────────────
  if (authed === null) {
    return (
      <div style={{
        display: "flex",
        height: "100vh",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "var(--bg-page)",
        color: "var(--text-light)",
        fontFamily: "'Hanken Grotesk', sans-serif"
      }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 44, animation: "spin 1.5s linear infinite", marginBottom: 12 }}>⏳</div>
          <div style={{ fontWeight: 600, fontSize: 15 }}>Loading Pricing Portal…</div>
        </div>
        <style>{`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  if (authed === false) {
    return <window.SignInOverlay onSignIn={signIn} />;
  }

  return (
    <React.Fragment>
      <window.Header
        onSignOut={signOut}
        currentUser={currentUser}
        mode={view === 'launcher' ? 'launcher' : 'workspace'}
        onHome={() => setView('launcher')}
      />

      {view === 'launcher' ? (
        <window.AppLauncherScreen onLaunchApp={() => setView('pricing')} />
      ) : view === 'comparison' ? (
        <window.ComparisonScreen
          rows={rows}
          selectedKeys={selectedRows}
          onBack={() => setView('pricing')}
          fetchedAt={fetchedAt}
          scenario={scenario}
        />
      ) : (
        <main className="app-container">
          <window.ScenarioForm
            scenario={scenario}
            setScenario={setScenario}
            onPrice={handleGeneratePricing}
          />

          <div className="content-area">
            <div className="section-title-row">
              <h1>Today's rates, priced for you</h1>
              <div className="live-status-pill">
                <span className="live-status-dot"></span>
                {mode === "idle" && "Ready"}
                {mode === "loading" && "Pricing…"}
                {mode === "stub" && "Live · Just Now"}
                {mode === "mortech" && "Live · Just Now"}
                {mode === "stub-fallback" && "Stub fallback"}
                {mode === "mortech-stub-blend" && "Live + fallback"}
                {mode === "error" && "Pricing error"}
              </div>
            </div>

            <div className="filter-row">
              <div className="filter-pills">
                <button className={`filter-pill ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>All</button>
                <button className={`filter-pill ${filter === "fixed" ? "active" : ""}`} onClick={() => setFilter("fixed")}>Fixed</button>
                <button className={`filter-pill ${filter === "arm" ? "active" : ""}`} onClick={() => setFilter("arm")}>ARM</button>
                <button className={`filter-pill ${filter === "gov" ? "active" : ""}`} onClick={() => setFilter("gov")}>FHA / VA</button>
                <button className={`filter-pill ${filter === "jumbo" ? "active" : ""}`} onClick={() => setFilter("jumbo")}>Jumbo</button>
              </div>

              <div className="scenario-summary-text">
                ${scenario.homePrice.toLocaleString()} · {((scenario.downPayment / scenario.homePrice) * 100).toFixed(0)}% DOWN · {scenario.credit} FICO
              </div>
            </div>

            {pricingError && (
              <div style={{
                padding: "12px 16px",
                backgroundColor: "#fee2e2",
                border: "1px solid #fca5a5",
                borderRadius: 8,
                color: "#991b1b",
                fontSize: 13,
                fontWeight: 500
              }}>
                Pricing Fetch Failed: {pricingError}
              </div>
            )}

            <window.RateTable
              rows={rows}
              filter={filter}
              selectedRows={selectedRows}
              onToggleSelect={handleToggleSelect}
              onSelectTier={handleSelectTier}
              scenario={scenario}
              onLockDaysChange={(days) => setScenario(prev => ({ ...prev, lockDays: days }))}
              fetchedAt={fetchedAt}
            />

            <window.MarketTrend />

            <window.StatsWidgets />

            <window.LoanComparisonDeck
              rows={rows}
              selectedRows={selectedRows}
              scenario={scenario}
              onCompare={() => setView('comparison')}
            />
          </div>
        </main>
      )}

      {view !== 'launcher' && <window.Disclosure />}
    </React.Fragment>
  );
}

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