import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import { useLocation, useNavigate } from "@/lib/navigation";
import type { NavParams, ScreenId } from "@/pages/app/types";
import type { WebLang, WebParams, WebRole, WebScreen } from "@/pages/web/types";
import { webStrings } from "@/pages/web/webI18n";
import { appFromPath, appPath, webFromPath, webPath } from "./routes";
import {
  merchantProducts as seedMerchantProducts,
  myBusiness as seedBusiness,
  myOpportunities as seedOpportunities,
  type MerchantBusiness,
  type MerchantProduct,
  type MerchantProductStatus,
  type MyOpportunity,
} from "@/mocks/dshnBusiness";
import { historyEventId, todayLabel } from "@/pages/app/lib/productHistory";
import {
  bizEditRequestNumber,
  buildBizEditChanges,
  formatBizEditDate,
  type BizEditRequest,
} from "@/pages/app/lib/bizEditRequest";
import {
  bizPartnershipRows as seedPartnerships,
  type BizPartnershipRow,
  type BizPartnershipStatus,
  type BizPartnerMsg,
} from "@/mocks/dshnBizPartners";
import { partnerRequestStamp } from "@/pages/app/lib/partnerRequest";
import { partnerStatusLabel, partnerStatusTone } from "@/pages/app/lib/partnerStatus";
import type { PartnerBusiness } from "@/mocks/dshnBusiness";
import {
  buildPartnerRequestRow,
  isOpenPartnership,
  nextPartnershipNumber,
  partnershipBusinessId,
  type PartnerRequestResult,
} from "@/pages/app/lib/partnerRequest";
import {
  BIZ_SIGNUP_DEMO_CODE,
  BIZ_SIGNUP_REJECT_REASON,
  emptyBizSignup,
  type BizSignupProfile,
  type BizSignupState,
} from "@/pages/app/lib/bizSignup";
import {
  bizInvestRequests as seedInvestRequests,
  bizInvestMessages as seedDealMessages,
  bizCommissionRate,
  type BizInvestRequestItem,
  type BizDealMsg,
} from "@/mocks/dshnBizDeals";

const AUTH_PATHS = ["/login", "/register", "/otp", "/account-type"];

const SIGNUP_MONTHS = [
  "يناير",
  "فبراير",
  "مارس",
  "أبريل",
  "مايو",
  "يونيو",
  "يوليو",
  "أغسطس",
  "سبتمبر",
  "أكتوبر",
  "نوفمبر",
  "ديسمبر",
];

/** `24 أكتوبر 2025 · 09:12 م` — used for signup timestamps. */
function formatSignupStamp(date: Date): string {
  const hour = date.getHours();
  const hour12 = hour % 12 === 0 ? 12 : hour % 12;
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const suffix = hour < 12 ? "ص" : "م";
  return `${date.getDate()} ${SIGNUP_MONTHS[date.getMonth()]} ${date.getFullYear()} · ${String(hour12).padStart(2, "0")}:${minutes} ${suffix}`;
}

export interface AgreementNotice {
  id: string;
  /** Human readable deal reference shown to the platform team. */
  dealRef: string;
  investor: string;
  businessName: string;
  amount: number;
  equity: number;
  /** Expected platform commission for this deal. */
  commission: number;
  createdAt: string;
  /** The staff mailbox the collection team notification was queued to. */
  emailTo: string;
  emailSent: boolean;
}

export interface SaveProductInput {
  id?: string;
  name: string;
  description: string;
  category: string;
  negotiable: boolean;
  price: number | null;
  minOrder: number;
  stock: number;
}

export interface SaveOpportunityInput {
  category: string;
  stage: string;
  amount: number;
  equity: number;
  valuation: number;
  usage: string;
  about: string;
  coinvest: boolean;
}

interface StoreValue {
  pathname: string;
  business: MerchantBusiness;
  updateBusiness: (patch: Partial<MerchantBusiness>) => void;
  bizEditRequest: BizEditRequest | null;
  submitBizEditRequest: (patch: Partial<MerchantBusiness>) => BizEditRequest | null;
  cancelBizEditRequest: () => void;
  appScreen: ScreenId;
  appParams: NavParams;
  webScreen: WebScreen;
  webParams: WebParams;
  role: WebRole | null;
  isGuest: boolean;
  setRole: (role: WebRole | null) => void;
  logout: () => void;
  cartCount: number;
  addToCart: (qty?: number) => void;
  favorites: string[];
  toggleFavorite: (id: string) => void;
  products: MerchantProduct[];
  saveProduct: (input: SaveProductInput) => void;
  deleteProduct: (id: string) => void;
  setProductStatus: (id: string, status: MerchantProductStatus) => void;
  opportunities: MyOpportunity[];
  addOpportunity: (input: SaveOpportunityInput) => string;
  publishOpportunity: (id: string) => void;
  cancelOpportunity: (id: string) => void;
  investRequests: BizInvestRequestItem[];
  dealChats: Record<string, BizDealMsg[]>;
  acceptInvestRequest: (id: string) => void;
  rejectInvestRequest: (id: string, reason: string) => void;
  counterInvestRequest: (id: string, amount: number, equity: number) => void;
  agreeInvestRequest: (id: string) => void;
  /** Platform-side notices fired the moment a deal reaches «تم الاتفاق». */
  agreementNotices: AgreementNotice[];
  recordDeal: (id: string, value: number) => void;
  sendDealMessage: (id: string, text: string) => void;
  partnerships: BizPartnershipRow[];
  activePartnershipFor: (businessId: string) => BizPartnershipRow | null;
  partnershipById: (id: string) => BizPartnershipRow | null;
  partnerThreads: Record<string, BizPartnerMsg[]>;
  appendPartnerMessage: (
    id: string,
    input: { text?: string; type?: "text" | "file" | "image"; name?: string; size?: string; thumb?: string },
  ) => void;
  sendPartnerRequest: (biz: PartnerBusiness, message?: string) => PartnerRequestResult;
  setPartnershipStatus: (
    id: string,
    status: BizPartnershipStatus,
    opts?: { note?: string; value?: number },
  ) => void;
  approvePartnership: (id: string) => void;
  rejectPartnership: (id: string, reason: string) => void;
  submitPartnerPayment: (id: string, mode: "online" | "transfer", reference?: string) => void;
  completePartnerAdminReview: (id: string) => void;
  cancelPartnership: (id: string, reason: string) => void;
  bizSignup: BizSignupState;
  startBizSignup: (profile: BizSignupProfile) => void;
  verifyBizSignupOtp: (code: string) => { ok: boolean; error?: string };
  resendBizSignupOtp: () => void;
  approveBizSignup: () => void;
  rejectBizSignup: (reason?: string) => void;
  restartBizSignup: () => void;
  beginBizSignupSetup: () => void;
  completeBizSignupSetup: () => void;
  resetBizSignup: () => void;
  lang: WebLang;
  setLang: (lang: WebLang) => void;
  dir: "rtl" | "ltr";
  t: (key: string) => string;
  guestOpen: boolean;
  closeGuest: () => void;
  openGuest: () => void;
  returnTo: string | null;
  appNavigate: (screen: ScreenId, params?: NavParams) => void;
  appJump: (screen: ScreenId, params?: NavParams) => void;
  webNavigate: (screen: WebScreen, params?: WebParams) => void;
  webJump: (screen: WebScreen, params?: WebParams) => void;
  goBack: () => void;
  canGoBack: boolean;
  startAuth: (target: "login" | "signup") => void;
  openAuth: (role?: WebRole) => void;
  completeAuth: (role: WebRole, fallback: string) => void;
  requireAuthApp: (action?: () => void) => void;
  requireAuthWeb: (role: WebRole, action?: () => void) => void;
}

const StoreContext = createContext<StoreValue | null>(null);

export function useProductStore(): StoreValue {
  const ctx = useContext(StoreContext);
  if (!ctx) throw new Error("useProductStore must be used within ProductStoreProvider");
  return ctx;
}

export function ProductStoreProvider({ children }: { children: ReactNode }) {
  const location = useLocation();
  const routerNavigate = useNavigate();

  const [role, setRoleState] = useState<WebRole | null>(null);
  const [cartCount, setCartCount] = useState(0);
  const [favorites, setFavorites] = useState<string[]>(["biz-rim", "biz-factory"]);
  const [products, setProducts] = useState<MerchantProduct[]>(() => seedMerchantProducts.map((p) => ({ ...p })));
  const [business, setBusiness] = useState<MerchantBusiness>(() => ({ ...seedBusiness }));
  const [bizEditRequest, setBizEditRequest] = useState<BizEditRequest | null>(null);
  const [opportunities, setOpportunities] = useState<MyOpportunity[]>(() =>
    seedOpportunities.map((o) => ({ ...o })),
  );
  const [investRequests, setInvestRequests] = useState<BizInvestRequestItem[]>(() =>
    seedInvestRequests.map((r) => ({ ...r })),
  );
  const [dealChats, setDealChats] = useState<Record<string, BizDealMsg[]>>({});
  const [agreementNotices, setAgreementNotices] = useState<AgreementNotice[]>([]);
  const [partnerRequests, setPartnerRequests] = useState<BizPartnershipRow[]>([]);
  const [partnerOverrides, setPartnerOverrides] = useState<Record<string, Partial<BizPartnershipRow>>>({});
  const [partnerThreads, setPartnerThreads] = useState<Record<string, BizPartnerMsg[]>>({});
  const [bizSignup, setBizSignup] = useState<BizSignupState>(() => ({
    ...emptyBizSignup,
    profile: { ...emptyBizSignup.profile },
  }));
  const [lang, setLangState] = useState<WebLang>("ar");
  const [guestOpen, setGuestOpen] = useState(false);
  const [returnTo, setReturnTo] = useState<string | null>(null);

  const { pathname, search } = location;
  const current = pathname + search;

  const appParsed = useMemo(() => appFromPath(pathname, search), [pathname, search]);
  const webParsed = useMemo(() => webFromPath(pathname, search), [pathname, search]);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "auto" });
  }, [current]);

  const go = useCallback(
    (path: string, replace = false) => {
      routerNavigate(path, replace ? { replace: true } : undefined);
    },
    [routerNavigate],
  );

  const appNavigate = useCallback((screen: ScreenId, params: NavParams = {}) => go(appPath(screen, params)), [go]);
  const appJump = useCallback((screen: ScreenId, params: NavParams = {}) => go(appPath(screen, params), true), [go]);
  const webNavigate = useCallback((screen: WebScreen, params: WebParams = {}) => go(webPath(screen, params)), [go]);
  const webJump = useCallback((screen: WebScreen, params: WebParams = {}) => go(webPath(screen, params), true), [go]);

  const goBack = useCallback(() => {
    if (window.history.length > 1) routerNavigate(-1);
    else routerNavigate("/");
  }, [routerNavigate]);

  const setRole = useCallback((next: WebRole | null) => setRoleState(next), []);
  const logout = useCallback(() => setRoleState(null), []);

  const startAuth = useCallback(
    (target: "login" | "signup") => {
      if (!AUTH_PATHS.includes(pathname) && pathname !== "/") setReturnTo(current);
      setGuestOpen(false);
      go(target === "signup" ? "/register" : "/login");
    },
    [pathname, current, go],
  );

  const openAuth = useCallback(
    (requestedRole?: WebRole) => {
      if (requestedRole || (!AUTH_PATHS.includes(pathname) && pathname !== "/")) setReturnTo(current);
      go("/account-type");
    },
    [pathname, current, go],
  );

  const completeAuth = useCallback(
    (nextRole: WebRole, fallback: string) => {
      setRoleState(nextRole);
      setGuestOpen(false);
      const target = returnTo;
      setReturnTo(null);
      go(target ?? fallback, true);
    },
    [returnTo, go],
  );

  const requireAuthApp = useCallback(
    (action?: () => void) => {
      if (role === null) {
        // Guest action rule: any real action sends the guest to the
        // account-type selection, then returns to the same page after login.
        if (!AUTH_PATHS.includes(pathname)) setReturnTo(current);
        setGuestOpen(false);
        go("/account-type");
        return;
      }
      action?.();
    },
    [role, pathname, current, go],
  );

  const requireAuthWeb = useCallback(
    (requestedRole: WebRole, action?: () => void) => {
      if (role === null) {
        setReturnTo(current);
        void requestedRole;
        go("/account-type");
        return;
      }
      action?.();
    },
    [role, current, go],
  );

  const addToCart = useCallback((qty = 1) => setCartCount((c) => c + qty), []);

  // Business profile edits stay in sync with the shared seed object so every
  // screen that reads `myBusiness` (dashboard, public preview...) sees them.
  const updateBusiness = useCallback((patch: Partial<MerchantBusiness>) => {
    setBusiness((prev) => ({ ...prev, ...patch }));
    Object.assign(seedBusiness, patch);
  }, []);

  /** Owner edits are not applied directly: they become a pending admin request. */
  const submitBizEditRequest = useCallback(
    (patch: Partial<MerchantBusiness>): BizEditRequest | null => {
      const changes = buildBizEditChanges(business, patch);
      if (changes.length === 0) return null;
      const now = new Date();
      const request: BizEditRequest = {
        id: bizEditRequestNumber(now),
        submittedAt: now.toISOString(),
        submittedLabel: formatBizEditDate(now),
        changes,
        patch,
      };
      setBizEditRequest(request);
      return request;
    },
    [business],
  );

  const cancelBizEditRequest = useCallback(() => setBizEditRequest(null), []);

  const toggleFavorite = useCallback((id: string) => {
    setFavorites((f) => (f.includes(id) ? f.filter((x) => x !== id) : [...f, id]));
  }, []);

  // Saving a product (add or edit) publishes it directly as "نشط" (no admin review).
  const saveProduct = useCallback((input: SaveProductInput) => {
    const stamp = todayLabel();
    setProducts((list) => {
      if (input.id && list.some((p) => p.id === input.id)) {
        return list.map((p) => {
          if (p.id !== input.id) return p;
          const wasRejected = p.status === "rejected";
          const nextStatus: MerchantProductStatus =
            p.status === "hidden"
              ? "hidden"
              : input.stock > 0
                ? p.status === "out" || p.status === "rejected"
                  ? "active"
                  : p.status
                : "out";
          const history = [...(p.history ?? [])];
          if (wasRejected) {
            history.push({
              id: historyEventId(p.id, "-resubmit"),
              type: "resubmitted",
              date: stamp,
              note:
                nextStatus === "out"
                  ? "تم تعديل المنتج وإعادة إرساله للمراجعة، لكن الكمية صفر حاليًا."
                  : "تم تعديل المنتج وإعادة إرساله للمراجعة، وأصبح متاحًا للعملاء.",
            });
          } else {
            history.push({
              id: historyEventId(p.id, "-update"),
              type: "updated",
              date: stamp,
              note: "تم تحديث بيانات المنتج.",
            });
          }
          return {
            ...p,
            name: input.name,
            description: input.description,
            category: input.category,
            negotiable: input.negotiable,
            price: input.price,
            minOrder: input.minOrder,
            stock: input.stock,
            status: nextStatus,
            // Editing a rejected product resubmits it, so the old reason is cleared.
            rejectReason: wasRejected ? undefined : p.rejectReason,
            rejectedDate: wasRejected ? undefined : p.rejectedDate,
            history,
          };
        });
      }
      const id = `mp-new-${Date.now()}`;
      const created: MerchantProduct = {
        id,
        name: input.name,
        description: input.description,
        category: input.category,
        negotiable: input.negotiable,
        price: input.price,
        minOrder: input.minOrder,
        stock: input.stock,
        status: input.stock > 0 ? "active" : "out",
        createdAt: stamp,
        history: [
          { id: `${id}-h-created`, type: "created", date: stamp },
          {
            id: `${id}-h-published`,
            type: "published",
            date: stamp,
            note: input.stock > 0 ? "المنتج متاح الآن للعملاء." : "الكمية صفر، سيظهر للعملاء كنفد المخزون.",
          },
        ],
        image:
          "https://readdy.ai/api/search-image?query=Minimal%20product%20placeholder%20on%20soft%20cream%20studio%20background%20with%20subtle%20shadow%2C%20clean%20premium%20composition%2C%20warm%20natural%20light%2C%20editorial%20photography&width=500&height=500&seq=dshn-prod-new-upload&orientation=squarish",
      };
      return [created, ...list];
    });
  }, []);

  const deleteProduct = useCallback((id: string) => {
    setProducts((list) => list.filter((p) => p.id !== id));
  }, []);

  // A rejected product can never be toggled live/hidden: it must be edited
  // and resubmitted first, so any status change on it is ignored.
  const setProductStatus = useCallback((id: string, status: MerchantProductStatus) => {
    const stamp = todayLabel();
    setProducts((list) =>
      list.map((p) => {
        if (p.id !== id || p.status === "rejected") return p;
        const history = [...(p.history ?? [])];
        if (status === "hidden") {
          history.push({
            id: historyEventId(id, "-hidden"),
            type: "hidden",
            date: stamp,
            note: "تم إخفاء المنتج من المتجر ولن يظهر للعملاء.",
          });
        } else if (p.status === "hidden") {
          history.push({
            id: historyEventId(id, "-shown"),
            type: "shown",
            date: stamp,
            note: "تم إظهار المنتج مرة أخرى في المتجر.",
          });
        }
        return { ...p, status, history };
      }),
    );
  }, []);

  const addOpportunity = useCallback((input: SaveOpportunityInput) => {
    const id = `op-new-${Date.now()}`;
    setOpportunities((list) => [
      {
        id,
        investAmount: input.amount,
        equity: input.equity,
        valuation: input.valuation,
        usage: input.usage,
        stage: input.stage,
        category: input.category,
        about: input.about,
        coinvest: input.coinvest,
        status: "review",
      },
      ...list,
    ]);
    return id;
  }, []);

  const publishOpportunity = useCallback((id: string) => {
    setOpportunities((list) =>
      list.map((o) =>
        o.id === id
          ? {
              ...o,
              status: "published",
              publishedDate: "22 أكتوبر 2025",
              endDate: "31 ديسمبر 2025",
              target: o.investAmount,
              collected: o.collected ?? 0,
            }
          : o,
      ),
    );
  }, []);

  const cancelOpportunity = useCallback((id: string) => {
    setOpportunities((list) => list.map((o) => (o.id === id ? { ...o, status: "cancelled" } : o)));
  }, []);

  /** Append a message to a deal conversation, seeding it on first use. */
  const pushDealMsg = useCallback((id: string, msg: BizDealMsg) => {
    setDealChats((map) => {
      const base = map[id] ?? seedDealMessages.map((m) => ({ ...m }));
      return { ...map, [id]: [...base, msg] };
    });
  }, []);

  const acceptInvestRequest = useCallback(
    (id: string) => {
      setInvestRequests((list) =>
        list.map((r) => (r.id === id && r.status === "new" ? { ...r, status: "talking" } : r)),
      );
      pushDealMsg(id, {
        id: `sys-${Date.now()}`,
        from: "system",
        type: "system",
        text: "تم القبول المبدئي لطلب الاستثمار، يمكنك بدء التواصل مع المستثمر",
        time: "الآن",
      });
    },
    [pushDealMsg],
  );

  const rejectInvestRequest = useCallback((id: string, reason: string) => {
    setInvestRequests((list) =>
      list.map((r) => (r.id === id ? { ...r, status: "rejected", rejectReason: reason } : r)),
    );
  }, []);

  const counterInvestRequest = useCallback(
    (id: string, amount: number, equity: number) => {
      setInvestRequests((list) =>
        list.map((r) =>
          r.id === id
            ? { ...r, status: "negotiating", counterAmount: amount, counterEquity: equity }
            : r,
        ),
      );
      pushDealMsg(id, {
        id: `sys-${Date.now()}`,
        from: "me",
        type: "text",
        text: `عرض مقابل: ${amount.toLocaleString("en-US")} ر.س مقابل ${equity}% من المنشأة`,
        time: "الآن",
      });
    },
    [pushDealMsg],
  );

  const agreeInvestRequest = useCallback(
    (id: string) => {
      setInvestRequests((list) => list.map((r) => (r.id === id ? { ...r, status: "agreed" } : r)));
      pushDealMsg(id, {
        id: `sys-${Date.now()}`,
        from: "system",
        type: "system",
        text: "تم الاتفاق على شروط الصفقة، الخطوة التالية تسجيل قيمة الصفقة",
        time: "الآن",
      });

      // Trigger: every deal that reaches «تم الاتفاق» notifies the platform
      // team immediately (dashboard notice + collection staff email) with the
      // deal reference, both parties and the expected commission.
      const deal = investRequests.find((r) => r.id === id);
      if (deal) {
        const value = deal.counterAmount ?? deal.amount;
        const equity = deal.counterEquity ?? deal.equity;
        setAgreementNotices((list) => [
          {
            id: `agr-${Date.now()}`,
            dealRef: `DEAL-${deal.id.toUpperCase()}`,
            investor: deal.investor,
            businessName: business.name,
            amount: value,
            equity,
            commission: Math.round(value * (bizCommissionRate / 100)),
            createdAt: formatSignupStamp(new Date()),
            emailTo: "collections@dshn.sa",
            emailSent: true,
          },
          ...list,
        ]);
      }
    },
    [pushDealMsg, investRequests, business.name],
  );

  const recordDeal = useCallback((id: string, value: number) => {
    setInvestRequests((list) =>
      list.map((r) =>
        r.id === id
          ? {
              ...r,
              status: "registered",
              dealValue: value,
              commission: Math.round(value * (bizCommissionRate / 100)),
            }
          : r,
      ),
    );
  }, []);

  const sendDealMessage = useCallback(
    (id: string, text: string) => {
      const trimmed = text.trim();
      if (!trimmed) return;
      pushDealMsg(id, {
        id: `m-${Date.now()}`,
        from: "me",
        type: "text",
        text: trimmed,
        time: "الآن",
      });
    },
    [pushDealMsg],
  );

  const partnerships = useMemo(
    () =>
      [...partnerRequests, ...seedPartnerships].map((row) =>
        partnerOverrides[row.id] ? { ...row, ...partnerOverrides[row.id] } : row,
      ),
    [partnerRequests, partnerOverrides],
  );

  const partnershipById = useCallback(
    (id: string) => partnerships.find((p) => p.id === id) ?? null,
    [partnerships],
  );

  /** Any live partnership (including rejected/cancelled resets) for an explored business. */
  const activePartnershipFor = useCallback(
    (businessId: string) =>
      partnerships.find((p) => partnershipBusinessId(p) === businessId && isOpenPartnership(p)) ?? null,
    [partnerships],
  );

  /** Create a "قيد التفاوض" partnership request — never a duplicate one. */
  const sendPartnerRequest = useCallback(
    (biz: PartnerBusiness, message?: string): PartnerRequestResult => {
      const existing = partnerships.find(
        (p) => partnershipBusinessId(p) === biz.id && isOpenPartnership(p),
      );
      if (existing) return { ok: false, existing };
      const now = new Date();
      const row = buildPartnerRequestRow(biz, nextPartnershipNumber(partnerships), now);
      setPartnerRequests((list) => [row, ...list]);
      const thread: BizPartnerMsg[] = [
        {
          id: `sys-${now.getTime()}`,
          from: "system",
          type: "system",
          text: `تم إنشاء طلب الشراكة مع ${biz.name} — قيد التفاوض`,
          time: "الآن",
        },
      ];
      const trimmed = message?.trim();
      if (trimmed) {
        thread.push({
          id: `msg-${now.getTime()}`,
          from: "me",
          type: "text",
          text: trimmed,
          time: "الآن",
        });
      }
      setPartnerThreads((map) => ({ ...map, [row.id]: thread }));
      return { ok: true, row };
    },
    [partnerships],
  );

  /** Append a message the owner typed (or attached) to a partnership conversation. */
  const appendPartnerMessage = useCallback(
    (
      id: string,
      input: { text?: string; type?: "text" | "file" | "image"; name?: string; size?: string; thumb?: string },
    ) => {
      const kind = input.type ?? "text";
      const body = input.text?.trim() ?? "";
      if (kind === "text" && !body) return;
      const stamp = Date.now();
      const uid = `${stamp}-${Math.random().toString(36).slice(2, 8)}`;
      const msg: BizPartnerMsg =
        kind === "text"
          ? { id: `pm-${uid}`, from: "me", type: "text", text: body, time: "الآن" }
          : {
              id: `pm-${uid}`,
              from: "me",
              type: kind,
              text: input.name ?? "مرفق",
              size: input.size,
              thumb: input.thumb,
              time: "الآن",
            };
      setPartnerThreads((map) => ({ ...map, [id]: [...(map[id] ?? []), msg] }));
    },
    [],
  );

  /** Append a system line to a partnership conversation (if any). */
  const pushPartnerSystemMsg = useCallback((id: string, text: string) => {
    setPartnerThreads((map) => {
      const base = map[id] ?? [];
      return {
        ...map,
        [id]: [
          ...base,
          {
            id: `sys-${Date.now()}-${base.length}`,
            from: "system",
            type: "system",
            text,
            time: "الآن",
          },
        ],
      };
    });
  }, []);

  /** Move a partnership to a new status, keeping label/tone + note in sync. */
  const setPartnershipStatus = useCallback(
    (
      id: string,
      status: BizPartnershipStatus,
      opts?: { note?: string; value?: number },
    ) => {
      const patch: Partial<BizPartnershipRow> = {
        status,
        statusLabel: partnerStatusLabel(status),
        statusTone: partnerStatusTone(status),
        updatedAt: partnerRequestStamp(new Date()),
      };
      if (typeof opts?.value === "number") patch.value = opts.value;
      if (opts?.note) patch.note = opts.note;
      setPartnerOverrides((map) => ({ ...map, [id]: { ...(map[id] ?? {}), ...patch } }));
      if (opts?.note) pushPartnerSystemMsg(id, opts.note);
    },
    [pushPartnerSystemMsg],
  );

  /** The other party accepts the contract → partnership moves to "قيد الدفع". */
  const approvePartnership = useCallback(
    (id: string) => {
      setPartnershipStatus(id, "paying", {
        note: "تمت الموافقة على عقد الشراكة — بانتظار سداد قيمة الشراكة",
      });
    },
    [setPartnershipStatus],
  );

  /** The other party rejects the contract with a reason. */
  const rejectPartnership = useCallback(
    (id: string, reason: string) => {
      const clean = reason.trim();
      setPartnershipStatus(id, "rejected", {
        note: clean ? `تم رفض عقد الشراكة — السبب: ${clean}` : "تم رفض عقد الشراكة",
      });
    },
    [setPartnershipStatus],
  );

  /**
   * Requester pays: online payment activates the partnership immediately,
   * while a bank transfer stays pending until the platform reviews the proof.
   */
  const submitPartnerPayment = useCallback(
    (id: string, mode: "online" | "transfer", reference?: string) => {
      if (mode === "online") {
        setPartnershipStatus(id, "current", {
          note: "تم سداد قيمة الشراكة إلكترونيًا — الشراكة سارية الآن",
        });
        return;
      }
      const ref = reference?.trim();
      setPartnershipStatus(id, "pendingAdmin", {
        note: ref
          ? `تم رفع إثبات التحويل (مرجع ${ref}) — بانتظار مراجعة الإدارة`
          : "تم رفع إثبات التحويل — بانتظار مراجعة الإدارة",
      });
    },
    [setPartnershipStatus],
  );

  /** Platform review approves the uploaded payment proof. */
  const completePartnerAdminReview = useCallback(
    (id: string) => {
      setPartnershipStatus(id, "current", {
        note: "اعتمدت الإدارة الدفعة — أصبحت الشراكة سارية",
      });
    },
    [setPartnershipStatus],
  );

  /** Either side cancels the partnership request. */
  const cancelPartnership = useCallback(
    (id: string, reason: string) => {
      const clean = reason.trim();
      setPartnershipStatus(id, "cancelled", {
        note: clean ? `تم إلغاء طلب الشراكة — السبب: ${clean}` : "تم إلغاء طلب الشراكة",
      });
    },
    [setPartnershipStatus],
  );

  /* ---------------- Business-owner signup lifecycle ---------------- */

  /** 1) Owner submits the registration form → account waits for phone OTP. */
  const startBizSignup = useCallback((profile: BizSignupProfile) => {
    setBizSignup((prev) => ({
      ...prev,
      status: "otp",
      profile: { ...profile },
      rejectReason: "",
      approvedAt: "",
      completedAt: "",
      otpAttempts: 0,
      submittedAt: "",
    }));
  }, []);

  /** 2) Phone verification → the request moves to admin review. */
  const verifyBizSignupOtp = useCallback((code: string) => {
    const clean = code.replace(/\D/g, "");
    if (clean.length !== 4) {
      return { ok: false, error: "أدخل رمز التحقق المكوّن من 4 أرقام." };
    }
    if (clean !== BIZ_SIGNUP_DEMO_CODE) {
      setBizSignup((prev) => ({
        ...prev,
        otpAttempts: prev.otpAttempts + 1,
      }));
      return { ok: false, error: "الرمز غير صحيح. تأكد من الأرقام المرسلة إلى جوالك." };
    }
    const now = new Date();
    setBizSignup((prev) => ({
      ...prev,
      status: "review",
      otpAttempts: 0,
      submittedAt: formatSignupStamp(now),
    }));
    return { ok: true };
  }, []);

  const resendBizSignupOtp = useCallback(() => {
    setBizSignup((prev) => ({ ...prev, resendCount: prev.resendCount + 1, otpAttempts: 0 }));
  }, []);

  /** Admin accepts the registration. */
  const approveBizSignup = useCallback(() => {
    setBizSignup((prev) => ({
      ...prev,
      status: "approved",
      rejectReason: "",
      approvedAt: formatSignupStamp(new Date()),
    }));
  }, []);

  /** Admin rejects the registration with a reason the owner can see. */
  const rejectBizSignup = useCallback((reason?: string) => {
    setBizSignup((prev) => ({
      ...prev,
      status: "rejected",
      rejectReason: reason?.trim() ? reason.trim() : BIZ_SIGNUP_REJECT_REASON,
    }));
  }, []);

  /** Owner edits the data and resubmits after a rejection. */
  const restartBizSignup = useCallback(() => {
    setBizSignup((prev) => ({
      ...prev,
      status: "form",
      rejectReason: "",
      otpAttempts: 0,
      resendCount: 0,
      submittedAt: "",
      approvedAt: "",
      completedAt: "",
    }));
  }, []);

  /** 3) Owner starts the business setup → status shows "إعداد المنشأة". */
  const beginBizSignupSetup = useCallback(() => {
    setBizSignup((prev) => (prev.status === "approved" ? { ...prev, status: "setup" } : prev));
  }, []);

  /** 4) Business setup finished → account is fully ready. */
  const completeBizSignupSetup = useCallback(() => {
    setBizSignup((prev) => ({
      ...prev,
      status: "done",
      completedAt: formatSignupStamp(new Date()),
    }));
  }, []);

  const resetBizSignup = useCallback(() => {
    setBizSignup({ ...emptyBizSignup, profile: { ...emptyBizSignup.profile } });
  }, []);

  const setLang = useCallback((next: WebLang) => setLangState(next), []);
  const closeGuest = useCallback(() => setGuestOpen(false), []);
  const openGuest = useCallback(() => setGuestOpen(true), []);

  const dir: "rtl" | "ltr" = lang === "ar" ? "rtl" : "ltr";
  const t = useCallback((key: string) => webStrings[lang][key] ?? webStrings.ar[key] ?? key, [lang]);

  const value = useMemo<StoreValue>(
    () => ({
      pathname,
      business,
      updateBusiness,
      bizEditRequest,
      submitBizEditRequest,
      cancelBizEditRequest,
      appScreen: appParsed.screen,
      appParams: appParsed.params,
      webScreen: webParsed.screen,
      webParams: webParsed.params,
      role,
      isGuest: role === null,
      setRole,
      logout,
      cartCount,
      addToCart,
      favorites,
      toggleFavorite,
      products,
      saveProduct,
      deleteProduct,
      setProductStatus,
      opportunities,
      addOpportunity,
      publishOpportunity,
      cancelOpportunity,
      investRequests,
      dealChats,
      acceptInvestRequest,
      rejectInvestRequest,
      counterInvestRequest,
      agreeInvestRequest,
      agreementNotices,
      recordDeal,
      sendDealMessage,
      partnerships,
      activePartnershipFor,
      partnershipById,
      partnerThreads,
      appendPartnerMessage,
      sendPartnerRequest,
      setPartnershipStatus,
      approvePartnership,
      rejectPartnership,
      submitPartnerPayment,
      completePartnerAdminReview,
      cancelPartnership,
      bizSignup,
      startBizSignup,
      verifyBizSignupOtp,
      resendBizSignupOtp,
      approveBizSignup,
      rejectBizSignup,
      restartBizSignup,
      beginBizSignupSetup,
      completeBizSignupSetup,
      resetBizSignup,
      lang,
      setLang,
      dir,
      t,
      guestOpen,
      closeGuest,
      openGuest,
      returnTo,
      appNavigate,
      appJump,
      webNavigate,
      webJump,
      goBack,
      canGoBack: true,
      startAuth,
      openAuth,
      completeAuth,
      requireAuthApp,
      requireAuthWeb,
    }),
    [
      pathname,
      business,
      updateBusiness,
      bizEditRequest,
      submitBizEditRequest,
      cancelBizEditRequest,
      appParsed,
      webParsed,
      role,
      setRole,
      logout,
      cartCount,
      addToCart,
      favorites,
      toggleFavorite,
      products,
      saveProduct,
      deleteProduct,
      setProductStatus,
      opportunities,
      addOpportunity,
      publishOpportunity,
      cancelOpportunity,
      investRequests,
      dealChats,
      acceptInvestRequest,
      rejectInvestRequest,
      counterInvestRequest,
      agreeInvestRequest,
      agreementNotices,
      recordDeal,
      sendDealMessage,
      partnerships,
      activePartnershipFor,
      partnershipById,
      partnerThreads,
      appendPartnerMessage,
      sendPartnerRequest,
      setPartnershipStatus,
      approvePartnership,
      rejectPartnership,
      submitPartnerPayment,
      completePartnerAdminReview,
      cancelPartnership,
      bizSignup,
      startBizSignup,
      verifyBizSignupOtp,
      resendBizSignupOtp,
      approveBizSignup,
      rejectBizSignup,
      restartBizSignup,
      beginBizSignupSetup,
      completeBizSignupSetup,
      resetBizSignup,
      lang,
      setLang,
      dir,
      t,
      guestOpen,
      closeGuest,
      openGuest,
      returnTo,
      appNavigate,
      appJump,
      webNavigate,
      webJump,
      goBack,
      startAuth,
      openAuth,
      completeAuth,
      requireAuthApp,
      requireAuthWeb,
    ],
  );

  return <StoreContext.Provider value={value}>{children}</StoreContext.Provider>;
}