import { useEffect, useRef, useState } from "react";
import Form, { Field, useForm } from "rc-field-form";
import { IconBuildingStore, IconCheck, IconUpload, IconPhoto, IconX, IconSparkles } from "@tabler/icons-react";
import { notifications } from "@/lib/notifications";
import { useTranslation } from "../../i18n/hooks/useTranslation";
import { useOfficeSpaceStore } from "../../store/officeSpaceStore";
import { useAuthStore } from "../../store/authStore";
import officeSpaceService from "../../services/officeSpaceService";
import { COMMON_INCOME_SERVICES } from "../../lib/incomeExpenseDefaults";
import SelectField from "../common/SelectField";
import TimePicker from "../common/TimePicker";
import { Switch } from "../ui/switch";

// Phone is unverified free text — accept any country's number, and Bengali numerals too.
// Normalize Bengali (০-৯) digits to Western, strip common separators, then require a
// plausible international length (7–15 digits, optional leading +).
const bnToEnDigits = (v) => String(v ?? "").replace(/[০-৯]/g, (d) => "০১২৩৪৫৬৭৮৯".indexOf(d));
const PHONE_RE = /^\+?\d{7,15}$/;
const isValidPhone = (v) => PHONE_RE.test(bnToEnDigits(v).replace(/[\s\-().]/g, ""));
// Shop email is unverified free text (like the phone) — only a light format check.
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isValidEmail = (v) => EMAIL_RE.test(String(v ?? "").trim());

const inputCls =
  "w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 bg-white dark:bg-zinc-800 text-zinc-800 dark:text-zinc-100 placeholder:text-zinc-400 dark:placeholder:text-zinc-500 disabled:opacity-50 disabled:cursor-not-allowed";

// Largest ORIGINAL logo we accept before optimisation (app-wide 20 MB image cap).
// The upload itself is always shrunk far below any server limit (see optimizeLogo).
const MAX_LOGO_BYTES = 20 * 1024 * 1024;

// Downscale the chosen logo to a small WebP before upload so it never trips the
// server's request-size limit ("request file too large"). WebP is used instead of
// a JPEG re-encode so a transparent PNG logo keeps its transparency, and a 512px
// logo is more than enough for the profile / print headers. Falls back to the
// original file if the browser can't encode it or the result isn't actually smaller.
async function optimizeLogo(file) {
  try {
    const bitmap = await createImageBitmap(file);
    const longer = Math.max(bitmap.width, bitmap.height);
    const scale = longer > 512 ? 512 / longer : 1;
    const w = Math.max(1, Math.round(bitmap.width * scale));
    const h = Math.max(1, Math.round(bitmap.height * scale));
    const canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext("2d");
    if (!ctx) return file;
    ctx.drawImage(bitmap, 0, 0, w, h);
    bitmap.close?.();
    const blob = await new Promise((res) => canvas.toBlob(res, "image/webp", 0.92));
    if (!blob || blob.size >= file.size) return file;
    const baseName = (file.name || "logo").replace(/\.[^.]+$/, "");
    return new File([blob], `${baseName}.webp`, { type: "image/webp", lastModified: Date.now() });
  } catch {
    return file; // decode/encode failed — upload the original
  }
}

// The shop's pickable services come from the shared "সার্ভিসের মূল্য তালিকা" catalog
// (COMMON_INCOME_SERVICES) — the same 60 services a shop can price in Settings. Services
// are stored as free text (Bangla), so the catalog is Bangla-only. Existing shops may hold
// older/custom values; those simply render as removable custom chips below.
const PRESET_SERVICES = COMMON_INCOME_SERVICES.map((name) => ({ bn: name, en: name }));
const PRESET_SERVICE_LABELS = PRESET_SERVICES.map((s) => s.bn);
const OFF_DAYS = [
  { v: "sun", bn: "রবি", en: "Sun" }, { v: "mon", bn: "সোম", en: "Mon" }, { v: "tue", bn: "মঙ্গল", en: "Tue" },
  { v: "wed", bn: "বুধ", en: "Wed" }, { v: "thu", bn: "বৃহঃ", en: "Thu" }, { v: "fri", bn: "শুক্র", en: "Fri" }, { v: "sat", bn: "শনি", en: "Sat" },
];
const FACEBOOK_HOSTS = ["facebook.com", "fb.com", "fb.me", "fb.watch", "m.me"];
const GOOGLE_MAPS_HOSTS = ["google.com", "goo.gl", "g.co", "page.link"];

// Normalize + validate a user-supplied link against an allow-list of hosts.
function sanitizeUrl(raw, allowedHosts) {
  if (raw == null) return { value: null };
  let s = String(raw).trim();
  if (!s) return { value: null };
  if (/^[a-z][a-z0-9+.-]*:/i.test(s)) {
    if (!/^https?:\/\//i.test(s)) return { error: true };
  } else {
    s = "https://" + s;
  }
  let url;
  try {
    url = new URL(s);
  } catch {
    return { error: true };
  }
  if (url.protocol !== "http:" && url.protocol !== "https:") return { error: true };
  url.protocol = "https:";
  const host = url.hostname.toLowerCase().replace(/^www\./, "");
  if (!host.includes(".")) return { error: true };
  if (allowedHosts && !allowedHosts.some((h) => host === h || host.endsWith("." + h))) {
    return { error: true };
  }
  return { value: url.toString() };
}

// Sanitize free-text input before it leaves the form: strip tag delimiters (`<`/`>`)
// so no markup/script survives, drop control chars, collapse spaces, trim and cap.
// Mirrors the backend Validator.sanitizeText — the server re-sanitizes regardless,
// this is defense-in-depth + immediate cleanup of pasted junk.
const sanitizeText = (v, { max, singleLine = false } = {}) => {
  let s = String(v ?? "").replace(/[<>]/g, "");
  s = singleLine
    ? s.replace(/[\x00-\x1F\x7F]/g, " ")
    : s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
  s = s.replace(/[ \t]{2,}/g, " ").trim();
  return max ? s.slice(0, max) : s;
};

// Amber (brand-warm) highlight for the profile-completion fields: an unfilled field
// gets a soft ring instead of a blocking red asterisk — the shop can be saved with
// them empty, they only gate the one-time completion bonus. Mirrors the same
// treatment on the profile page (Profile.jsx fieldHighlightCls / PersonalSummaryCard).
const MISSING_CLS =
  "border-amber-400 dark:border-amber-500/70 ring-1 ring-amber-300/60 dark:ring-amber-500/30 bg-amber-50/50 dark:bg-amber-900/10";
const isFieldEmpty = (v) => v === null || v === undefined || String(v).trim() === "";
const fieldHighlightCls = (control, meta) =>
  meta?.errors?.[0] ? "border-red-500" : isFieldEmpty(control?.value) ? MISSING_CLS : "";

/**
 * OfficeShopSection — the shop / business ("Dokan") editor for a single office
 * space. The office name (edited in the Basic Information section) IS the shop
 * name, so there is no separate shop-name field here. Everything else — category,
 * services, address, hours, links, directory visibility — lives on the office's
 * 1:1 business profile and is saved via PUT /api/office-spaces/:id.
 */
export default function OfficeShopSection({ officeSpace, isOwner }) {
  const { t, currentLanguage } = useTranslation();
  const lang = currentLanguage === "en" ? "en" : "bn";
  const { updateOfficeSpace, fetchOfficeSpaces } = useOfficeSpaceStore();
  const getCurrentUser = useAuthStore((s) => s.getCurrentUser);
  const bonusAmount = useAuthStore((s) => s.user?.profileCompletionBonus ?? 20);
  const bonusGiven = useAuthStore((s) => s.user?.settings?.profileCompletionBonusGiven === true);
  const [form] = useForm();
  const [saving, setSaving] = useState(false);
  const [name, setName] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [services, setServices] = useState([]);
  const [offDays, setOffDays] = useState([]);
  const [showInDirectory, setShowInDirectory] = useState(false);
  const [serviceInput, setServiceInput] = useState("");
  const [shopLogo, setShopLogo] = useState("");
  const [logoUploading, setLogoUploading] = useState(false);
  const logoInputRef = useRef(null);

  const bp = officeSpace?.businessProfile || {};

  // Re-seed the form + local state whenever the office (or its profile) changes,
  // e.g. after a store refresh or when switching between offices.
  useEffect(() => {
    form.setFieldsValue({
      businessCategory: bp.businessCategory || null,
      businessAddress: bp.businessAddress || "",
      mapUrl: bp.mapUrl || "",
      // Sensible shop defaults when not yet set: 10:00 AM – 08:00 PM.
      openTime: bp.openTime || "10:00",
      closeTime: bp.closeTime || "20:00",
      facebookUrl: bp.facebookUrl || "",
      businessAbout: bp.businessAbout || "",
      courtAddress: bp.courtAddress || "",
      shopPhone: bp.shopPhone || "",
      shopEmail: bp.shopEmail || "",
    });
    setShopLogo(bp.shopLogo || "");
    setName(officeSpace?.name || "");
    setIsActive(officeSpace?.status === "active");
    setServices(Array.isArray(bp.services) ? bp.services : []);
    // Default weekly off day: Friday (until the shop sets its own).
    setOffDays(Array.isArray(bp.offDays) && bp.offDays.length ? bp.offDays : ["fri"]);
    setShowInDirectory(!!bp.showInDirectory);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [officeSpace?.id, officeSpace?.businessProfile, officeSpace?.name, officeSpace?.status]);

  // Upload the chosen logo file to R2 (server compresses to ≤100KB) and keep the
  // returned URL in local state; it is persisted to the profile on "Update info".
  const handleLogoSelect = async (e) => {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    if (!["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
      notifications.show({ title: t("common.error"), message: t("profile.logoTypeError") || "লোগো JPEG, PNG বা WebP হতে হবে।", color: "red" });
      return;
    }
    if (file.size > MAX_LOGO_BYTES) {
      notifications.show({ title: t("common.error"), message: t("profile.logoSizeError") || "লোগোর আকার সর্বোচ্চ ২০ MB হতে পারে।", color: "red" });
      return;
    }
    try {
      setLogoUploading(true);
      // Shrink to a small WebP so the upload never exceeds the server's size limit.
      const optimized = await optimizeLogo(file);
      const res = await officeSpaceService.uploadShopLogo(officeSpace.id, optimized);
      const url = res?.data?.url || res?.url;
      if (url) setShopLogo(url);
    } catch (err) {
      const raw = String(err?.message || "");
      // Show the backend "request file too large" (413) as a friendly Bangla message.
      const isTooLarge = /large|payload|413/i.test(raw);
      notifications.show({ title: t("common.error"), message: isTooLarge ? (t("profile.logoSizeError") || "লোগোর আকার সর্বোচ্চ ২০ MB হতে পারে।") : (raw || t("profile.failedToUpdate")), color: "red" });
    } finally {
      setLogoUploading(false);
    }
  };

  const handleSave = async () => {
    try {
      const values = form.getFieldsValue();
      const cleanName = sanitizeText(name, { max: 255, singleLine: true });

      // Reset field-level errors before re-validating.
      form.setFields([
        { name: "mapUrl", errors: [] },
        { name: "facebookUrl", errors: [] },
        { name: "shopPhone", errors: [] },
        { name: "shopEmail", errors: [] },
      ]);

      // ── Format-only validation: every completion field may be left empty (the
      // shop saves fine without them — they only gate the completion bonus), but a
      // PROVIDED value must be well-formed. ────────────────────────────────────
      const fieldErrors = [];

      // Phone — format-checked when present (any country + Bengali numerals).
      const phoneRaw = String(values.shopPhone || "").trim();
      if (phoneRaw && !isValidPhone(phoneRaw)) fieldErrors.push({ name: "shopPhone", errors: [t("profile.invalidPhone") || "সঠিক ফোন নম্বর দিন।"] });

      // Email — unverified, but format-checked when present (empty is fine).
      const emailRaw = String(values.shopEmail || "").trim();
      if (emailRaw && !isValidEmail(emailRaw)) fieldErrors.push({ name: "shopEmail", errors: [t("profile.invalidEmail") || "সঠিক ইমেইল দিন।"] });

      // Google Maps / Facebook links — host-validated when present (empty → null).
      const mapRes = sanitizeUrl(values.mapUrl, GOOGLE_MAPS_HOSTS);
      if (mapRes.error) fieldErrors.push({ name: "mapUrl", errors: [t("profile.invalidMapUrl")] });
      const fbRes = sanitizeUrl(values.facebookUrl, FACEBOOK_HOSTS);
      if (fbRes.error) fieldErrors.push({ name: "facebookUrl", errors: [t("profile.invalidFacebookUrl")] });

      if (fieldErrors.length) {
        form.setFields(fieldErrors);
        notifications.show({ title: t("common.error"), message: t("profile.fixInvalidFields") || "চিহ্নিত ঘরের তথ্য সঠিকভাবে দিন", color: "red" });
        return;
      }

      setSaving(true);

      // Sanitize every free-text field before it leaves the form. Custom service
      // strings are cleaned + de-duplicated; empties collapse to null.
      const cleanServices = [
        ...new Set(services.map((s) => sanitizeText(s, { max: 100, singleLine: true })).filter(Boolean)),
      ];

      // The office name IS the shop name — backend mirrors name → shopName.
      const payload = {
        name: cleanName,
        status: isActive ? "active" : "inactive",
        businessCategory: sanitizeText(values.businessCategory, { max: 100, singleLine: true }) || null,
        services: cleanServices,
        businessAddress: sanitizeText(values.businessAddress, { max: 500 }) || null,
        mapUrl: mapRes.value,
        openTime: values.openTime || null,
        closeTime: values.closeTime || null,
        offDays,
        facebookUrl: fbRes.value,
        businessAbout: sanitizeText(values.businessAbout, { max: 5000 }) || null,
        showInDirectory,
        courtAddress: sanitizeText(values.courtAddress, { max: 500 }) || null,
        shopLogo: shopLogo || null,
        shopPhone: phoneRaw || null,
        shopEmail: emailRaw || null,
      };

      const result = await updateOfficeSpace(officeSpace.id, payload);
      await fetchOfficeSpaces();
      // The completion banner reads the shop fields flattened onto the user, so
      // refresh the user after every save (not just on bonus) to keep the % live.
      await getCurrentUser().catch(() => {});
      notifications.show({
        title: t("common.success"),
        message: t("profile.shopUpdated") || "দোকানের তথ্য সংরক্ষিত হয়েছে",
        color: "green",
        icon: <IconCheck size={16} />,
      });

      // Completing the shop can be the final piece that earns the profile-completion
      // bonus (the backend re-checks every field before granting) — celebrate.
      if (result?.profileCompletionBonus) {
        notifications.show({
          title: t("profileCompletion.bonusBannerTitle", { amount: bonusAmount }),
          message: t("profileCompletion.bonusBannerMessage", { amount: bonusAmount }),
          color: "green",
          icon: <IconSparkles size={16} />,
          autoClose: 8000,
        });
      }
    } catch (error) {
      console.error("Shop update error:", error);
      notifications.show({ title: t("common.error"), message: t("profile.failedToUpdate"), color: "red" });
    } finally {
      setSaving(false);
    }
  };

  const customServices = services.filter((s) => !PRESET_SERVICE_LABELS.includes(s));

  return (
    <section className="rounded-2xl border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-900 p-4 sm:p-5 shadow-sm">
      <div className="flex flex-col gap-4">
        <div className="flex flex-col gap-1">
          <div className="flex items-center gap-2">
            <IconBuildingStore size={18} stroke={1.7} className="text-zinc-400" />
            <h2 className="text-base font-semibold text-zinc-900 dark:text-zinc-100">
              {t("officeSpace.shopSection") || "দোকান / ব্যবসার তথ্য"}
            </h2>
          </div>
          {/* Saving works with the amber-marked fields empty — they only gate the bonus. */}
          {!bonusGiven && (
            <p className="text-xs text-amber-600 dark:text-amber-500">
              {t("profile.bonusFieldsHint", { amount: bonusAmount })}
            </p>
          )}
        </div>

        {/* Dokan name (== shop name) + status — one row */}
        <div className="flex flex-col gap-1.5">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
            <div className="flex flex-1 flex-col gap-1.5">
              <label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
                {t("officeSpace.workspaceName") || "দোকানের নাম"}
              </label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                disabled={!isOwner}
                className={`${inputCls} ${!name.trim() ? MISSING_CLS : ""}`}
              />
            </div>
            <label className="flex flex-none items-center gap-3 rounded-lg bg-zinc-50 dark:bg-zinc-800/60 px-3 py-2 cursor-pointer">
              <span className="relative flex-none">
                <input type="checkbox" checked={isActive} onChange={(e) => setIsActive(e.currentTarget.checked)} disabled={!isOwner} className="sr-only" />
                <span className={`block h-6 w-10 rounded-full transition-colors ${isActive ? "bg-primary" : "bg-zinc-300 dark:bg-zinc-600"} ${!isOwner ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`} />
                <span className={`absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${isActive ? "translate-x-4" : ""}`} />
              </span>
              <span>
                <span className="block text-sm font-medium text-zinc-800 dark:text-zinc-200">{t("officeSpace.workspaceStatus") || "দোকানের অবস্থা"}</span>
                <span className="block text-xs text-zinc-500 dark:text-zinc-400">{isActive ? t("officeSpace.workspaceIsActive") : t("officeSpace.workspaceIsInactive")}</span>
              </span>
            </label>
          </div>
          <p className="text-xs text-zinc-400 dark:text-zinc-500">
            {t("officeSpace.workspaceNameHint") || "এই নামটিই আপনার দোকানের নাম হিসেবে ব্যবহৃত হবে।"}
          </p>
        </div>

        {/* Directory toggle */}
        <div className="flex items-center justify-between p-3 bg-orange-50 dark:bg-orange-950/20 border border-orange-100 dark:border-orange-900 rounded-xl">
          <div>
            <p className="text-sm font-semibold text-zinc-800 dark:text-zinc-100">{t("profile.showInDirectory") || "সাইট ডিরেক্টরিতে দেখান"}</p>
            <p className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">{t("profile.showInDirectoryDesc") || "আপনার দোকানের তথ্য আমাদের ডিরেক্টরিতে প্রকাশ করুন — সরাসরি প্রচার পাবেন।"}</p>
          </div>
          <Switch checked={showInDirectory} onCheckedChange={setShowInDirectory} disabled={!isOwner} />
        </div>

        <Form form={form}>
          <div className="flex flex-col gap-4">
            {/* Shop logo + phone + email (email sits beside the phone) */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-[auto_1fr_1fr] gap-4 items-start">
              <div>
                <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.shopLogo") || "দোকানের লোগো"}</label>
                <div className="flex items-center gap-3">
                  <div className={`w-16 h-16 rounded-xl border ${shopLogo ? "border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800" : MISSING_CLS} flex items-center justify-center overflow-hidden flex-shrink-0`}>
                    {shopLogo ? <img src={shopLogo} alt="logo" className="w-full h-full object-contain" /> : <IconPhoto size={22} className="text-amber-400 dark:text-amber-500/70" />}
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <input ref={logoInputRef} type="file" accept="image/png,image/jpeg,image/webp" hidden onChange={handleLogoSelect} />
                    <button type="button" disabled={!isOwner || logoUploading} onClick={() => logoInputRef.current?.click()}
                      className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 dark:border-zinc-700 px-3 py-1.5 text-xs font-semibold text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed">
                      {logoUploading
                        ? <span className="h-3 w-3 rounded-full border-2 border-zinc-400 border-t-transparent animate-spin" />
                        : <IconUpload size={14} />}
                      {shopLogo ? (t("profile.changeLogo") || "লোগো পরিবর্তন") : (t("profile.uploadLogo") || "লোগো আপলোড")}
                    </button>
                    {shopLogo && (
                      <button type="button" disabled={!isOwner} onClick={() => setShopLogo("")}
                        className="inline-flex items-center gap-1 text-xs text-red-500 hover:text-red-600 disabled:opacity-50">
                        <IconX size={12} /> {t("profile.removeLogo") || "সরান"}
                      </button>
                    )}
                  </div>
                </div>
                <p className="mt-1.5 text-xs text-zinc-400 dark:text-zinc-500">{t("profile.logoUploadHint") || "JPEG, PNG বা WebP • সর্বোচ্চ ২০ MB"}</p>
              </div>
              <Field name="shopPhone">
                {(control, meta) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.shopPhone") || "দোকানের ফোন নম্বর"}</label>
                    <input {...control} value={control.value ?? ""} type="tel" inputMode="tel" placeholder="01XXXXXXXXX" className={`${inputCls} ${fieldHighlightCls(control, meta)}`} />
                    {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                  </div>
                )}
              </Field>
              {/* Shop email — unverified free text, same as the phone. Optional; used
                  on invoices/customer statements as the shop's contact email. */}
              <Field name="shopEmail">
                {(control, meta) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.shopEmail") || "দোকানের ইমেইল"}</label>
                    <input {...control} value={control.value ?? ""} type="email" inputMode="email" autoComplete="off" placeholder="shop@example.com" className={`${inputCls} ${fieldHighlightCls(control, meta)}`} />
                    {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                  </div>
                )}
              </Field>
            </div>

            {/* Category */}
            <Field name="businessCategory">
              {(control, meta) => (
                <div>
                  <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.businessCategory") || "ব্যবসার ধরন"}</label>
                  <SelectField
                    value={control.value ?? ""}
                    onChange={(val) => control.onChange({ target: { value: val || null } })}
                    placeholder={t("profile.selectCategory") || "ক্যাটাগরি বেছে নিন"}
                    triggerClassName={`${inputCls} ${fieldHighlightCls(control, meta)}`}
                    options={[
                      { value: "",                label: t("profile.selectCategory") || "ক্যাটাগরি বেছে নিন" },
                      { value: "cyber_cafe",      label: "সাইবার ক্যাফে / কম্পিউটার সেন্টার" },
                      { value: "photo_studio",    label: "ফটো স্টুডিও" },
                      { value: "document_service",label: "ডকুমেন্ট সার্ভিস সেন্টার" },
                      { value: "print_shop",      label: "প্রিন্ট ও ফটোকপি শপ" },
                      { value: "stationery",      label: "স্টেশনারি ও অফিস সাপ্লাই" },
                      { value: "it_service",      label: "আইটি সার্ভিস / সফটওয়্যার" },
                      { value: "notary_legal",    label: "নোটারি / আইন সেবা" },
                      { value: "mobile_service",  label: "মোবাইল সার্ভিস শপ" },
                      { value: "other",           label: "অন্যান্য" },
                    ]}
                  />
                  {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                </div>
              )}
            </Field>

            {/* Services */}
            <div className={`rounded-xl border p-4 ${services.length === 0 ? MISSING_CLS : "bg-zinc-50 dark:bg-zinc-800/40 border-zinc-100 dark:border-zinc-700/50"}`}>
              <label className="block text-sm font-semibold text-zinc-700 dark:text-zinc-300 mb-1">
                {t("profile.services") || "সার্ভিস / সেবাসমূহ"}
              </label>
              <p className="text-xs text-zinc-400 dark:text-zinc-500 mb-3">{t("profile.servicesDesc") || "আপনার দোকানে যেসব সেবা দেন সেগুলো সিলেক্ট করুন।"}</p>
              <div className="flex flex-wrap gap-1.5 mb-3">
                {PRESET_SERVICES.map((s) => {
                  const label = s[lang];
                  // A preset counts as selected if EITHER language variant is stored.
                  const active = services.includes(s.bn) || services.includes(s.en);
                  return (
                    <button key={s.en} type="button"
                      onClick={() => setServices((prev) => active
                        ? prev.filter((x) => x !== s.bn && x !== s.en)
                        : [...prev, label])}
                      className={`px-2.5 py-1 rounded-full text-xs font-medium border transition-colors ${active ? "bg-orange-500 text-white border-orange-500" : "bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 border-zinc-200 dark:border-zinc-600 hover:border-orange-400"}`}
                    >{label}</button>
                  );
                })}
              </div>
              <div className="flex gap-2 items-center">
                <input value={serviceInput} onChange={(e) => setServiceInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); const v = sanitizeText(serviceInput, { max: 100, singleLine: true }); if (v && !services.includes(v)) setServices((prev) => [...prev, v]); setServiceInput(""); } }}
                  placeholder={t("profile.addCustomService") || "কাস্টম সার্ভিস লিখুন ও Enter চাপুন"}
                  className="flex-1 px-3 py-1.5 border border-zinc-200 dark:border-zinc-700 rounded-lg text-sm bg-white dark:bg-zinc-800 text-zinc-800 dark:text-zinc-100 placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-primary/40"
                />
                <button type="button" onClick={() => { const v = sanitizeText(serviceInput, { max: 100, singleLine: true }); if (v && !services.includes(v)) setServices((prev) => [...prev, v]); setServiceInput(""); }}
                  className="w-8 h-8 flex items-center justify-center bg-orange-500 hover:bg-orange-600 text-white text-sm rounded-lg flex-shrink-0">+</button>
              </div>
              {customServices.length > 0 && (
                <div className="flex flex-wrap gap-1.5 mt-2">
                  {customServices.map((s) => (
                    <span key={s} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-white dark:bg-zinc-800 text-zinc-700 dark:text-zinc-200 border border-zinc-200 dark:border-zinc-600">
                      {s}<button type="button" onClick={() => setServices((prev) => prev.filter((x) => x !== s))} className="text-zinc-400 hover:text-red-500">×</button>
                    </span>
                  ))}
                </div>
              )}
            </div>

            {/* Address + map URL */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field name="businessAddress">
                {(control, meta) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.businessAddress") || "দোকানের ঠিকানা"}</label>
                    <input {...control} value={control.value ?? ""} placeholder="দোকানের সম্পূর্ণ ঠিকানা" className={`${inputCls} ${fieldHighlightCls(control, meta)}`} />
                    {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                  </div>
                )}
              </Field>
              <Field name="mapUrl">
                {(control, meta) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.mapUrl") || "Google Maps লিংক"}</label>
                    <input {...control} value={control.value ?? ""} type="url" placeholder="https://maps.google.com/..." className={`${inputCls} ${fieldHighlightCls(control, meta)}`} />
                    {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                  </div>
                )}
              </Field>
            </div>

            {/* Open/close + Off days */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <Field name="openTime">
                {(control) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.openTime") || "খোলার সময়"}</label>
                    <TimePicker value={control.value || ""} onChange={control.onChange} />
                  </div>
                )}
              </Field>
              <Field name="closeTime">
                {(control) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.closeTime") || "বন্ধের সময়"}</label>
                    <TimePicker value={control.value || ""} onChange={control.onChange} />
                  </div>
                )}
              </Field>
              <div>
                <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.offDays") || "সাপ্তাহিক বন্ধের দিন"}</label>
                <div className="flex flex-wrap gap-1.5">
                  {OFF_DAYS.map(({ v, bn, en }) => {
                    const active = offDays.includes(v);
                    return (
                      <button key={v} type="button"
                        onClick={() => setOffDays((prev) => active ? prev.filter((d) => d !== v) : [...prev, v])}
                        className={`px-3 py-1 rounded-lg text-xs font-medium border transition-colors ${active ? "bg-red-500 text-white border-red-500" : "bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 border-zinc-200 dark:border-zinc-600 hover:border-red-400"}`}
                      >{lang === "en" ? en : bn}</button>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Facebook + Court address */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field name="facebookUrl">
                {(control, meta) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.facebookUrl") || "Facebook পেজ"}</label>
                    <input {...control} value={control.value ?? ""} type="url" placeholder="facebook.com/..." className={`${inputCls} ${fieldHighlightCls(control, meta)}`} />
                    {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                  </div>
                )}
              </Field>
              <Field name="courtAddress">
                {(control) => (
                  <div>
                    <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.courtAddress") || "কোর্ট / নোটারি ঠিকানা"}</label>
                    <input {...control} value={control.value ?? ""} placeholder={t("profile.courtAddressPlaceholder")} className={inputCls} />
                    <p className="mt-1 text-xs text-zinc-400 dark:text-zinc-500 leading-snug">{t("profile.courtAddressHint")}</p>
                  </div>
                )}
              </Field>
            </div>

            {/* Business about */}
            <Field name="businessAbout">
              {(control, meta) => (
                <div>
                  <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">{t("profile.businessAbout") || "দোকান সম্পর্কে"}</label>
                  <textarea {...control} value={control.value ?? ""} placeholder={t("profile.businessAboutPlaceholder") || "সংক্ষিপ্ত বিবরণ..."} rows={2} className={`${inputCls} resize-y ${fieldHighlightCls(control, meta)}`} />
                  {meta.errors?.[0] && <p className="mt-0.5 text-xs text-red-500">{meta.errors[0]}</p>}
                </div>
              )}
            </Field>

            {isOwner && (
              <div className="flex justify-end pt-1">
                <button type="button" onClick={handleSave} disabled={saving || !name.trim()}
                  className="inline-flex items-center gap-1.5 rounded-lg bg-primary hover:bg-primary/90 disabled:opacity-60 text-white px-5 py-2.5 font-semibold text-sm transition-colors">
                  {saving && <span className="h-3 w-3 rounded-full border-2 border-white border-t-transparent animate-spin" />}
                  {t("profile.updateInfo")}
                </button>
              </div>
            )}
          </div>
        </Form>
      </div>
    </section>
  );
}
