// Main app for Perdura Capital
// Wires subdomain routing → auth → wizard → dashboard

const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "bizType": "product",
  "persona": "CFO",
  "period": "MTD",
  "fiscalYear": "FY26",
  "density": "regular",
  "dark": false,
  "accent": "#059669",
  "plainEnglish": false,
  "showWizard": false
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ["#059669", "#2563eb", "#d97706", "#7c3aed", "#db2777"];
const MONTHS_LIST = ["January","February","March","April","May","June","July","August","September","October","November","December"];

// ─── Subdomain context (set synchronously by subdomain.js before React mounts)
const SD = window.PerduraSubdomain || { type: "root", slug: null };

// ─── Redirect helpers ─────────────────────────────────────────────────────────

function redirectToSubdomain(slug, path = "") {
  const target = `https://${slug}.cfodash.app${path}`;
  window.location.replace(target);
}

function redirectToApp(path = "") {
  window.location.replace(`https://app.cfodash.app${path}`);
}

function redirectToRoot() {
  window.location.replace("https://cfodash.app");
}

// ─── Lookup company_id for a subdomain slug ────────────────────────────────────

async function lookupCompanyBySlug(slug) {
  const db = window.supabaseClient;
  if (!db || !slug) return null;
  const { data } = await db
    .from("companies")
    .select("id, name, subdomain, status, business_type, fiscal_year_end, fiscal_year_start, revenue_band, employee_count, multi_entity, industry, owner_name")
    .eq("subdomain", slug)
    .maybeSingle();
  return data || null;
}

async function fetchCompanyProfile(companyId) {
  const db = window.supabaseClient;
  if (!db || !companyId) return null;
  const { data } = await db
    .from("companies")
    .select("id, name, subdomain, status, business_type, fiscal_year_end, fiscal_year_start, revenue_band, employee_count, multi_entity, industry, owner_name")
    .eq("id", companyId)
    .maybeSingle();
  return data || null;
}

async function saveCompanyProfile(companyId, profile) {
  const db = window.supabaseClient;
  if (!db || !companyId) return;
  await db.from("companies").update(profile).eq("id", companyId);
}

// ─── Lookup this user's company memberships ────────────────────────────────────

async function lookupUserMembership(userId) {
  const db = window.supabaseClient;
  if (!db || !userId) return null;
  // Accept Pending and Active — a freshly invited user starts as Pending
  const { data } = await db
    .from("company_users")
    .select("company_id, role, status, companies(subdomain, name)")
    .eq("user_id", userId)
    .in("status", ["Active", "Pending"])
    .maybeSingle();
  return data || null;
}

// ─── Fetch all companies (super-admin only) ────────────────────────────────────

async function fetchAllCompanies() {
  const db = window.supabaseClient;
  if (!db) return [];
  const { data } = await db
    .from("companies")
    .select("id, name, subdomain, status")
    .order("name", { ascending: true });
  return data || [];
}

// ─── App ──────────────────────────────────────────────────────────────────────

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = useStateApp("health");
  const [aiOpen, setAIOpen] = useStateApp(false);

  // view: "loading" | "auth" | "wizard" | "setup" | "app" | "admin" | "no-access"
  const [view, setView] = useStateApp("loading");

  // Live data state
  const [liveResult, setLiveResult] = useStateApp(null);

  // The company_id this dashboard is scoped to (resolved from subdomain or membership)
  const [scopedCompanyId, setScopedCompanyId] = useStateApp(null);

  // Full company profile loaded from DB
  const [companyProfile, setCompanyProfile] = useStateApp(null);

  // For no-access screen: which slug the user tried and what their own slug is
  const [accessMeta, setAccessMeta] = useStateApp({ requestedSlug: null, ownSlug: null });

  // Super-admin state
  const [isSuperAdminUser, setIsSuperAdminUser] = useStateApp(false);
  const [allCompanies, setAllCompanies] = useStateApp([]);
  // When admin views a real company that has no GL data yet, show empty state
  const [adminViewingNoData, setAdminViewingNoData] = useStateApp(false);

  // Returns "setup" if this company has never completed onboarding, otherwise "app"
  // Super-admins always skip setup; only regular company users see it.
  const resolveCompanyView = (company) => {
    if (!company) return "app";
    if (!company.business_type) return "setup";
    return "app";
  };

  // ── Bootstrap: determine view from subdomain + session ──────────────────────
  useEffectApp(() => {
    const db = window.supabaseClient;

    async function bootstrap() {
      // No Supabase → fall through to demo app
      if (!db) { setView(t.showWizard ? "wizard" : "app"); return; }

      const { data: { session } } = await db.auth.getSession();
      const user = session?.user || null;
      const isSuperAdmin = user?.app_metadata?.super_admin === true;

      if (isSuperAdmin) {
        setIsSuperAdminUser(true);
        // Load all companies for the switcher
        fetchAllCompanies().then(cos => setAllCompanies(cos));
      }

      // ── ROOT domain or non-cfodash.app host (e.g. Vercel preview) ──────────
      if (SD.type === "root") {
        if (!user) { setView("auth"); return; }
        // Super-admin ALWAYS goes to admin console on root URL — no exceptions
        if (isSuperAdmin) { setView("admin"); return; }
        // Regular user → redirect to their company subdomain if on cfodash.app
        const membership = await lookupUserMembership(user.id);
        if (membership?.companies?.subdomain) {
          if (window.location.hostname.endsWith("cfodash.app")) {
            redirectToSubdomain(membership.companies.subdomain);
            return;
          }
          // On Vercel preview — load company inline
          const company = await fetchCompanyProfile(membership.company_id);
          if (company) {
            setScopedCompanyId(company.id);
            setCompanyProfile(company);
            setView(t.showWizard ? "wizard" : resolveCompanyView(company));
            return;
          }
        }
        setView(t.showWizard ? "wizard" : "app");
        return;
      }

      // ── APP subdomain: app.cfodash.app ────────────────────────────────────
      if (SD.type === "app") {
        if (!user) { setView("auth"); return; }
        const membership = await lookupUserMembership(user.id);
        if (membership?.companies?.subdomain) {
          redirectToSubdomain(membership.companies.subdomain);
        } else {
          setView(t.showWizard ? "wizard" : "app");
        }
        return;
      }

      // ── ADMIN subdomain: admin.cfodash.app ────────────────────────────────
      if (SD.type === "admin") {
        if (!user) { setView("auth"); return; }
        if (isSuperAdmin) { setView("admin"); return; }
        redirectToRoot();
        return;
      }

      // ── COMPANY subdomain: {slug}.cfodash.app ─────────────────────────────
      if (SD.type === "subdomain") {
        const company = await lookupCompanyBySlug(SD.slug);
        if (!company) {
          redirectToRoot();
          return;
        }

        if (!user) {
          setView("auth");
          return;
        }

        if (isSuperAdmin) {
          setScopedCompanyId(company.id);
          setView("admin");
          return;
        }

        const membership = await lookupUserMembership(user.id);
        if (membership?.company_id === company.id) {
          setScopedCompanyId(company.id);
          setCompanyProfile(company);
          setView(t.showWizard ? "wizard" : resolveCompanyView(company));
        } else {
          const ownSlug = membership?.companies?.subdomain || null;
          setAccessMeta({ requestedSlug: SD.slug, ownSlug });
          setView("no-access");
        }
        return;
      }
    }

    // Safety net: if bootstrap hangs for >8s, fall back to auth screen
    const loadingTimeout = setTimeout(() => setView(v => v === "loading" ? "auth" : v), 8000);

    bootstrap().catch(err => {
      console.error("[app] bootstrap error", err);
      setView("auth");
    }).finally(() => clearTimeout(loadingTimeout));

    if (!db) return;

    // Auth state listener — handles sign-in (activate pending member), sign-out, and password recovery
    const { data: { subscription } } = db.auth.onAuthStateChange((event, session) => {
      (async () => {
        // Password reset link — show the set-new-password form
        if (event === "PASSWORD_RECOVERY") {
          setView("reset-password");
          return;
        }
        if (!session) {
          setIsSuperAdminUser(false);
          setAllCompanies([]);
          setView("auth");
          return;
        }
        // When a newly-invited user signs in for the first time, mark them Active
        if (event === "SIGNED_IN" || event === "USER_UPDATED") {
          await db
            .from("company_users")
            .update({ status: "Active", joined_at: new Date().toISOString() })
            .eq("user_id", session.user.id)
            .eq("status", "Pending");
        }
      })();
    });
    return () => { clearTimeout(loadingTimeout); subscription.unsubscribe(); };
  }, []);

  // ── Fetch company profile whenever scopedCompanyId resolves ────────────
  useEffectApp(() => {
    if (!scopedCompanyId) return;
    fetchCompanyProfile(scopedCompanyId).then(p => {
      if (p) setCompanyProfile(p);
    });
  }, [scopedCompanyId]);

  // ── Live data fetch whenever the app view is active ──────────────────────
  useEffectApp(() => {
    if (view !== "app") return;
    if (!window.PerduraLive) return;
    window.PerduraLive.fetchLiveData(t.bizType, scopedCompanyId).then(result => {
      setLiveResult(result);
    }).catch(() => {
      setLiveResult({ data: null, integrations: [], isEmpty: true });
    });
  }, [view, t.bizType, scopedCompanyId]);

  // ── Resolve data object ──────────────────────────────────────────────────
  const demoData = PerduraData[t.bizType] || PerduraData.product;
  // A real company (has scopedCompanyId) with no live data should NOT show demo numbers
  const hasRealCompany = !!scopedCompanyId;
  const hasLiveData = !!(liveResult && !liveResult.isEmpty && liveResult.data);
  const data = hasLiveData ? liveResult.data : demoData;
  const isDemo = !hasLiveData;
  // showEmptyState = real company, no live data yet
  // Also applies when admin is viewing a company that has setup but no GL transactions
  const showEmptyState = (hasRealCompany && isDemo && !isSuperAdminUser) || adminViewingNoData;
  const integrations = (liveResult && liveResult.integrations) || [];
  const exceptionsCount = data.exceptions.length;

  // ── Theme + accent ───────────────────────────────────────────────────────
  useEffectApp(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", t.dark ? "dark" : "light");
    root.style.setProperty("--accent", t.accent);
    // Also update --positive to match accent if it's the green variant
    if (t.accent === "#059669" || t.accent === "#6ee7b7") {
      root.style.setProperty("--positive", "#059669");
    }
    const accent2Map = {
      "#059669": "#2563eb",
      "#2563eb": "#059669",
      "#d97706": "#dc2626",
      "#7c3aed": "#2563eb",
      "#db2777": "#7c3aed",
      "#6ee7b7": "#2563eb",
      "#60a5fa": "#059669",
      "#fbbf24": "#dc2626",
      "#a78bfa": "#2563eb",
      "#f472b6": "#7c3aed",
    };
    root.style.setProperty("--accent-2", accent2Map[t.accent] || "#2563eb");
    // --on-accent must be readable on top of the accent color
    const lightAccents = ["#fbbf24", "#6ee7b7", "#d97706"];
    root.style.setProperty("--on-accent", lightAccents.includes(t.accent) ? "#0c1220" : "#ffffff");
    root.style.setProperty("--density", t.density === "compact" ? "0.85" : t.density === "comfy" ? "1.1" : "1");
    window.__perduraPlain = !!t.plainEnglish;
  }, [t.dark, t.accent, t.density, t.plainEnglish]);

  useEffectApp(() => { window.__perduraSetPage = setPage; }, [setPage]);

  // ── Super-admin: switch to a specific company's dashboard (null = demo) ──
  const switchToCompany = async (companyId, companyObj) => {
    if (!companyId) {
      // null = back to demo mode
      setScopedCompanyId(null);
      setLiveResult(null);
      setCompanyProfile(null);
      setAdminViewingNoData(false);
      setPage("health");
      setView("app");
      return;
    }
    setScopedCompanyId(companyId);
    setLiveResult(null);
    setCompanyProfile(companyObj || null);
    setAdminViewingNoData(false);
    setPage("health");
    setView("loading");

    // Fetch company profile if not passed in
    const profile = companyObj || await fetchCompanyProfile(companyId);
    if (profile) setCompanyProfile(profile);

    // Check if this company has any GL data or completed setup
    const db = window.supabaseClient;
    let hasData = false;
    if (db) {
      const { data: txns } = await db
        .from("gl_transactions")
        .select("id")
        .eq("company_id", companyId)
        .limit(1);
      hasData = (txns || []).length > 0;
    }

    // Also check if business_type is set (setup completed)
    const hasSetup = !!(profile || companyObj)?.business_type;

    if (!hasSetup) {
      setView("setup");
    } else if (!hasData) {
      // Company completed setup but no GL data — show empty state even for admin
      setAdminViewingNoData(true);
      setView("app");
    } else {
      setAdminViewingNoData(false);
      setView("app");
    }
  };

  const onSetupComplete = ({ bizType, profile }) => {
    const fyEnd = profile.fyEnd || "December";
    const fyYear = new Date().getFullYear();
    const currentMonth = new Date().getMonth();
    const endMonthIdx = MONTHS_LIST.indexOf(fyEnd);
    const fiscalYearLabel = "FY" + String(currentMonth <= endMonthIdx ? fyYear : fyYear + 1).slice(-2);
    if (scopedCompanyId) {
      saveCompanyProfile(scopedCompanyId, {
        business_type: bizType,
        fiscal_year_end: fyEnd,
        revenue_band: profile.revenue || undefined,
        employee_count: profile.employees || undefined,
        multi_entity: profile.multiEntity || false,
      });
    }
    setTweak({ bizType });
    setTweak("fiscalYear", fiscalYearLabel);
    setCompanyProfile(prev => ({ ...(prev || {}), business_type: bizType, fiscal_year_end: fyEnd }));
    setView("app");
  };

  const onWizardComplete = ({ bizType, profile }) => {
    setTweak({ bizType, showWizard: false });
    if (scopedCompanyId && profile) {
      const fyYear = new Date().getFullYear();
      const fyEnd = profile.fyEnd || "December";
      const currentMonth = new Date().getMonth(); // 0-based
      const endMonthIdx = ["January","February","March","April","May","June","July","August","September","October","November","December"].indexOf(fyEnd);
      const fiscalYearLabel = "FY" + String(currentMonth <= endMonthIdx ? fyYear : fyYear + 1).slice(-2);
      saveCompanyProfile(scopedCompanyId, {
        name: profile.company || undefined,
        business_type: bizType,
        fiscal_year_end: fyEnd,
        fiscal_year_start: profile.fiscalYearStart || "January",
        revenue_band: profile.revenue || undefined,
        employee_count: profile.employees || undefined,
        multi_entity: profile.multiEntity || false,
      });
      setCompanyProfile(prev => ({
        ...(prev || {}),
        name: profile.company,
        business_type: bizType,
        fiscal_year_end: fyEnd,
      }));
      setTweak("fiscalYear", fiscalYearLabel);
    }
    setView("app");
  };

  useEffectApp(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setAIOpen(true);
      }
      if (e.key === "Escape") setAIOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Handle OAuth callback return — navigate to config page and show result
  useEffectApp(() => {
    const params = new URLSearchParams(window.location.search);
    const oauthSuccess = params.get("oauth_success");
    const oauthError = params.get("oauth_error");
    if (oauthSuccess || oauthError) {
      window.history.replaceState({}, "", window.location.pathname);
      setPage("settings_config");
    }
  }, [view]);

  // ── Views ────────────────────────────────────────────────────────────────

  if (view === "loading") {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg-base)" }}>
        <div style={{ width: 32, height: 32, border: "2px solid var(--border-strong)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "pc-spin 0.7s linear infinite" }} />
      </div>
    );
  }

  if (view === "reset-password") {
    return (
      <ResetPasswordForm onDone={() => {
        // Re-bootstrap to pick up the newly-authenticated session
        setView("loading");
        window.location.hash = "";
        window.location.reload();
      }} />
    );
  }

  if (view === "auth") {
    return (
      <AuthPage onAuthenticated={async (user) => {
        const isSuperAdmin = user?.app_metadata?.super_admin === true;

        if (isSuperAdmin) {
          setIsSuperAdminUser(true);
          fetchAllCompanies().then(cos => setAllCompanies(cos));
        }

        // Admin subdomain
        if (SD.type === "admin" && isSuperAdmin) { setView("admin"); return; }

        // On root / Vercel URL: super-admin goes to admin console
        if ((SD.type === "root") && isSuperAdmin) { setView("admin"); return; }

        // Company subdomain — verify access after login
        if (SD.type === "subdomain") {
          const company = await lookupCompanyBySlug(SD.slug);
          if (company) {
            if (isSuperAdmin) {
              // Super-admin on a customer subdomain → go to admin console, not customer view
              setView("admin");
              return;
            }
            const membership = await lookupUserMembership(user.id);
            if (membership?.company_id === company.id) {
              setScopedCompanyId(company.id);
              setCompanyProfile(company);
              setView(t.showWizard ? "wizard" : resolveCompanyView(company));
              return;
            }
            setAccessMeta({ requestedSlug: SD.slug, ownSlug: membership?.companies?.subdomain || null });
            setView("no-access");
            return;
          }
        }

        // Regular user on Vercel/root — load their company inline
        if (!isSuperAdmin) {
          const membership = await lookupUserMembership(user.id);
          if (membership?.company_id) {
            const company = await fetchCompanyProfile(membership.company_id);
            if (company) {
              setScopedCompanyId(company.id);
              setCompanyProfile(company);
              setView(t.showWizard ? "wizard" : resolveCompanyView(company));
              return;
            }
            setScopedCompanyId(membership.company_id);
          }
        }

        setView(t.showWizard ? "wizard" : "app");
      }} />
    );
  }

  if (view === "no-access") {
    return <NoAccessPage requestedSlug={accessMeta.requestedSlug} ownSlug={accessMeta.ownSlug} />;
  }

  if (view === "admin") {
    return (
      <AdminPage
        isSuperAdmin={isSuperAdminUser}
        onViewCompany={(companyId, companyObj) => switchToCompany(companyId, companyObj)}
        onLogout={async () => {
          const db = window.supabaseClient;
          if (db) await db.auth.signOut();
          window.location.reload();
        }}
      />
    );
  }

  if (view === "wizard") {
    return (
      <>
        <Wizard onComplete={onWizardComplete} onExit={() => setView("app")} initialBizType={t.bizType} />
        <AppTweaks t={t} setTweak={setTweak} setView={setView} />
      </>
    );
  }

  // Persistent admin bar shown whenever super-admin is scoped to a real company
  const adminBar = isSuperAdminUser && scopedCompanyId ? (
    <div style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 9999,
      background: "#0e7490", color: "#fff",
      display: "flex", alignItems: "center", gap: 10,
      padding: "0 20px", height: 38, fontSize: 13, fontWeight: 500,
      boxShadow: "0 2px 8px rgba(0,0,0,0.18)"
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      Viewing as customer:
      <strong style={{ color: "#fff" }}>
        {(companyProfile?.name) || allCompanies.find(c => c.id === scopedCompanyId)?.name || "Customer"}
      </strong>
      <span style={{ opacity: 0.75, fontSize: 12 }}>
        · {companyProfile?.subdomain || ""}
      </span>
      <button
        onClick={() => setView("admin")}
        style={{
          marginLeft: "auto", background: "rgba(255,255,255,0.2)", border: "none",
          color: "#fff", borderRadius: 6, padding: "4px 12px", cursor: "pointer",
          fontSize: 12, fontWeight: 600, display: "flex", alignItems: "center", gap: 6
        }}
      >
        ← Back to Admin Console
      </button>
    </div>
  ) : null;

  if (view === "setup") {
    return (
      <>
        {adminBar}
        <div style={adminBar ? { paddingTop: 38 } : {}}>
          <SetupPage companyProfile={companyProfile} onComplete={onSetupComplete} />
        </div>
      </>
    );
  }

  const onRerunWizard = () => setView("wizard");

  return (
    <>
      {adminBar}
      <div className={"pc-app " + (t.density || "regular")} style={adminBar ? { paddingTop: 38 } : {}}>
      <Sidebar page={page} setPage={setPage}
        bizType={t.bizType} persona={t.persona}
        exceptionsCount={exceptionsCount} density={t.density}
        integrations={integrations}
        companyProfile={companyProfile}
        isSuperAdmin={isSuperAdminUser}
        allCompanies={allCompanies}
        scopedCompanyId={scopedCompanyId}
        onSwitchToAdmin={() => setView("admin")}
        onSwitchCompany={(id, obj) => switchToCompany(id, obj)}
      />
      <div className="pc-main">
        {isSuperAdminUser && isDemo && !adminViewingNoData && (
          <div className="pc-demo-banner">
            <span className="pc-demo-banner-dot" />
            Viewing sample data — this company has no live integration yet.
          </div>
        )}
        {!isSuperAdminUser && isDemo && !showEmptyState && (
          <div className="pc-demo-banner">
            <span className="pc-demo-banner-dot" />
            You're viewing sample data.{" "}
            <button className="pc-demo-banner-link" onClick={() => setPage("settings_config")}>
              Connect your accounting software
            </button>{" "}
            to see your real numbers.
          </div>
        )}
        <Topbar
          period={t.period} setPeriod={(v) => setTweak("period", v)}
          fiscalYear={t.fiscalYear} setFiscalYear={(v) => setTweak("fiscalYear", v)}
          persona={t.persona} setPersona={(v) => setTweak("persona", v)}
          bizType={t.bizType} setBizType={(v) => setTweak("bizType", v)}
          page={page}
          density={t.density}
          onOpenAI={() => setAIOpen(true)}
          exceptionsCount={exceptionsCount}
          companyProfile={companyProfile}
        />
        <div className="pc-content">
          {showEmptyState && !page.startsWith("settings") ? (
            <NoDataState onConnect={() => setPage("settings_config")} companyProfile={companyProfile} />
          ) : (<>
          {page === "health"     && <HealthPage data={data} bizType={t.bizType} setPage={setPage} period={t.period} setPeriod={(v) => setTweak("period", v)} companyProfile={companyProfile} />}
          {page === "overview"   && <OverviewPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} density={t.density} bizType={t.bizType} onDrill={() => {}} />}
          {page === "cash"       && <CashFlowPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "capital"    && <CapitalPage data={data} />}
          {page === "goals"      && <GoalsPage data={data} />}
          {page === "ratios"     && <RatiosPage data={data} bizType={t.bizType} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "acquisition" && <AcquisitionPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "arap"       && <ARAPPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} onDrill={() => {}} />}
          {page === "forecast"   && <ForecastPage data={data} period={t.period} />}
          {page === "sales"      && <SalesPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} onDrill={() => {}} />}
          {page === "customer"   && <CustomerProfitPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "margin"     && <MarginPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "stores"     && <StoresPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "inventory"  && <InventoryPage data={data} />}
          {page === "supply"     && <SupplyPage data={data} />}
          {page === "service"    && <ServicePage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "manufacturing" && <ManufacturingPage data={data} />}
          {page === "exceptions" && <ExceptionsPage data={data} />}
          {page === "decisions"  && <DecisionsPage data={data} bizType={t.bizType} />}
          {page === "weekly"     && <WeeklyReviewPage data={data} bizType={t.bizType} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "risk"       && <RiskPage data={data} bizType={t.bizType} />}
          {page === "expenses"   && <ExpensesPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "patterns"   && <SalesPatternsPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "pricing"    && <PricingPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "subscription" && <SubscriptionPage data={data} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "settings_config" && <ConfigPage data={data} bizType={t.bizType} setBizType={(v) => setTweak("bizType", v)} onRerunWizard={onRerunWizard} companyProfile={companyProfile} scopedCompanyId={scopedCompanyId} />}
          {page === "settings_period" && <PeriodPage fiscalYear={t.fiscalYear} setFiscalYear={(v) => setTweak("fiscalYear", v)} period={t.period} setPeriod={(v) => setTweak("period", v)} />}
          {page === "settings_users"  && <UsersPage />}
          {page === "settings_custom" && <CustomizePage t={t} setTweak={setTweak} onRerunWizard={onRerunWizard} />}
          {page === "contact"         && <ContactPage companyProfile={companyProfile} />}
          {page === "documents"       && <DocumentsPage companyProfile={companyProfile} scopedCompanyId={scopedCompanyId} />}
          </>)}
        </div>
      </div>
      <AICopilot open={aiOpen} onClose={() => setAIOpen(false)} page={page} />
      <AppTweaks t={t} setTweak={setTweak} setView={setView} setPage={setPage} />
    </div>
    </>
  );
}

// ── Empty state shown to real customers with no integrations yet ──────────
function NoDataState({ onConnect, companyProfile }) {
  const name = companyProfile?.name || "your company";
  return (
    <div style={{
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      minHeight: "calc(100vh - 120px)", padding: "40px 24px", textAlign: "center",
    }}>
      <div style={{
        width: 72, height: 72, borderRadius: 20, marginBottom: 24,
        background: "var(--bg-elev-2)", border: "1px solid var(--border)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
          <polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
          <line x1="12" y1="22.08" x2="12" y2="12"/>
        </svg>
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 10, letterSpacing: -0.3 }}>
        Welcome to Perdura
      </div>
      <div style={{ fontSize: 15, color: "var(--text-2)", maxWidth: 420, lineHeight: 1.6, marginBottom: 8 }}>
        {name} is all set up. Connect your accounting software to start seeing your real financial data across every dashboard.
      </div>
      <div style={{ fontSize: 13, color: "var(--text-3)", maxWidth: 380, lineHeight: 1.55, marginBottom: 32 }}>
        Perdura supports QuickBooks, Xero, NetSuite, and more. Your data stays read-only — we never write back.
      </div>
      <button
        onClick={onConnect}
        style={{
          padding: "12px 28px", background: "var(--accent)", color: "white",
          border: "none", borderRadius: 8, fontSize: 14, fontWeight: 600,
          cursor: "pointer", letterSpacing: -0.1,
        }}
      >
        Connect your accounting software
      </button>
      <div style={{ marginTop: 16, fontSize: 12, color: "var(--text-3)" }}>
        Or upload an Excel / CSV file to get started immediately
      </div>
    </div>
  );
}

function AppTweaks({ t, setTweak, setView, setPage }) {
  return (
    <TweaksPanel>
      <TweakSection label="Quick switches" />
      <TweakSelect label="Business" value={t.bizType}
        options={[
          { value: "service", label: "Service" },
          { value: "product", label: "Product" },
          { value: "retail",  label: "Retail / Stores" },
          { value: "manufacturing", label: "Manufacturing" },
          { value: "subscription", label: "Subscription" },
        ]}
        onChange={(v) => setTweak("bizType", v)} />
      <TweakToggle label="Dark mode" value={t.dark}
        onChange={(v) => setTweak("dark", v)} />
      <TweakColor label="Accent"
        value={t.accent}
        options={ACCENT_OPTIONS}
        onChange={(v) => setTweak("accent", v)} />

      <TweakSection label="More" />
      {setPage && <TweakButton label="Open full Customization page" onClick={() => setPage && setPage("settings_custom")} />}
      <TweakButton label="Re-run setup wizard" onClick={() => setView("wizard")} />
    </TweaksPanel>
  );
}

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