"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { SITE, UI, type Lang, SERVICES, SERVICE_KEYS } from "@/lib/config";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import { signupStorage, type CompanyInfo } from "@/lib/storage";
import { logger } from "@/lib/logger";
import SignupProgress from "@/components/SignupProgress";

export default function CompanyInfoPage({
  params,
}: {
  params: { lang: Lang };
}) {
  const { lang } = params;
  const router = useRouter();
  const searchParams = useSearchParams();
  const stripeSessionId = searchParams?.get("session_id");
  const t = UI[lang].t;
  const dir = UI[lang].dir;

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [selectedPlan, setSelectedPlan] = useState<string>("");
  const [csrfToken, setCSRFToken] = useState("");

  const [formData, setFormData] = useState<CompanyInfo>({
    companyName: "",
    industry: "",
    companySize: "",
    gccCountry: "",
    phoneNumber: "",
    agentCount: "",
    agentUseCase: "",
    companyDescription: "",
    services: [],
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    // Fetch CSRF token on mount
    fetch("/api/auth/csrf")
      .then((res) => res.json())
      .then((data) => setCSRFToken(data.csrfToken))
      .catch((err) => logger.error("Failed to fetch CSRF token", err));

    // Note: Removed auto-redirect checks
    // Users can access this page directly from verify page
    // Fresh start enforced from pricing page

    // Load selected plan from storage if available (optional)
    const signupData = signupStorage.get();
    if (signupData?.plan?.tierId) {
      setSelectedPlan(signupData.plan.tierId); // Extract tierId string from plan object
    }

    // Load existing company info if available (for resume)
    // BUT: Always override agent fields with package-based values
    if (signupData?.companyInfo) {
      const savedInfo = signupData.companyInfo;
      const planId = signupData.plan?.tierId;

      setFormData({
        ...savedInfo,
        // ALWAYS use package-based values for agent fields (never use saved values)
        agentCount: planId
          ? getAgentCountForPlan(planId).toString()
          : savedInfo.agentCount,
        agentUseCase: planId
          ? getAgentUseCaseForPlan(planId, lang)
          : savedInfo.agentUseCase,
      });
    }
  }, [lang]);

  // Auto-populate agent count and use case when plan is selected
  useEffect(() => {
    if (selectedPlan) {
      const agentCount = getAgentCountForPlan(selectedPlan);
      const agentUseCase = getAgentUseCaseForPlan(selectedPlan, lang);

      setFormData((prev) => ({
        ...prev,
        agentCount: agentCount.toString(),
        agentUseCase: agentUseCase,
      }));

      logger.info("Auto-populated agent fields", {
        plan: selectedPlan,
        agentCount,
        agentUseCase,
      });
    }
  }, [selectedPlan, lang]);

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.companyName.trim()) {
      newErrors.companyName = t.fieldRequired;
    }

    if (!formData.industry) {
      newErrors.industry = t.fieldRequired;
    }

    if (!formData.companySize) {
      newErrors.companySize = t.fieldRequired;
    }

    if (!formData.gccCountry) {
      newErrors.gccCountry = t.fieldRequired;
    }

    if (!formData.phoneNumber.trim()) {
      newErrors.phoneNumber = t.fieldRequired;
    } else if (!/^\+?[0-9\s-()]{8,}$/.test(formData.phoneNumber)) {
      newErrors.phoneNumber = t.invalidPhone;
    }

    if (!formData.agentCount.trim()) {
      newErrors.agentCount = t.fieldRequired;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    // Ensure CSRF token is loaded
    if (!csrfToken) {
      setError(
        lang === "ar"
          ? "خطأ في الأمان. يرجى تحديث الصفحة."
          : "Security error. Please refresh the page.",
      );
      return;
    }

    setLoading(true);
    setError("");

    try {
      // Get user email and tier context from localStorage
      const signupData = signupStorage.get();

      // Validate that signup data exists (user must complete signup first)
      if (!signupData?.email) {
        setError(
          lang === "ar"
            ? "يجب عليك إكمال خطوات التسجيل أولاً. سيتم إعادة توجيهك..."
            : "You must complete the signup steps first. Redirecting...",
        );
        setLoading(false);
        // Redirect back to signup page after 2 seconds
        setTimeout(() => {
          router.push(`/${lang}/signup`);
        }, 2000);
        return;
      }

      const userEmail = signupData.email;

      logger.info("Submitting company info", {
        email: userEmail,
        hasCompanyName: !!formData.companyName,
        hasIndustry: !!formData.industry,
        hasCompanySize: !!formData.companySize,
        hasGccCountry: !!formData.gccCountry,
        hasPhoneNumber: !!formData.phoneNumber,
        servicesCount: formData.services?.length || 0,
      });

      // Save company info to database via API (with CSRF protection)
      const response = await fetch("/api/onboarding/company-info", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          email: userEmail, // Include email to identify user
          companyName: formData.companyName,
          industry: formData.industry,
          companySize: formData.companySize,
          gccCountry: formData.gccCountry, // Send as gccCountry field
          phoneNumber: formData.phoneNumber,
          address: formData.gccCountry, // Also use as address
          website: "", // Optional field
          agentCount: formData.agentCount,
          agentUseCase: formData.agentUseCase,
          services: formData.services,
          companyDescription: formData.companyDescription,
          selectedPlan: selectedPlan || signupData?.plan?.tierId || "tier2", // Extract tierId from plan object
          billingPeriod:
            signupData?.billingPeriod ||
            signupData?.plan?.billingPeriod ||
            "monthly", // Include billing period
          currency: signupData?.currency || signupData?.plan?.currency || "GBP", // Include currency
          stripeSessionId,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        logger.error("API returned error", { errorData });

        // Show validation errors if available
        if (errorData.details && Array.isArray(errorData.details)) {
          const errorMessages = errorData.details
            .map((d: any) => `${d.field}: ${d.message}`)
            .join(", ");
          throw new Error(`Validation failed: ${errorMessages}`);
        }

        throw new Error(
          errorData.error || "Failed to save company information",
        );
      }

      // Save to localStorage as backup
      signupStorage.saveCompanyInfo(formData);

      logger.info("Company info saved to database", {
        companyName: formData.companyName,
        industry: formData.industry,
      });

      // Redirect to onboarding page (Step 4 - Goals & Subscription)
      router.push(`/${lang}/signup/onboarding`);
    } catch (err: unknown) {
      logger.error("Company info submission error", err);
      setError(
        err instanceof Error
          ? err.message
          : "Failed to save company information. Please try again.",
      );
      setLoading(false);
    }
  };

  const handleSkip = () => {
    // Allow skipping but redirect to onboarding page
    // User can fill company info later from dashboard
    router.push(`/${lang}/signup/onboarding`);
  };

  const industries = [
    { value: "healthcare", label: t.industryHealthCare },
    { value: "beauty-wellness", label: t.industryBeautyWellness },
    { value: "dental", label: t.industryDental },
    { value: "aesthetics", label: t.industryAesthetics },
    { value: "medical-spas", label: t.industryMedicalSpas },
    { value: "physio", label: t.industryPhysio },
    { value: "labs-diagnostics", label: t.industryLabsDiagnostics },
    { value: "telehealth", label: t.industryTelehealth },
    { value: "vet", label: t.industryVet },
    { value: "food-hospitality", label: t.industryFoodHospitality },
    { value: "restaurants-cafes", label: t.industryRestaurantsCafes },
    { value: "hotels-accommodation", label: t.industryHotelsAccommodation },
    { value: "mobility-industry", label: t.industryMobilityIndustry },
    { value: "vehicle-rental", label: t.industryVehicleRental },
    { value: "education", label: t.industryEducation },
    { value: "sports-academies", label: t.industrySportsAcademies },
    { value: "events-venues", label: t.industryEventsVenues },
    { value: "property-facilities", label: t.industryPropertyFacilities },
    { value: "home-services-trades", label: t.industryHomeServicesTrades },
    { value: "pet-services", label: t.industryPetServices },
    { value: "public-sector", label: t.industryPublicSector },
    { value: "nonprofit-community", label: t.industryNonprofitCommunity },
    { value: "retail-services", label: t.industryRetailServices },
    { value: "other", label: t.industryOther },
  ];

  const companySizes = [
    { value: "1-10", label: t.companySizeSmall },
    { value: "11-50", label: t.companySizeMedium },
    { value: "51-200", label: t.companySizeLarge },
    { value: "200+", label: t.companySizeEnterprise },
  ];

  const gccCountries = [
    { value: "sa", label: t.gccCountrySA },
    { value: "uae", label: t.gccCountryUAE },
    { value: "qa", label: t.gccCountryQA },
    { value: "kw", label: t.gccCountryKW },
    { value: "bh", label: t.gccCountryBH },
    { value: "om", label: t.gccCountryOM },
  ];

  // Plan-based agent count mapping (based on actual package limits)
  const planAgentCounts: Record<string, number> = {
    tier1: 1, // Starter: 1 agent
    tier2: 1, // Professional: 1 agent
    tier3: 2, // Business: 2 agents (WhatsApp + AI Voice)
    tier4: 4, // Enterprise: 4 agents
    tier5: 8, // Ultimate: 8 agents
  };

  const getAgentCountForPlan = (plan: string): number => {
    return planAgentCounts[plan] || 1; // Default to 1 if plan not found
  };

  // Plan-based agent use case descriptions
  const planAgentUseCases: Record<string, { en: string; ar: string }> = {
    tier1: {
      en: "FAQ automation, appointment booking",
      ar: "أتمتة الأسئلة الشائعة، حجز المواعيد",
    },
    tier2: {
      en: "Appointment booking, quotations, CRM management",
      ar: "حجز المواعيد، عروض الأسعار، إدارة CRM",
    },
    tier3: {
      en: "WhatsApp booking automation, AI voice receptionist for calls and transfers",
      ar: "أتمتة حجز واتساب، موظفة استقبال صوتية للمكالمات والتحويلات",
    },
    tier4: {
      en: "Multi-channel management, social media automation, engagement analytics, customer support",
      ar: "إدارة متعددة القنوات، أتمتة وسائل التواصل، تحليلات التفاعل، دعم العملاء",
    },
    tier5: {
      en: "Lead generation, automated nurturing, multi-channel capture, conversion optimization, advanced CRM, ROI tracking, customer lifecycle management, comprehensive automation",
      ar: "توليد العملاء المحتملين، رعاية آلية، التقاط متعدد القنوات، تحسين التحويلات، CRM متقدم، تتبع عائد الاستثمار، إدارة دورة حياة العميل، أتمتة شاملة",
    },
  };

  const getAgentUseCaseForPlan = (plan: string, language: Lang): string => {
    const useCase = planAgentUseCases[plan];
    if (!useCase) return "";
    return language === "ar" ? useCase.ar : useCase.en;
  };

  // Check if user can upgrade to a higher tier
  const canUpgrade = (currentPlan: string): boolean => {
    const tierOrder = ["tier1", "tier2", "tier3", "tier4", "tier5"];
    const currentIndex = tierOrder.indexOf(currentPlan);
    return currentIndex >= 0 && currentIndex < tierOrder.length - 1;
  };

  return (
    <main className="mx-auto flex min-h-screen items-center justify-center px-4 py-16">
      <div className="w-full max-w-2xl space-y-8">
        {/* Logo */}
        <div className="text-center">
          <Link href={`/${lang}`} className="inline-block">
            <img src="/mawidi-icon.svg" alt="Mawidi" className="h-12 w-auto mx-auto" width={48} height={48} />
          </Link>
        </div>

        {/* Header */}
        <div className="space-y-2 text-center">
          <h2 className="text-3xl font-extrabold text-brand-ink">
            {t.companyInfoTitle}
          </h2>
          <p className="text-neutral-600">{t.companyInfoSubtitle}</p>
        </div>

        {/* Progress Indicator */}
        <SignupProgress
          currentStep={3}
          totalSteps={5}
          steps={[
            lang === "ar" ? "إنشاء حساب" : "Create Account",
            lang === "ar" ? "تحقق البريد" : "Verify Email",
            lang === "ar" ? "معلومات الشركة" : "Company Details",
            lang === "ar" ? "الأهداف" : "Goals",
            lang === "ar" ? "لوحة التحكم" : "Dashboard",
          ]}
        />

        {/* Error Message */}
        {error && (
          <div className="rounded-lg bg-red-50 p-4 text-sm text-red-600">
            {error}
          </div>
        )}

        {/* Selected Package Info */}
        {selectedPlan && (
          <div className="rounded-lg bg-brand-green/5 border-2 border-brand-green/20 p-4">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <h3 className="text-sm font-semibold text-brand-ink">
                  {lang === "ar" ? "📦 الباقة المختارة" : "📦 Selected Package"}
                </h3>
                <p className="mt-1 text-lg font-bold text-brand-green">
                  {PRICING_TIERS.find((t) => t.id === selectedPlan)?.nameEn ||
                    selectedPlan}{" "}
                  <span className="text-sm font-normal text-neutral-600">
                    ({formData.agentCount} {lang === "ar" ? "وكيل" : "agent"}
                    {Number(formData.agentCount) > 1 ? "s" : ""})
                  </span>
                </p>
                <p className="mt-1 text-xs text-neutral-600">
                  {lang === "ar"
                    ? "إذا كنت بحاجة لوكلاء أكثر، يمكنك ترقية باقتك في أي وقت."
                    : "Need more agents? You can upgrade your package anytime."}
                </p>
              </div>
              {canUpgrade(selectedPlan) && (
                <button
                  type="button"
                  onClick={() =>
                    router.push(`/${lang}/pricing?change_plan=true`)
                  }
                  className="rounded-lg bg-brand-green px-4 py-2 text-xs font-semibold text-white transition-all hover:bg-brand-greenHover"
                >
                  {lang === "ar" ? "ترقية" : "Upgrade"}
                </button>
              )}
            </div>
          </div>
        )}

        {/* Company Info Form */}
        <form onSubmit={handleSubmit} className="space-y-6" dir={dir}>
          <div className="grid gap-6 md:grid-cols-2">
            {/* Company Name */}
            <div className="md:col-span-2">
              <label
                htmlFor="companyName"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.companyName}
              </label>
              <input
                id="companyName"
                type="text"
                value={formData.companyName}
                onChange={(e) =>
                  setFormData({ ...formData, companyName: e.target.value })
                }
                className={`w-full rounded-lg border ${
                  errors.companyName ? "border-red-300" : "border-neutral-200"
                } px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
                placeholder={t.companyName}
              />
              {errors.companyName && (
                <p className="mt-1 text-xs text-red-600">
                  {errors.companyName}
                </p>
              )}
            </div>

            {/* Industry */}
            <div>
              <label
                htmlFor="industry"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.industry}
              </label>
              <select
                id="industry"
                value={formData.industry}
                onChange={(e) =>
                  setFormData({ ...formData, industry: e.target.value })
                }
                className={`w-full rounded-lg border ${
                  errors.industry ? "border-red-300" : "border-neutral-200"
                } px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
              >
                <option value="">{t.industry}</option>
                {industries.map((ind) => (
                  <option key={ind.value} value={ind.value}>
                    {ind.label}
                  </option>
                ))}
              </select>
              {errors.industry && (
                <p className="mt-1 text-xs text-red-600">{errors.industry}</p>
              )}
            </div>

            {/* Company Size */}
            <div>
              <label
                htmlFor="companySize"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.companySize}
              </label>
              <select
                id="companySize"
                value={formData.companySize}
                onChange={(e) =>
                  setFormData({ ...formData, companySize: e.target.value })
                }
                className={`w-full rounded-lg border ${
                  errors.companySize ? "border-red-300" : "border-neutral-200"
                } px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
              >
                <option value="">{t.companySize}</option>
                {companySizes.map((size) => (
                  <option key={size.value} value={size.value}>
                    {size.label}
                  </option>
                ))}
              </select>
              {errors.companySize && (
                <p className="mt-1 text-xs text-red-600">
                  {errors.companySize}
                </p>
              )}
            </div>

            {/* GCC Country */}
            <div>
              <label
                htmlFor="gccCountry"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.gccCountry}
              </label>
              <select
                id="gccCountry"
                value={formData.gccCountry}
                onChange={(e) =>
                  setFormData({ ...formData, gccCountry: e.target.value })
                }
                className={`w-full rounded-lg border ${
                  errors.gccCountry ? "border-red-300" : "border-neutral-200"
                } px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
              >
                <option value="">{t.gccCountry}</option>
                {gccCountries.map((country) => (
                  <option key={country.value} value={country.value}>
                    {country.label}
                  </option>
                ))}
              </select>
              {errors.gccCountry && (
                <p className="mt-1 text-xs text-red-600">{errors.gccCountry}</p>
              )}
            </div>

            {/* Phone Number */}
            <div>
              <label
                htmlFor="phoneNumber"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.phoneNumber}
              </label>
              <input
                id="phoneNumber"
                type="tel"
                value={formData.phoneNumber}
                onChange={(e) =>
                  setFormData({ ...formData, phoneNumber: e.target.value })
                }
                className={`w-full rounded-lg border ${
                  errors.phoneNumber ? "border-red-300" : "border-neutral-200"
                } px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
                placeholder="+966 5X XXX XXXX"
              />
              {errors.phoneNumber && (
                <p className="mt-1 text-xs text-red-600">
                  {errors.phoneNumber}
                </p>
              )}
            </div>

            {/* Services Offered - Multi-select */}
            <div className="md:col-span-2">
              <label
                htmlFor="services"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.servicesOffered}
              </label>
              <p className="text-xs text-neutral-500 mb-2">{t.servicesHelp}</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 p-4 border border-neutral-200 rounded-lg max-h-64 overflow-y-auto">
                {SERVICE_KEYS.map((serviceKey) => {
                  const service = SERVICES[serviceKey];
                  const isSelected = formData.services.includes(serviceKey);
                  return (
                    <label
                      key={serviceKey}
                      className={`flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-all ${
                        isSelected
                          ? "bg-brand-green/10 border-2 border-brand-green"
                          : "bg-neutral-50 border-2 border-transparent hover:border-neutral-200"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setFormData({
                              ...formData,
                              services: [...formData.services, serviceKey],
                            });
                          } else {
                            setFormData({
                              ...formData,
                              services: formData.services.filter(
                                (s) => s !== serviceKey,
                              ),
                            });
                          }
                        }}
                        className="mt-1 h-4 w-4 rounded border-neutral-300 text-brand-green focus:ring-brand-green"
                      />
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="text-lg">{service.icon}</span>
                          <span className="font-medium text-sm text-brand-ink">
                            {service.name[lang]}
                          </span>
                        </div>
                        <p className="text-xs text-neutral-600 mt-1">
                          {service.summary[lang]}
                        </p>
                      </div>
                    </label>
                  );
                })}
              </div>
              {formData.services.length > 0 && (
                <p className="mt-2 text-xs text-brand-green">
                  {formData.services.length}{" "}
                  {lang === "ar" ? "خدمة محددة" : "service(s) selected"}
                </p>
              )}
            </div>

            {/* Plan Agent Info Box - REMOVED */}
            {/* Agent count information removed as it was confusing for users */}

            {/* Agent Count - Auto-populated based on package */}
            <div className="md:col-span-2">
              <label
                htmlFor="agentCount"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.agentCount}
              </label>
              <div className="relative">
                <input
                  id="agentCount"
                  type="text"
                  value={formData.agentCount}
                  disabled={true}
                  className="w-full rounded-lg border border-neutral-200 bg-neutral-50 px-4 py-3 text-sm text-neutral-700 cursor-not-allowed"
                  placeholder={
                    lang === "ar"
                      ? "يتم التحديد تلقائياً حسب الباقة"
                      : "Auto-set based on package"
                  }
                />
                {selectedPlan && (
                  <div className="absolute inset-y-0 right-3 flex items-center">
                    <span className="text-xs font-semibold text-brand-green">
                      {lang === "ar" ? "حسب الباقة" : "Package-based"}
                    </span>
                  </div>
                )}
              </div>
              <p className="mt-1 text-xs text-neutral-500">
                {lang === "ar"
                  ? `عدد الوكلاء محدد حسب باقتك. باقتك الحالية تشمل ${formData.agentCount} وكيل${Number(formData.agentCount) > 1 ? "" : ""}.`
                  : `Agent count is set by your package. Your current package includes ${formData.agentCount} agent${Number(formData.agentCount) > 1 ? "s" : ""}.`}
              </p>
              {selectedPlan && canUpgrade(selectedPlan) && (
                <button
                  type="button"
                  onClick={() =>
                    router.push(`/${lang}/pricing?change_plan=true`)
                  }
                  className="mt-2 text-xs text-brand-green hover:underline font-medium"
                >
                  {lang === "ar"
                    ? "🚀 ترقية الباقة للحصول على وكلاء إضافيين"
                    : "🚀 Upgrade package for more agents"}
                </button>
              )}
              {errors.agentCount && (
                <p className="mt-1 text-xs text-red-600">{errors.agentCount}</p>
              )}
            </div>

            {/* Agent Use Case - Pre-filled based on package */}
            <div className="md:col-span-2">
              <div className="flex items-center justify-between mb-1">
                <label
                  htmlFor="agentUseCase"
                  className="block text-sm font-medium text-neutral-700"
                >
                  {t.agentUseCase}
                </label>
                {selectedPlan && (
                  <button
                    type="button"
                    onClick={() => {
                      const agentUseCase = getAgentUseCaseForPlan(
                        selectedPlan,
                        lang,
                      );
                      setFormData({ ...formData, agentUseCase });
                      logger.info("Manually refreshed agent use case", {
                        plan: selectedPlan,
                        agentUseCase,
                      });
                    }}
                    className="text-xs text-brand-green hover:underline font-medium"
                  >
                    {lang === "ar"
                      ? "🔄 تحديث حسب الباقة"
                      : "🔄 Refresh from package"}
                  </button>
                )}
              </div>
              <textarea
                id="agentUseCase"
                rows={3}
                value={formData.agentUseCase}
                onChange={(e) =>
                  setFormData({ ...formData, agentUseCase: e.target.value })
                }
                className="w-full rounded-lg border border-neutral-200 px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
                placeholder={
                  lang === "ar"
                    ? "مثلاً: حجز المواعيد، الرد على الاستفسارات"
                    : "e.g., Appointment booking, answering inquiries"
                }
              />
              <p className="mt-1 text-xs text-neutral-500">
                {lang === "ar"
                  ? "تم ملء هذا الحقل مسبقاً بناءً على ميزات باقتك. يمكنك تعديله حسب احتياجاتك."
                  : "Pre-filled based on your package features. You can customize as needed."}
              </p>
            </div>

            {/* Company Description */}
            <div className="md:col-span-2">
              <label
                htmlFor="companyDescription"
                className="block text-sm font-medium text-neutral-700 mb-1"
              >
                {t.companyDescription}
              </label>
              <textarea
                id="companyDescription"
                rows={4}
                value={formData.companyDescription}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    companyDescription: e.target.value,
                  })
                }
                className="w-full rounded-lg border border-neutral-200 px-4 py-3 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
                placeholder={t.companyDescriptionPlaceholder}
              />
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-col gap-3 sm:flex-row sm:justify-between">
            <button
              type="button"
              onClick={handleSkip}
              className="order-2 rounded-lg border border-neutral-200 px-6 py-3 text-sm font-semibold text-neutral-600 transition-all hover:bg-neutral-50 sm:order-1"
            >
              {t.skipButton}
            </button>

            <button
              type="submit"
              disabled={loading}
              className="order-1 rounded-lg bg-brand-green px-6 py-3 text-sm font-semibold text-white transition-all hover:bg-brand-greenHover disabled:cursor-not-allowed disabled:opacity-50 sm:order-2"
            >
              {loading
                ? lang === "ar"
                  ? "جاري الحفظ..."
                  : "Saving..."
                : t.continueButton}
            </button>
          </div>
        </form>
      </div>
    </main>
  );
}
