"use client";
import "./crm-extra.css";
import Link from "next/link";
import { FormEvent, useCallback, useEffect, useState } from "react";
import {
  Activity,
  ArrowLeft,
  ArrowRight,
  BriefcaseBusiness,
  Building2,
  CheckCircle2,
  CircleDollarSign,
  Clock3,
  ContactRound,
  Download,
  FileUp,
  Filter,
  Languages,
  ListTodo,
  Mail,
  MessageCircle,
  MoreHorizontal,
  Phone,
  Plus,
  RefreshCw,
  Save,
  Search,
  Tag,
  UserRound,
  Users,
  X,
} from "lucide-react";
import { Toaster, toast } from "sonner";
type Row = Record<string, unknown>;
type Section =
  | "contacts"
  | "companies"
  | "leads"
  | "deals"
  | "pipelines"
  | "tasks"
  | "activities"
  | "reports";
type Data = {
  workspace: Row;
  permissions: string[];
  user: { id: string; name: string };
  summary: Row;
  pipelineId?: string;
  pipelines: Row[];
  stages: Row[];
  members: Row[];
  savedViews: Row[];
  contactOptions: Row[];
  records: Row[];
  detail?: {
    contact: Row;
    conversations: Row[];
    leads: Row[];
    deals: Row[];
    tasks: Row[];
    activities: Row[];
    notes: Row[];
  };
};
const labels = {
  ar: {
    unknown: "غير مسجل",
    title: "العملاء والمبيعات",
    sub: "إدارة العلاقة من أول محادثة حتى إغلاق الصفقة",
    contacts: "العملاء",
    companies: "الشركات",
    leads: "Leads",
    deals: "الصفقات",
    pipelines: "مسار المبيعات",
    tasks: "المهام",
    activities: "الأنشطة",
    reports: "التقارير",
    search: "ابحث بالاسم أو الهاتف أو البريد أو الصفقة",
    add: "إضافة",
    export: "تصدير",
    import: "استيراد CSV",
    empty: "لا توجد سجلات بعد",
    retry: "إعادة المحاولة",
    total: "إجمالي العملاء",
    newLeads: "Leads جديدة",
    qualified: "مؤهلة",
    openDeals: "صفقات مفتوحة",
    won: "مكتسبة",
    due: "مهام مستحقة",
    unassigned: "غير معيّنة",
    source: "المصدر",
    owner: "المسؤول",
    score: "التقييم",
    priority: "الأولوية",
    status: "الحالة",
    next: "المتابعة القادمة",
    value: "القيمة",
    customer360: "ملف العميل 360",
    timeline: "الخط الزمني",
    save: "حفظ",
    cancel: "إلغاء",
    create: "إنشاء",
    internalNote: "ملاحظة داخلية",
    addTask: "إضافة مهمة",
    createLead: "إنشاء Lead",
    back: "العودة للعملاء",
    noData: "لا توجد بيانات فعلية لهذا القسم حتى الآن.",
  },
  en: {
    unknown: "Not recorded",
    title: "Customers & sales",
    sub: "Manage every relationship from first conversation to closed deal",
    contacts: "Contacts",
    companies: "Companies",
    leads: "Leads",
    deals: "Deals",
    pipelines: "Sales pipeline",
    tasks: "Tasks",
    activities: "Activities",
    reports: "Reports",
    search: "Search names, phones, emails or deals",
    add: "Add",
    export: "Export",
    import: "Import CSV",
    empty: "No records yet",
    retry: "Retry",
    total: "Total contacts",
    newLeads: "New leads",
    qualified: "Qualified",
    openDeals: "Open deals",
    won: "Won",
    due: "Tasks due",
    unassigned: "Unassigned",
    source: "Source",
    owner: "Owner",
    score: "Score",
    priority: "Priority",
    status: "Status",
    next: "Next follow-up",
    value: "Value",
    customer360: "Customer 360",
    timeline: "Timeline",
    save: "Save",
    cancel: "Cancel",
    create: "Create",
    internalNote: "Internal note",
    addTask: "Add task",
    createLead: "Create lead",
    back: "Back to contacts",
    noData: "No real data is available for this section yet.",
  },
};
const sections: Section[] = [
  "contacts",
  "companies",
  "leads",
  "deals",
  "pipelines",
  "tasks",
  "activities",
  "reports",
];
const icons = {
  contacts: ContactRound,
  companies: Building2,
  leads: Users,
  deals: BriefcaseBusiness,
  pipelines: CircleDollarSign,
  tasks: ListTodo,
  activities: Activity,
  reports: Filter,
};
export default function CRMCenter({
  initialSection,
  initialId,
}: {
  initialSection: Section;
  initialId?: string;
}) {
  const [lang, setLang] = useState<"ar" | "en">("ar"),
    [section, setSection] = useState<Section>(initialSection),
    [q, setQ] = useState(""),
    [data, setData] = useState<Data | null>(null),
    [loading, setLoading] = useState(true),
    [error, setError] = useState(""),
    [modal, setModal] = useState<"create" | "import" | "note" | "task" | null>(
      null,
    ),
    [busy, setBusy] = useState(false),
    [detailTab, setDetailTab] = useState("overview");
  const t = labels[lang];
  const load = useCallback(async () => {
    setLoading(true);
    try {
      const p = new URLSearchParams({ section });
      if (q) p.set("q", q);
      if (initialId) p.set("id", initialId);
      const r = await fetch(`/api/crm?${p}`, { cache: "no-store" });
      const j = (await r.json()) as Data & { error?: string };
      if (!r.ok) throw new Error(j.error || "load_failed");
      setData(j);
      setError("");
    } catch (e) {
      setError(e instanceof Error ? e.message : "load_failed");
    } finally {
      setLoading(false);
    }
  }, [section, q, initialId]);
  useEffect(() => {
    const x = window.setTimeout(() => void load(), q ? 250 : 0);
    return () => window.clearTimeout(x);
  }, [load, q]);
  const post = async (body: Row) => {
    setBusy(true);
    try {
      const r = await fetch("/api/crm", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(body),
      });
      const j = (await r.json()) as Row;
      if (!r.ok) {
        if (j.error === "possible_duplicate") {
          toast.warning(
            lang === "ar"
              ? "يوجد عميل محتمل مطابق. افتح السجل الموجود قبل إنشاء نسخة جديدة."
              : "A possible duplicate exists. Review it before creating another.",
          );
          return j;
        }
        throw new Error(String(j.error || "action_failed"));
      }
      await load();
      toast.success(lang === "ar" ? "تم حفظ التغيير" : "Change saved");
      return j;
    } catch (e) {
      toast.error(lang === "ar" ? "تعذر حفظ التغيير" : "Could not save change");
      throw e;
    } finally {
      setBusy(false);
    }
  };
  const go = (s: Section) => {
    setSection(s);
    setQ("");
    const routes: Partial<Record<Section, string>> = {
      contacts: "/crm/contacts",
      leads: "/crm/leads",
      deals: "/crm/deals",
      pipelines: "/crm/pipelines",
      tasks: "/crm/tasks",
    };
    window.history.pushState({}, "", routes[s] ?? "/crm");
  };
  if (initialId)
    return (
      <Customer360
        data={data}
        lang={lang}
        t={t}
        loading={loading}
        error={error}
        retry={load}
        post={post}
        tab={detailTab}
        setTab={setDetailTab}
        setModal={setModal}
        modal={modal}
        busy={busy}
      />
    );
  const summary = [
    ["contacts", "total", ContactRound],
    ["new_leads", "newLeads", Users],
    ["qualified", "qualified", CheckCircle2],
    ["open_deals", "openDeals", BriefcaseBusiness],
    ["won_deals", "won", CircleDollarSign],
    ["tasks_due", "due", Clock3],
    ["unassigned", "unassigned", UserRound],
  ] as const;
  return (
    <main className="crm-app" dir={lang === "ar" ? "rtl" : "ltr"}>
      <Toaster richColors position={lang === "ar" ? "top-left" : "top-right"} />
      <header className="crm-top">
        <Link href="/dashboard" className="crm-brand">
          <span>N</span>
          <b>
            NEXORA <em>AI</em>
          </b>
        </Link>
        <div>
          <h1>{t.title}</h1>
          <p>{t.sub}</p>
        </div>
        <button onClick={() => setLang(lang === "ar" ? "en" : "ar")}>
          <Languages />
          {lang === "ar" ? "EN" : "ع"}
        </button>
      </header>
      <nav className="crm-tabs" aria-label={t.title}>
        {sections.map((s) => {
          const I = icons[s];
          return (
            <button
              key={s}
              className={section === s ? "active" : ""}
              onClick={() => go(s)}
            >
              <I />
              {t[s]}{" "}
            </button>
          );
        })}
      </nav>
      <section className="crm-main">
        <div className="crm-summary">
          {summary.map(([key, label, I]) => (
            <article key={key}>
              <span>
                <I />
              </span>
              <div>
                <b>
                  {Number(data?.summary?.[key] ?? 0).toLocaleString(
                    lang === "ar" ? "ar-SA" : "en-US",
                  )}
                </b>
                <small>{t[label]}</small>
              </div>
            </article>
          ))}
        </div>
        <div className="crm-toolbar">
          <label>
            <Search />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder={t.search}
            />
          </label>
          <div>
            {q && ["contacts", "companies", "leads", "deals"].includes(section) && (
              <button
                onClick={() => {
                  const name = window.prompt(
                    lang === "ar" ? "اسم العرض المحفوظ" : "Saved view name",
                  );
                  if (name)
                    void post({
                      action: "save_view",
                      name,
                      entityType: section,
                      filters: { q },
                    });
                }}
              >
                <Save />
                {lang === "ar" ? "حفظ العرض" : "Save view"}
              </button>
            )}
            <button onClick={() => setModal("create")}>
              <Plus />
              {t.add} {t[section]}
            </button>
            {section === "contacts" && (
              <button onClick={() => setModal("import")}>
                <FileUp />
                {t.import}
              </button>
            )}
            {data?.permissions.includes("crm.export") && (
              <a href={`/api/crm?section=${section}&format=csv`}>
                <Download />
                {t.export}
              </a>
            )}
          </div>
        </div>
        {data?.savedViews.filter((x) => x.entity_type === section).length ? (
          <div className="saved-views">
            {data.savedViews
              .filter((x) => x.entity_type === section)
              .map((x) => (
                <button
                  key={String(x.id)}
                  onClick={() => {
                    try {
                      const filters = JSON.parse(String(x.filters_json || "{}"));
                      setQ(String(filters.q || ""));
                    } catch {
                      setQ("");
                    }
                  }}
                >
                  {String(x.name)}
                </button>
              ))}
          </div>
        ) : null}
        <section className="crm-content">
          {loading ? (
            <Loading />
          ) : error ? (
            <Empty
              title={lang === "ar" ? "تعذر تحميل CRM" : "CRM could not load"}
              copy={error}
              action={t.retry}
              onAction={() => void load()}
            />
          ) : section === "pipelines" ? (
            <Pipeline data={data!} lang={lang} post={post} />
          ) : section === "reports" ? (
            <Reports rows={data?.records || []} lang={lang} />
          ) : data?.records.length ? (
            <Records
              section={section}
              rows={data.records}
              lang={lang}
              data={data}
              post={post}
            />
          ) : (
            <Empty
              title={t.empty}
              copy={t.noData}
              action={`${t.add} ${t[section]}`}
              onAction={() => setModal("create")}
            />
          )}
        </section>
      </section>
      {modal && (
        <Modal title={`${t.add} ${t[section]}`} close={() => setModal(null)}>
          {modal === "import" ? (
            <ImportForm
              lang={lang}
              busy={busy}
              submit={async (rows) => {
                await post({ action: "import_contacts", rows });
                setModal(null);
              }}
            />
          ) : (
            <CreateForm
              section={section}
              lang={lang}
              data={data}
              busy={busy}
              submit={async (body) => {
                await post(body);
                setModal(null);
              }}
            />
          )}
        </Modal>
      )}
    </main>
  );
}
function Records({
  section,
  rows,
  lang,
  data,
  post,
}: {
  section: Section;
  rows: Row[];
  lang: "ar" | "en";
  data: Data;
  post: (b: Row) => Promise<Row | undefined>;
}) {
  if (section === "contacts")
    return (
      <div className="contact-grid">
        {rows.map((r) => (
          <Link
            href={`/crm/contacts/${r.id}`}
            key={String(r.id)}
            className="contact-card"
          >
            <span className="contact-avatar">
              {String(r.full_name).slice(0, 1)}
            </span>
            <div>
              <h3>{String(r.full_name)}</h3>
              <p>{String(r.company || r.email || r.phone || "—")}</p>
              <small>
                <Tag />
                {String(r.source)} · {Number(r.leads_count)} Leads ·{" "}
                {Number(r.deals_count)} Deals
              </small>
            </div>
            {Arrow(lang)}
          </Link>
        ))}
      </div>
    );
  if (section === "companies")
    return (
      <div className="company-grid">
        {rows.map((r) => (
          <article key={String(r.id)}>
            <span>
              <Building2 />
            </span>
            <h3>{String(r.name)}</h3>
            <p>{String(r.industry || r.country || "—")}</p>
            <footer>
              {Number(r.contacts_count)} Contacts · {Number(r.deals_count)}{" "}
              Deals
            </footer>
          </article>
        ))}
      </div>
    );
  if (section === "leads")
    return (
      <div className="data-list leads">
        {rows.map((r) => (
          <article key={String(r.id)}>
            <span className={`priority ${r.priority}`}>{String(r.score)}</span>
            <div>
              <h3>{String(r.title)}</h3>
              <p>
                {String(r.full_name || "")} · {String(r.interest || r.source)}
              </p>
              <small>
                {String(r.stage)} · {String(r.source)} ·{" "}
                {r.next_action_at
                  ? new Date(String(r.next_action_at)).toLocaleDateString(
                      lang === "ar" ? "ar-SA" : "en-US",
                    )
                  : lang === "ar"
                    ? "لا توجد متابعة"
                    : "No follow-up"}
              </small>
            </div>
            <select
              value={String(r.stage)}
              onChange={(e) =>
                void post({
                  action: "update_lead",
                  id: r.id,
                  stage: e.target.value,
                  score: Number(r.score),
                  priority: r.priority,
                  ownerUserId: r.owner_user_id || null,
                  nextActionAt: r.next_action_at || null,
                })
              }
            >
              {[
                "new",
                "contacted",
                "qualified",
                "unqualified",
                "nurture",
                "converted",
                "lost",
              ].map((x) => (
                <option key={x}>{x}</option>
              ))}
            </select>
            {String(r.stage) === "qualified" && (
              <button
                onClick={() => {
                  const st = data.stages.find(
                    (x) =>
                      x.pipeline_id === data.pipelineId &&
                      !x.is_won &&
                      !x.is_lost,
                  );
                  if (st)
                    void post({
                      action: "convert_lead",
                      id: r.id,
                      pipelineId: data.pipelineId,
                      stageId: st.id,
                      dealName: r.title,
                      valueMinor: r.value_minor || null,
                    });
                }}
              >
                {lang === "ar" ? "تحويل لصفقة" : "Convert"}
              </button>
            )}
          </article>
        ))}
      </div>
    );
  if (section === "deals")
    return (
      <div className="data-list deals">
        {rows.map((r) => (
          <article key={String(r.id)}>
            <span style={{ background: String(r.stage_color) }}>
              <BriefcaseBusiness />
            </span>
            <div>
              <h3>{String(r.name)}</h3>
              <p>{String(r.full_name || r.company_name || "—")}</p>
              <small>
                {String(lang === "ar" ? r.stage_ar : r.stage_en)} ·{" "}
                {r.value_minor == null
                  ? lang === "ar"
                    ? "بلا قيمة مسجلة"
                    : "No recorded value"
                  : `${(Number(r.value_minor) / 100).toLocaleString()} ${r.currency}`}
              </small>
            </div>
          </article>
        ))}
      </div>
    );
  if (section === "tasks")
    return (
      <div className="data-list tasks">
        {rows.map((r) => (
          <article key={String(r.id)}>
            <span>
              <ListTodo />
            </span>
            <div>
              <h3>{String(r.title)}</h3>
              <p>
                {String(r.kind)} · {String(r.priority)}
              </p>
              <small>
                {r.due_at
                  ? new Date(String(r.due_at)).toLocaleString(
                      lang === "ar" ? "ar-SA" : "en-US",
                    )
                  : lang === "ar"
                    ? "بدون موعد"
                    : "No due date"}
              </small>
            </div>
            <b className={r.status === "completed" ? "done" : ""}>
              {String(r.status)}
            </b>
          </article>
        ))}
      </div>
    );
  return (
    <div className="timeline">
      {rows.map((r) => (
        <article key={String(r.id)}>
          <span>
            <Activity />
          </span>
          <div>
            <h3>{String(r.title)}</h3>
            <p>
              {String(r.kind)} ·{" "}
              {new Date(String(r.created_at)).toLocaleString(
                lang === "ar" ? "ar-SA" : "en-US",
              )}
            </p>
          </div>
        </article>
      ))}
    </div>
  );
}
function Pipeline({
  data,
  lang,
  post,
}: {
  data: Data;
  lang: string;
  post: (b: Row) => Promise<Row | undefined>;
}) {
  const stages = data.stages.filter((x) => x.pipeline_id === data.pipelineId);
  return (
    <div
      className="pipeline"
      role="region"
      aria-label={lang === "ar" ? "مسار المبيعات" : "Sales pipeline"}
    >
      {data.permissions.includes("crm.pipeline.manage") && data.pipelineId && (
        <div className="pipeline-admin">
          <button
            onClick={() => {
              const nameAr = window.prompt("اسم المرحلة بالعربية");
              if (!nameAr) return;
              const nameEn = window.prompt("Stage name in English", nameAr);
              if (!nameEn) return;
              void post({
                action: "add_stage",
                pipelineId: data.pipelineId,
                nameAr,
                nameEn,
                color: "#6754d9",
                probability: 50,
              });
            }}
          >
            <Plus />
            {lang === "ar" ? "إضافة مرحلة" : "Add stage"}
          </button>
        </div>
      )}
      {stages.map((s) => {
        const deals = data.records.filter((d) => d.stage_id === s.id);
        const value = deals.reduce((n, d) => n + Number(d.value_minor || 0), 0);
        return (
          <section
            key={String(s.id)}
            onDragOver={(e) => e.preventDefault()}
            onDrop={(e) => {
              const raw = e.dataTransfer.getData("application/json");
              if (!raw) return;
              const d = JSON.parse(raw);
              let lostReason = null;
              if (s.is_lost)
                lostReason = window.prompt(
                  lang === "ar" ? "سبب خسارة الصفقة" : "Lost reason",
                );
              if (s.is_lost && !lostReason) return;
              void post({
                action: "move_deal",
                id: d.id,
                stageId: s.id,
                version: d.version,
                lostReason,
              });
            }}
          >
            <header>
              <i style={{ background: String(s.color) }} />
              <h2>{String(lang === "ar" ? s.name_ar : s.name_en)}</h2>
              <b>{deals.length}</b>
            </header>
            <p>
              {value
                ? `${(value / 100).toLocaleString()} SAR`
                : lang === "ar"
                  ? "لا توجد قيمة مسجلة"
                  : "No recorded value"}
            </p>
            <div>
              {deals.map((d) => (
                <article
                  draggable
                  onDragStart={(e) =>
                    e.dataTransfer.setData(
                      "application/json",
                      JSON.stringify({
                        id: d.id,
                        version: Number(d.lock_version),
                      }),
                    )
                  }
                  key={String(d.id)}
                >
                  <h3>{String(d.name)}</h3>
                  <p>{String(d.full_name || d.company_name || "—")}</p>
                  <footer>
                    {d.value_minor == null
                      ? "—"
                      : `${(Number(d.value_minor) / 100).toLocaleString()} ${d.currency}`}
                    <MoreHorizontal />
                  </footer>
                  <label className="mobile-stage">
                    <span>{lang === "ar" ? "نقل إلى" : "Move to"}</span>
                    <select
                      value={String(d.stage_id)}
                      onChange={(e) => {
                        const target = stages.find((x) => x.id === e.target.value);
                        let lostReason = null;
                        if (target?.is_lost)
                          lostReason = window.prompt(
                            lang === "ar" ? "سبب خسارة الصفقة" : "Lost reason",
                          );
                        if (target?.is_lost && !lostReason) return;
                        void post({
                          action: "move_deal",
                          id: d.id,
                          stageId: e.target.value,
                          version: Number(d.lock_version),
                          lostReason,
                        });
                      }}
                    >
                      {stages.map((option) => (
                        <option value={String(option.id)} key={String(option.id)}>
                          {String(lang === "ar" ? option.name_ar : option.name_en)}
                        </option>
                      ))}
                    </select>
                  </label>
                </article>
              ))}
              {!deals.length && (
                <small>
                  {lang === "ar" ? "اسحب صفقة إلى هنا" : "Drop a deal here"}
                </small>
              )}
            </div>
          </section>
        );
      })}
    </div>
  );
}
function Reports({ rows, lang }: { rows: Row[]; lang: string }) {
  const max = Math.max(1, ...rows.map((r) => Number(r.leads)));
  return (
    <div className="reports">
      <header>
        <h2>
          {lang === "ar" ? "أداء مصادر العملاء" : "Lead source performance"}
        </h2>
        <p>
          {lang === "ar"
            ? "البيانات المعروضة مأخوذة من Leads المسجلة فعليًا."
            : "Only recorded leads are included."}
        </p>
      </header>
      {rows.length ? (
        rows.map((r) => (
          <article key={String(r.source)}>
            <div>
              <b>{String(r.source)}</b>
              <span>
                {Number(r.leads)} Leads · {Number(r.qualified)}{" "}
                {lang === "ar" ? "مؤهلة" : "qualified"}
              </span>
            </div>
            <i>
              <u style={{ width: `${(Number(r.leads) / max) * 100}%` }} />
            </i>
          </article>
        ))
      ) : (
        <Empty
          title={lang === "ar" ? "لا توجد بيانات للتقرير" : "No report data"}
          copy={
            lang === "ar"
              ? "ستظهر النتائج بعد إنشاء Leads فعلية."
              : "Results appear after real leads are created."
          }
        />
      )}
    </div>
  );
}
function Customer360({
  data,
  lang,
  t,
  loading,
  error,
  retry,
  post,
  tab,
  setTab,
  setModal,
  modal,
  busy,
}: {
  data: Data | null;
  lang: "ar" | "en";
  t: typeof labels.ar;
  loading: boolean;
  error: string;
  retry: () => Promise<void>;
  post: (b: Row) => Promise<Row | undefined>;
  tab: string;
  setTab: (x: string) => void;
  setModal: (x: "note" | "task" | null) => void;
  modal: "create" | "import" | "note" | "task" | null;
  busy: boolean;
}) {
  if (loading)
    return (
      <main className="crm-app">
        <Loading />
      </main>
    );
  if (error || !data?.detail)
    return (
      <main className="crm-app">
        <Empty
          title="Customer unavailable"
          copy={error}
          action={t.retry}
          onAction={() => void retry()}
        />
      </main>
    );
  const c = data.detail.contact,
    d = data.detail;
  const tabs = [
    "overview",
    "conversations",
    "leads",
    "deals",
    "tasks",
    "notes",
    "activity",
  ];
  return (
    <main className="crm-app customer360" dir={lang === "ar" ? "rtl" : "ltr"}>
      <Toaster richColors />
      <header className="crm-top">
        <Link href="/crm/contacts">
          {lang === "ar" ? <ArrowRight /> : <ArrowLeft />}
          {t.back}
        </Link>
        <h1>{t.customer360}</h1>
        <button>
          <Languages />
          {lang === "ar" ? "AR" : "EN"}
        </button>
      </header>
      <section className="profile-hero">
        <span className="contact-avatar large">
          {String(c.full_name).slice(0, 1)}
        </span>
        <div>
          <h2>{String(c.full_name)}</h2>
          <p>{String(c.company || c.email || c.phone || t.unknown)}</p>
          <footer>
            <b>{String(c.status)}</b>
            <span>{String(c.source)}</span>
          </footer>
        </div>
        <aside>
          <button onClick={() => setModal("task")}>
            <ListTodo />
            {t.addTask}
          </button>
          <button onClick={() => setModal("note")}>
            <MessageCircle />
            {t.internalNote}
          </button>
        </aside>
      </section>
      <nav className="detail-tabs">
        {tabs.map((x) => (
          <button
            className={tab === x ? "active" : ""}
            onClick={() => setTab(x)}
            key={x}
          >
            {x}
          </button>
        ))}
      </nav>
      <section className="detail-grid">
        <article className="detail-main">
          {tab === "overview" ? (
            <Overview d={d} lang={lang} />
          ) : tab === "conversations" ? (
            <MiniRows rows={d.conversations} kind="conversation" lang={lang} />
          ) : tab === "leads" ? (
            <MiniRows rows={d.leads} kind="lead" lang={lang} />
          ) : tab === "deals" ? (
            <MiniRows rows={d.deals} kind="deal" lang={lang} />
          ) : tab === "tasks" ? (
            <MiniRows rows={d.tasks} kind="task" lang={lang} />
          ) : tab === "notes" ? (
            <MiniRows rows={d.notes} kind="note" lang={lang} />
          ) : (
            <MiniRows rows={d.activities} kind="activity" lang={lang} />
          )}
        </article>
        <aside className="profile-side">
          <h3>{lang === "ar" ? "بيانات التواصل" : "Contact details"}</h3>
          <p>
            <Mail />
            {String(c.email || t.unknown)}
          </p>
          <p>
            <Phone />
            {String(c.phone || t.unknown)}
          </p>
          <p>
            <Building2 />
            {String(c.company || t.unknown)}
          </p>
          <p>
            <Languages />
            {String(c.language || "ar").toUpperCase()}
          </p>
          <h3>{lang === "ar" ? "ملخص العلاقة" : "Relationship summary"}</h3>
          <span>{d.conversations.length} Conversations</span>
          <span>{d.leads.length} Leads</span>
          <span>{d.deals.length} Deals</span>
          <span>
            {d.tasks.filter((x) => x.status !== "completed").length} Open tasks
          </span>
        </aside>
      </section>
      {modal && (
        <Modal
          title={modal === "task" ? t.addTask : t.internalNote}
          close={() => setModal(null)}
        >
          {modal === "note" ? (
            <SimpleNote
              busy={busy}
              submit={async (content) => {
                await post({
                  action: "add_note",
                  entityType: "contact",
                  entityId: c.id,
                  content,
                });
                setModal(null);
              }}
            />
          ) : (
            <SimpleTask
              busy={busy}
              submit={async (body) => {
                await post({
                  ...body,
                  action: "create_task",
                  relatedType: "contact",
                  relatedId: c.id,
                });
                setModal(null);
              }}
            />
          )}
        </Modal>
      )}
    </main>
  );
}
function Overview({
  d,
  lang,
}: {
  d: NonNullable<Data["detail"]>;
  lang: string;
}) {
  const events: Row[] = [
    ...d.activities.map((x) => ({ ...x, when: x.created_at })),
    ...d.conversations.map((x) => ({
      id: x.id,
      title: `${x.channel}: ${x.preview}`,
      kind: "conversation",
      when: x.updated_at,
    })),
  ].sort((a, b) => String(b.when).localeCompare(String(a.when)));
  return (
    <>
      <div className="overview-cards">
        <article>
          <Users />
          <b>{d.leads.length}</b>
          <small>Leads</small>
        </article>
        <article>
          <BriefcaseBusiness />
          <b>{d.deals.length}</b>
          <small>Deals</small>
        </article>
        <article>
          <ListTodo />
          <b>{d.tasks.filter((x) => x.status !== "completed").length}</b>
          <small>{lang === "ar" ? "مهام مفتوحة" : "Open tasks"}</small>
        </article>
        <article>
          <MessageCircle />
          <b>{d.conversations.length}</b>
          <small>{lang === "ar" ? "محادثات" : "Conversations"}</small>
        </article>
      </div>
      <h3>{lang === "ar" ? "رحلة العميل" : "Customer journey"}</h3>
      <div className="timeline">
        {events.length ? (
          events.map((x) => (
            <article key={`${x.kind}-${x.id}`}>
              <span>
                <Activity />
              </span>
              <div>
                <h3>{String(x.title)}</h3>
                <p>
                  {String(x.kind)} ·{" "}
                  {new Date(String(x.when)).toLocaleString(
                    lang === "ar" ? "ar-SA" : "en-US",
                  )}
                </p>
              </div>
            </article>
          ))
        ) : (
          <Empty
            title={lang === "ar" ? "لا توجد أنشطة بعد" : "No activity yet"}
          />
        )}
      </div>
    </>
  );
}
function MiniRows({
  rows,
  kind,
  lang,
}: {
  rows: Row[];
  kind: string;
  lang: string;
}) {
  return rows.length ? (
    <div className="mini-rows">
      {rows.map((r) => (
        <article key={String(r.id)}>
          <span>
            <Activity />
          </span>
          <div>
            <h3>
              {String(r.title || r.name || r.preview || r.content || kind)}
            </h3>
            <p>
              {String(r.stage || r.status || r.channel || r.kind || "")} ·{" "}
              {new Date(String(r.created_at || r.updated_at)).toLocaleString(
                lang === "ar" ? "ar-SA" : "en-US",
              )}
            </p>
          </div>
          {kind === "conversation" && (
            <Link href={`/inbox/${r.id}`}>
              {lang === "ar" ? "فتح" : "Open"}
            </Link>
          )}
        </article>
      ))}
    </div>
  ) : (
    <Empty title={lang === "ar" ? "لا توجد سجلات" : "No records"} />
  );
}
function CreateForm({
  section,
  lang,
  data,
  busy,
  submit,
}: {
  section: Section;
  lang: string;
  data: Data | null;
  busy: boolean;
  submit: (b: Row) => Promise<void>;
}) {
  const done = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const f = new FormData(e.currentTarget),
      v = (k: string) => String(f.get(k) || "");
    if (section === "contacts")
      return void submit({
        action: "create_contact",
        fullName: v("name"),
        email: v("email"),
        phone: v("phone"),
        company: v("company"),
        country: v("country"),
        language: v("language") || "ar",
        source: v("source") || "manual",
      });
    if (section === "companies")
      return void submit({
        action: "create_company",
        name: v("name"),
        industry: v("industry"),
        website: v("website"),
        country: v("country"),
        city: v("city"),
        size: v("size"),
      });
    if (section === "leads")
      return void submit({
        action: "create_lead",
        contactId: v("contact"),
        title: v("name"),
        interest: v("interest"),
        source: v("source") || "manual",
        score: Number(v("score") || 0),
        priority: v("priority") || "normal",
        nextActionAt: null,
      });
    if (section === "deals" || section === "pipelines") {
      const stage = data?.stages.find((x) => x.pipeline_id === data.pipelineId);
      return void submit({
        action: "create_deal",
        name: v("name"),
        contactId: v("contact") || null,
        companyId: null,
        sourceLeadId: null,
        pipelineId: data?.pipelineId,
        stageId: stage?.id,
        valueMinor: v("value") ? Math.round(Number(v("value")) * 100) : null,
        currency: "SAR",
        expectedCloseAt: null,
      });
    }
    if (section === "tasks")
      return void submit({
        action: "create_task",
        title: v("name"),
        kind: "task",
        relatedType: "contact",
        relatedId: v("contact"),
        dueAt: null,
        priority: "medium",
      });
    toast.info(
      lang === "ar"
        ? "تُدار إعدادات هذا القسم من صلاحيات المدير."
        : "This section is managed from admin settings.",
    );
  };
  const needsContact = ["leads", "deals", "pipelines", "tasks"].includes(
    section,
  );
  return (
    <form className="crm-form" onSubmit={done}>
      <label>
        {lang === "ar" ? "الاسم أو العنوان" : "Name or title"}
        <input name="name" required minLength={2} />
      </label>
      {section === "contacts" && (
        <>
          <label>
            Email
            <input name="email" type="email" />
          </label>
          <label>
            {lang === "ar" ? "الجوال" : "Phone"}
            <input name="phone" dir="ltr" />
          </label>
          <label>
            {lang === "ar" ? "الشركة" : "Company"}
            <input name="company" />
          </label>
          <label>
            {lang === "ar" ? "الدولة" : "Country"}
            <input name="country" />
          </label>
          <label>
            {lang === "ar" ? "اللغة" : "Language"}
            <select name="language">
              <option value="ar">العربية</option>
              <option value="en">English</option>
            </select>
          </label>
          <label>
            {lang === "ar" ? "المصدر" : "Source"}
            <select name="source">
              <option value="manual">Manual</option>
              <option value="website">Website</option>
              <option value="webchat">Web Chat</option>
              <option value="whatsapp">WhatsApp</option>
              <option value="referral">Referral</option>
            </select>
          </label>
        </>
      )}
      {section === "companies" && (
        <>
          <label>
            Industry
            <input name="industry" />
          </label>
          <label>
            Website
            <input name="website" type="url" />
          </label>
          <label>
            Country
            <input name="country" />
          </label>
          <label>
            City
            <input name="city" />
          </label>
          <label>
            Size
            <input name="size" />
          </label>
        </>
      )}
      {needsContact && (
        <label>
          {lang === "ar" ? "العميل" : "Contact"}
          <select name="contact" required>
            <option value="">—</option>
            {data?.contactOptions.map((x) => (
              <option value={String(x.id)} key={String(x.id)}>
                {String(x.full_name)}
              </option>
            ))}
          </select>
        </label>
      )}
      {section === "leads" && (
        <>
          <label>
            Interest
            <input name="interest" />
          </label>
          <label>
            Score
            <input
              name="score"
              type="number"
              min="0"
              max="100"
              defaultValue="0"
            />
          </label>
          <label>
            Priority
            <select name="priority">
              <option>normal</option>
              <option>high</option>
              <option>urgent</option>
              <option>low</option>
            </select>
          </label>
          <label>
            Source
            <input name="source" defaultValue="manual" />
          </label>
        </>
      )}
      {(section === "deals" || section === "pipelines") && (
        <label>
          {lang === "ar" ? "القيمة (ر.س)" : "Value (SAR)"}
          <input name="value" type="number" min="0" step="0.01" />
        </label>
      )}
      <footer>
        <button type="submit" disabled={busy}>
          {lang === "ar" ? "حفظ" : "Save"}
        </button>
      </footer>
    </form>
  );
}
function ImportForm({
  lang,
  busy,
  submit,
}: {
  lang: string;
  busy: boolean;
  submit: (r: Row[]) => Promise<void>;
}) {
  const [rows, setRows] = useState<Row[]>([]);
  return (
    <div className="import-form">
      <p>
        {lang === "ar"
          ? "ارفع CSV بالأعمدة: fullName,email,phone,company,country. ستُراجع التكرارات قبل الإضافة."
          : "Upload CSV columns: fullName,email,phone,company,country. Duplicates are checked first."}
      </p>
      <input
        type="file"
        accept=".csv,text/csv"
        onChange={async (e) => {
          const file = e.target.files?.[0];
          if (!file) return;
          const lines = (await file.text()).split(/\r?\n/).filter(Boolean),
            heads =
              lines
                .shift()
                ?.split(",")
                .map((x) => x.trim()) || [];
          setRows(
            lines.slice(0, 500).map((line) => {
              const vals = line.split(",");
              return Object.fromEntries(
                heads.map((h, i) => [h, vals[i]?.trim() || ""]),
              );
            }),
          );
        }}
      />
      <b>
        {rows.length} {lang === "ar" ? "صفوف جاهزة للمراجعة" : "rows ready"}
      </b>
      <button disabled={busy || !rows.length} onClick={() => void submit(rows)}>
        {lang === "ar" ? "استيراد بعد التحقق" : "Validate and import"}
      </button>
    </div>
  );
}
function SimpleNote({
  busy,
  submit,
}: {
  busy: boolean;
  submit: (s: string) => Promise<void>;
}) {
  const [x, setX] = useState("");
  return (
    <form
      className="crm-form"
      onSubmit={(e) => {
        e.preventDefault();
        void submit(x);
      }}
    >
      <textarea required value={x} onChange={(e) => setX(e.target.value)} />
      <button disabled={busy}>Save</button>
    </form>
  );
}
function SimpleTask({
  busy,
  submit,
}: {
  busy: boolean;
  submit: (b: Row) => Promise<void>;
}) {
  const [x, setX] = useState("");
  return (
    <form
      className="crm-form"
      onSubmit={(e) => {
        e.preventDefault();
        void submit({
          title: x,
          kind: "follow_up",
          dueAt: null,
          priority: "medium",
        });
      }}
    >
      <input
        required
        minLength={2}
        value={x}
        onChange={(e) => setX(e.target.value)}
      />
      <button disabled={busy}>Save</button>
    </form>
  );
}
function Modal({
  title,
  close,
  children,
}: {
  title: string;
  close: () => void;
  children: React.ReactNode;
}) {
  return (
    <div className="crm-modal" role="dialog" aria-modal="true">
      <div>
        <header>
          <h2>{title}</h2>
          <button onClick={close} aria-label="Close">
            <X />
          </button>
        </header>
        {children}
      </div>
    </div>
  );
}
function Loading() {
  return (
    <div className="crm-loading">
      <RefreshCw />
      <span />
      <span />
      <span />
    </div>
  );
}
function Empty({
  title,
  copy,
  action,
  onAction,
}: {
  title: string;
  copy?: string;
  action?: string;
  onAction?: () => void;
}) {
  return (
    <div className="crm-empty">
      <ContactRound />
      <h2>{title}</h2>
      {copy && <p>{copy}</p>}
      {action && <button onClick={onAction}>{action}</button>}
    </div>
  );
}
function Arrow(lang: string) {
  return lang === "ar" ? <ArrowLeft /> : <ArrowRight />;
}
