// App shell — Task 8. No router dependency: view switching is the tiny
// hash-based hook in lib/useHashView.ts. Company selection (and the
// zero/one/many-companies branching) comes from lib/company.tsx's
// CompanyProvider, mounted in main.tsx.
//
// Task 9 adds the two drill-through routes (#/account/:id, #/entry/:id) and
// wires every "go look at this number" callback — Reports' account rows,
// the dashboard's BalancePanel/ActivityList, and an entry's reversal links —
// through navigate() to them (CLAUDE.md §9 "every number drills through").

import { useCompany } from "./lib/company";
import { useHashView } from "./lib/useHashView";
import { Sidebar } from "./Sidebar";
import { Dashboard } from "./Dashboard";
import { Home } from "./home/Home";
import { BankImportWizard } from "./bank/BankImportWizard";
import { StatementReview } from "./bank/StatementReview";
import { Reports } from "./Reports";
import { RegisterScreen } from "./register/RegisterScreen";
import { AccountEntries } from "./AccountEntries";
import { EntryDetail } from "./EntryDetail";
import { Record } from "./Record";
import { CloseScreen } from "./close/CloseScreen";
import { SettingsScreen } from "./settings/SettingsScreen";
import { SetupWizard } from "./setup/SetupWizard";
import { ErrorBanner } from "./components/ErrorBanner";
import { PrintPnl } from "./reports/PrintPnl";
import { PrintBalanceSheet } from "./reports/PrintBalanceSheet";
import { PrintInventoryValuation } from "./reports/PrintInventoryValuation";
import { CustomersScreen } from "./customers/CustomersScreen";
import { InvoicesScreen } from "./invoices/InvoicesScreen";
import { InvoiceDetail } from "./invoices/InvoiceDetail";
import { InvoicePrint } from "./invoices/InvoicePrint";
import { ReceivePayment } from "./payments/ReceivePayment";
import { PaymentDetail } from "./payments/PaymentDetail";
import { VendorsScreen } from "./vendors/VendorsScreen";
import { BillsScreen } from "./bills/BillsScreen";
import { BillDetail } from "./bills/BillDetail";
import { PayBills } from "./billPayments/PayBills";
import { BillPaymentDetail } from "./billPayments/BillPaymentDetail";
import { ChecksScreen } from "./checks/ChecksScreen";
import { CheckPrintPage } from "./checks/CheckPrintPage";
import { ChartScreen } from "./accounts/ChartScreen";
import { ItemsScreen } from "./items/ItemsScreen";
import { ItemDetail } from "./items/ItemDetail";
import { PurchaseOrdersScreen } from "./purchaseOrders/PurchaseOrdersScreen";
import { PurchaseOrderDetail } from "./purchaseOrders/PurchaseOrderDetail";
import { PurchaseOrderPrint } from "./purchaseOrders/PurchaseOrderPrint";
import { BuildsScreen } from "./builds/BuildsScreen";
import { StockAdjustmentsScreen } from "./inventory/StockAdjustmentsScreen";

export default function App() {
  const { companies, loading, error, refresh } = useCompany();
  const [route, navigate] = useHashView();
  const goToAccount = (accountId: string) => navigate({ view: "account", id: accountId });
  const goToEntry = (entryId: string) => navigate({ view: "entry", id: entryId });

  // Only the TRUE initial load (nothing known yet) takes over the whole
  // screen. Task 10 introduced the first callers of refresh() that fire
  // mid-session (the setup wizard, right after creating a company) — if
  // this instead fired on every loading/error flip regardless of whether
  // companies are already known, a background refetch would blank out
  // whatever screen (e.g. the wizard, mid-step) the user is currently on,
  // which is jarring on its own AND unmounts+remounts it: that remount
  // reruns the wizard's mount-time resumability check while
  // selectedCompanyId still holds its PRE-refresh value (the caller hasn't
  // reached its post-await selectCompany() call yet), reproducing the exact
  // company-switcher-snaps-back-to-the-old-company bug this comment is
  // guarding against. Once at least one company is known, later
  // loading/error states are handled stale-while-revalidate: keep rendering
  // what we had.
  if (loading && companies.length === 0) {
    return (
      <div className="shell-fullscreen">
        <p className="msg">Loading your companies&hellip;</p>
      </div>
    );
  }

  if (error && companies.length === 0) {
    return (
      <div className="shell-fullscreen">
        <div style={{ width: "100%", maxWidth: 480 }}>
          <ErrorBanner message={error} onRetry={refresh} />
        </div>
      </div>
    );
  }

  if (companies.length === 0) {
    // First run, Task 10: nothing to switch between yet, so the wizard
    // fills the screen standalone (no Sidebar — there's no company to show
    // one for). Once step 1 creates a company, useCompany's own effect
    // picks it up and this branch stops matching on the next render.
    // entry stays "unspecified" (the default): there is no company to have
    // stated anything about, and this is the arrival the resumability check
    // was designed for.
    return (
      <div className="setup-standalone">
        <SetupWizard navigate={navigate} />
      </div>
    );
  }

  // Statement print views (AR Task 4) render with NO Sidebar/app chrome at
  // all — the whole point of #reports/print/pnl and
  // #reports/print/balance-sheet is a page containing only the formal
  // document (plus a screen-only back link/print button hidden again in the
  // @media print stylesheet), so this returns before the shell wrapper
  // below, same as the zero-companies branch above. #invoice/:id/print (AR
  // Task 5) is the same idea for a single invoice.
  if (route.view === "print") {
    if (route.printType === "pnl") {
      return <PrintPnl from={route.params.from ?? ""} to={route.params.to ?? ""} />;
    }
    if (route.printType === "inventory-valuation") {
      return <PrintInventoryValuation asOf={route.params.asOf ?? ""} />;
    }
    return <PrintBalanceSheet asOf={route.params.asOf ?? ""} />;
  }
  if (route.view === "invoice-print") {
    return <InvoicePrint invoiceId={route.id} />;
  }
  // #purchase-order/:id/print (Inventory Task 4) is the purchasing mirror of
  // the same idea — chrome-free paper, its own no-print toolbar.
  if (route.view === "purchase-order-print") {
    return <PurchaseOrderPrint poId={route.id} />;
  }
  // #checks/print-run (AP Task 5) is the checks mirror of the same idea —
  // no chrome, just the printable check/voucher layout plus its own
  // no-print toolbar/confirmation panel (CheckPrintPage.tsx).
  if (route.view === "checks-print") {
    return <CheckPrintPage params={route.params} navigate={navigate} />;
  }

  // Sidebar highlighting only applies to the seven static top-level screens —
  // the drill-through pages and the setup wizard (reached only via the
  // company switcher's "Add company" item, Task 10) aren't in the nav, so
  // nothing lights up while looking at one (that's fine; the BackLink/wizard
  // itself is the way out).
  const navView =
    route.view === "account" ||
    route.view === "entry" ||
    route.view === "invoice" ||
    route.view === "payment" ||
    route.view === "receive-payment" ||
    route.view === "bill" ||
    route.view === "bill-payment" ||
    route.view === "item" ||
    route.view === "purchase-order" ||
    route.view === "pay-bills" ||
    route.view === "setup" ||
    route.view === "bank-import" ||
    route.view === "bank-statement"
      ? null
      : route.view;

  return (
    <div className="shell">
      <Sidebar view={navView} onNavigate={navigate} />
      <main className="shell-main">
        {route.view === "home" && (
          <Home onSelectAccount={goToAccount} onSelectEntry={goToEntry} navigate={navigate} />
        )}
        {route.view === "dashboard" && (
          <Dashboard onSelectAccount={goToAccount} onSelectEntry={goToEntry} navigate={navigate} />
        )}
        {route.view === "reports" && <Reports onSelectAccount={goToAccount} navigate={navigate} />}
        {route.view === "transactions" && (
          <RegisterScreen
            navigate={navigate}
            onSelectEntry={goToEntry}
            initialAccountId={"accountId" in route ? route.accountId : undefined}
          />
        )}
        {route.view === "chart" && <ChartScreen navigate={navigate} />}
        {route.view === "items" && <ItemsScreen navigate={navigate} />}
        {route.view === "purchase-orders" && <PurchaseOrdersScreen navigate={navigate} />}
        {route.view === "builds" && <BuildsScreen navigate={navigate} />}
        {route.view === "stock-adjustments" && <StockAdjustmentsScreen navigate={navigate} />}
        {route.view === "record" && <Record navigate={navigate} />}
        {route.view === "customers" && <CustomersScreen navigate={navigate} />}
        {route.view === "invoices" && <InvoicesScreen navigate={navigate} />}
        {route.view === "vendors" && <VendorsScreen navigate={navigate} />}
        {route.view === "bills" && <BillsScreen navigate={navigate} />}
        {route.view === "checks" && <ChecksScreen navigate={navigate} />}
        {route.view === "close" && <CloseScreen />}
        {route.view === "settings" && <SettingsScreen navigate={navigate} />}
        {/* #/setup?new=1 carries the "+ Add company…" intent through reload
            and Back; a bare #/setup states nothing, and the wizard asks. */}
        {route.view === "setup" && (
          <SetupWizard navigate={navigate} entry={"intent" in route ? route.intent : "unspecified"} />
        )}
        {route.view === "account" && <AccountEntries accountId={route.id} onSelectEntry={goToEntry} />}
        {route.view === "entry" && <EntryDetail entryId={route.id} onSelectEntry={goToEntry} />}
        {route.view === "invoice" && <InvoiceDetail invoiceId={route.id} navigate={navigate} />}
        {route.view === "payment" && <PaymentDetail paymentId={route.id} navigate={navigate} />}
        {route.view === "bill" && <BillDetail billId={route.id} navigate={navigate} />}
        {route.view === "item" && <ItemDetail itemId={route.id} navigate={navigate} />}
        {route.view === "purchase-order" && (
          <PurchaseOrderDetail poId={route.id} navigate={navigate} />
        )}
        {route.view === "bill-payment" && <BillPaymentDetail paymentId={route.id} navigate={navigate} />}
        {route.view === "receive-payment" && (
          <ReceivePayment
            navigate={navigate}
            initialCustomerId={route.params.customerId}
            initialInvoiceId={route.params.invoiceId}
          />
        )}
        {route.view === "pay-bills" && (
          <PayBills
            navigate={navigate}
            initialVendorId={route.params.vendorId}
            initialBillId={route.params.billId}
          />
        )}
        {route.view === "bank-import" && (
          <BankImportWizard navigate={navigate} initialAccountId={route.params.accountId} />
        )}
        {route.view === "bank-statement" && (
          <StatementReview statementId={route.id} navigate={navigate} />
        )}
      </main>
    </div>
  );
}
