"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "./ui";

/** Fetch a Platform API resource with reload; keeps previous data while refetching. */
export function useApi<T = any>(path: string | null, deps: unknown[] = []) {
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(!!path);
  const seq = useRef(0);
  const load = useCallback(async () => {
    if (!path) return;
    const n = ++seq.current;
    setLoading(true);
    try {
      const r = await api<T>(path);
      if (n === seq.current) { setData(r); setError(null); }
    } catch (e) {
      if (n === seq.current) setError((e as Error).message);
    } finally {
      if (n === seq.current) setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [path, ...deps]);
  useEffect(() => { load(); }, [load]);
  return { data, error, loading, reload: load, setData };
}

export type ClientIndustry = { key: string; label: string; group?: string; visit: string; visitPlural: string; briefExample: string; kbHint: string; offering: string; projectLabel: string; regulated?: boolean };
const DEFAULT_INDUSTRY: ClientIndustry = { key: "general", label: "General / other", visit: "Appointment", visitPlural: "Appointments", briefExample: "Product, audience, offer and proof points", kbHint: "prices, offers, opening hours, locations and FAQs", offering: "product or service", projectLabel: "Interest" };
/** Workspace industry wording (labels for the booked step, examples). Falls back to neutral wording while loading. */
export function useIndustry(): ClientIndustry {
  const t = useApi<{ industry?: ClientIndustry }>("/team");
  return t.data?.industry ?? DEFAULT_INDUSTRY;
}

export function useDebounced<T>(value: T, ms = 250) {
  const [v, setV] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setV(value), ms);
    return () => clearTimeout(t);
  }, [value, ms]);
  return v;
}

export const money = (minor: number | null | undefined, currency = "BDT") => {
  if (minor == null) return "—";
  const v = minor / 100;
  try {
    return new Intl.NumberFormat(currency === "BDT" ? "en-BD" : "en-US", { style: "currency", currency, maximumFractionDigits: Math.abs(v) >= 1000 ? 0 : 2 }).format(v);
  } catch {
    return `${currency} ${v.toFixed(0)}`;
  }
};
/** Compact money for stat tiles: ৳13.7 L / ৳2.15 Cr for BDT, $1.2M otherwise */
export const moneyShort = (minor: number | null | undefined, currency = "BDT") => {
  if (minor == null) return "—";
  const v = minor / 100;
  if (currency === "BDT") return Math.abs(v) >= 1e7 ? `৳${(v / 1e7).toFixed(2)} Cr` : Math.abs(v) >= 1e5 ? `৳${(v / 1e5).toFixed(1)} L` : `৳${new Intl.NumberFormat("en-IN").format(Math.round(v))}`;
  return new Intl.NumberFormat("en-US", { style: "currency", currency, notation: Math.abs(v) >= 1e5 ? "compact" : "standard", maximumFractionDigits: Math.abs(v) >= 1e5 ? 1 : 0 }).format(v);
};
export const compact = (n: number | null | undefined) => (n == null ? "—" : new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(n));
export const fmtDate = (d: string | Date | null | undefined, tz?: string, withTime = true) => {
  if (!d) return "—";
  return new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", ...(withTime ? { timeStyle: "short" } : {}), ...(tz ? { timeZone: tz } : {}) }).format(new Date(d));
};
export const ago = (d: string | Date | null | undefined) => {
  if (!d) return "—";
  const ms = Date.now() - new Date(d).getTime();
  const fut = ms < 0;
  const m = Math.round(Math.abs(ms) / 60000);
  const s = m < 1 ? "now" : m < 60 ? `${m}m` : m < 1440 ? `${Math.round(m / 60)}h` : `${Math.round(m / 1440)}d`;
  return s === "now" ? "just now" : fut ? `in ${s}` : `${s} ago`;
};
export const CHANNEL_TONE: Record<string, string> = { whatsapp: "green", email: "blue", sms: "amber", messenger: "violet", instagram: "red" };
export const SOURCE_LABEL: Record<string, string> = { meta_lead_ad: "Meta Lead Ad", google_lead_form: "Google lead form", web_form: "Web form", whatsapp: "WhatsApp", messenger: "Messenger", call: "Call", api: "API", import: "Import", website: "Website", tiktok: "TikTok", linkedin: "LinkedIn", manual: "Manual" };
