'use client';

import {
  Info, Image as ImageIcon, Shield, Truck, CreditCard, User, Link2, Settings,
  ExternalLink, ChevronRight, Copy, Plus, Trash2, HeadphonesIcon, Star, Loader2, AlertCircle, Upload, X
} from 'lucide-react';
import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { api } from '@/lib/api';
import { Toaster, toast } from 'react-hot-toast';

export default function SellerProfilePage() {
  const tabs = [
    { id: 'basic', icon: Info, label: 'Thông tin cơ bản' },
    { id: 'images', icon: ImageIcon, label: 'Hình ảnh & Banner' },
    { id: 'policies', icon: Shield, label: 'Chính sách & FAQ' },
    { id: 'settings', icon: Settings, label: 'Cài đặt khác' },
  ];

  const quickLinks = [
    { label: 'Quản lý sản phẩm', href: '/vi/seller/products' },
    { label: 'Quản lý đơn hàng', href: '/vi/seller/orders' },
    { label: 'Ví & Thanh toán', href: '/vi/seller/wallet' },
    { label: 'Thống kê doanh thu', href: '/vi/seller/dashboard' },
  ];

  const [activeTab, setActiveTab] = useState('basic');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const [uploadingBanner, setUploadingBanner] = useState(false);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  const avatarInputRef = useRef<HTMLInputElement>(null);
  const bannerInputRef = useRef<HTMLInputElement>(null);

  const [profile, setProfile] = useState({
    shopName: '',
    shopSlug: '',
    status: 'ACTIVE',
    avatarUrl: '',
    bannerUrl: '',
    description: '',
    loginInstruction: '',
    announcement: '',
    supportHours: '',
    facebookUrl: '',
    discordUrl: '',
    youtubeUrl: '',
    telegramUrl: '',
    policies: [] as { title: string, content: string }[],
    faqs: [] as { question: string, answer: string }[]
  });

  useEffect(() => {
    api.get('/seller/profile')
      .then(res => {
        if (res.data) {
          setProfile({
            shopName: res.data.shopName || '',
            shopSlug: res.data.shopSlug || '',
            status: res.data.status || 'ACTIVE',
            avatarUrl: res.data.avatarUrl || '',
            bannerUrl: res.data.bannerUrl || '',
            description: res.data.description || '',
            loginInstruction: res.data.loginInstruction || '',
            announcement: res.data.announcement || '',
            supportHours: res.data.supportHours || '',
            facebookUrl: res.data.facebookUrl || '',
            discordUrl: res.data.discordUrl || '',
            youtubeUrl: res.data.youtubeUrl || '',
            telegramUrl: res.data.telegramUrl || '',
            policies: res.data.policies || [],
            faqs: res.data.faqs || []
          });
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const generateSlug = (text: string) => {
    return text.toString().toLowerCase()
      .replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a")
      .replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e")
      .replace(/ì|í|ị|ỉ|ĩ/g, "i")
      .replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o")
      .replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u")
      .replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y")
      .replace(/đ/g, "d")
      .replace(/\u0300|\u0301|\u0303|\u0309|\u0323/g, "")
      .replace(/\u02C6|\u0306|\u031B/g, "")
      .replace(/\s+/g, '-')
      .replace(/[^\w\-]+/g, '')
      .replace(/\-\-+/g, '-')
      .replace(/^-+/, '')
      .replace(/-+$/, '');
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setProfile(prev => {
      const updated = { ...prev, [name]: value };
      if (name === 'shopName') {
        updated.shopSlug = generateSlug(value).substring(0, 60);
        if (errors['shopSlug']) setErrors(prevErr => ({ ...prevErr, shopSlug: '' }));
      }
      return updated;
    });
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const handleUploadImage = async (file: File, field: 'avatarUrl' | 'bannerUrl') => {
    const setUploading = field === 'avatarUrl' ? setUploadingAvatar : setUploadingBanner;
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      const res = await api.post('/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      setProfile(prev => ({ ...prev, [field]: res.data.url }));
      toast.success(field === 'avatarUrl' ? 'Đã tải logo lên!' : 'Đã tải banner lên!');
    } catch (err: any) {
      toast.error('Lỗi khi tải ảnh lên: ' + (err.response?.data?.message || err.message));
    } finally {
      setUploading(false);
    }
  };

  const validate = () => {
    const newErrors: { [key: string]: string } = {};
    if (!profile.shopName.trim()) newErrors.shopName = 'Vui lòng nhập tên gian hàng';
    if (!profile.shopSlug.trim()) newErrors.shopSlug = 'Vui lòng nhập đường dẫn gian hàng';
    if (!profile.description?.trim()) newErrors.description = 'Vui lòng nhập mô tả gian hàng';
    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) {
      toast.error('Vui lòng kiểm tra lại các trường bị lỗi!');
      setActiveTab('basic');
      return false;
    }
    return true;
  };

  const handleSave = async () => {
    if (!validate()) return;
    setSaving(true);
    try {
      await api.put('/seller/profile', profile);
      toast.success('Đã lưu cấu hình gian hàng thành công!', { position: 'top-center', duration: 4000 });
    } catch (err: any) {
      console.error(err);
      toast.error(err.response?.data?.message || 'Có lỗi xảy ra khi lưu!', { position: 'top-center', duration: 4000 });
      if (err.response?.status === 409) {
        setErrors(prev => ({ ...prev, shopSlug: 'Đường dẫn này đã được sử dụng' }));
        setActiveTab('basic');
      }
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="relative min-h-[calc(100vh-64px)] pb-24">
      <Toaster />

      {/* Top Tabs */}
      <div className="sticky top-0 z-10 bg-background border-b border-border/50 overflow-x-auto">
        <div className="flex px-4 md:px-0 space-x-1">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors border-b-2 ${
                activeTab === tab.id
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground hover:bg-white/5'
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Main Content Area */}
      <div className="flex flex-col lg:flex-row gap-6 mt-6">

        {/* Left Column (Forms) */}
        <div className="flex-1 space-y-6">

          {/* ===================== TAB: THÔNG TIN CƠ BẢN ===================== */}
          {activeTab === 'basic' && (
            <>
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-bold text-white mb-6">Thông tin cơ bản</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Tên gian hàng <span className="text-red-500">*</span></label>
                    <input
                      type="text" name="shopName" value={profile.shopName} onChange={handleChange} maxLength={60}
                      className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-colors ${errors.shopName ? 'border-red-500' : 'border-white/10 focus:border-primary'}`}
                    />
                    {errors.shopName ? (
                      <p className="text-xs text-red-500 flex items-center gap-1"><AlertCircle className="w-3 h-3" /> {errors.shopName}</p>
                    ) : (
                      <div className="flex justify-between">
                        <p className="text-xs text-gray-500">Tên hiển thị trên trang gian hàng.</p>
                        <p className="text-xs text-gray-500">{profile.shopName.length}/60</p>
                      </div>
                    )}
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Đường dẫn gian hàng <span className="text-red-500">*</span></label>
                    <input
                      type="text" name="shopSlug" value={profile.shopSlug} onChange={handleChange} maxLength={60}
                      className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-colors ${errors.shopSlug ? 'border-red-500' : 'border-white/10 focus:border-primary'}`}
                    />
                    {errors.shopSlug ? (
                      <p className="text-xs text-red-500 flex items-center gap-1"><AlertCircle className="w-3 h-3" /> {errors.shopSlug}</p>
                    ) : (
                      <div className="flex justify-between">
                        <p className="text-xs text-gray-500">/sellers/{profile.shopSlug || '...'}</p>
                        <p className="text-xs text-gray-500">{profile.shopSlug.length}/60</p>
                      </div>
                    )}
                  </div>
                </div>
                <div className="space-y-2 w-full md:w-1/2">
                  <label className="text-sm font-medium text-gray-300">Trạng thái gian hàng</label>
                  <div className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-2.5 flex items-center">
                    <span className={`text-xs font-medium px-3 py-1 rounded-full border ${profile.status === 'ACTIVE' ? 'bg-green-500/10 text-green-400 border-green-500/20' : 'bg-red-500/10 text-red-400 border-red-500/20'}`}>
                      {profile.status === 'ACTIVE' ? 'Đang hoạt động' : 'Tạm khóa'}
                    </span>
                  </div>
                  <p className="text-xs text-gray-500">Trạng thái do Admin xét duyệt.</p>
                </div>
              </div>

              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-bold text-white mb-6">Giới thiệu gian hàng</h3>
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-300">Mô tả gian hàng <span className="text-red-500">*</span></label>
                  <div className={`w-full bg-[#0a0b0d] border rounded-xl overflow-hidden ${errors.description ? 'border-red-500' : 'border-white/10 focus-within:border-primary'}`}>
                    <textarea
                      name="description" value={profile.description} onChange={handleChange} maxLength={2000}
                      className="w-full bg-transparent p-4 text-sm text-gray-300 focus:outline-none min-h-[200px] leading-relaxed resize-y"
                      placeholder="Mô tả chi tiết về gian hàng, dịch vụ, sản phẩm..."
                    />
                  </div>
                  {errors.description ? (
                    <p className="text-xs text-red-500 flex items-center gap-1"><AlertCircle className="w-3 h-3" /> {errors.description}</p>
                  ) : (
                    <div className="flex justify-end"><p className="text-xs text-gray-500">{(profile.description || '').length}/2000</p></div>
                  )}
                </div>
              </div>

              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-bold text-white mb-6">Hướng dẫn & Thông báo</h3>
                <div className="space-y-6">
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Hướng dẫn giao hàng chung</label>
                    <textarea
                      name="loginInstruction" value={profile.loginInstruction} onChange={handleChange} maxLength={1000}
                      placeholder="Hướng dẫn cách nhận/sử dụng sản phẩm sau khi mua..."
                      className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl p-4 text-sm text-gray-300 focus:outline-none focus:border-primary min-h-[120px] resize-y"
                    />
                    <div className="flex justify-end"><p className="text-xs text-gray-500">{(profile.loginInstruction || '').length}/1000</p></div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Thông báo từ shop</label>
                    <textarea
                      name="announcement" value={profile.announcement} onChange={handleChange} maxLength={280}
                      className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-sm text-gray-300 focus:outline-none focus:border-primary min-h-[80px]"
                      placeholder="Thông báo lịch giao, ưu đãi, lưu ý..."
                    />
                    <div className="flex justify-between">
                      <p className="text-xs text-gray-500">Hiển thị ở đầu trang gian hàng.</p>
                      <p className="text-xs text-gray-500">{(profile.announcement || '').length}/280</p>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Giờ hỗ trợ</label>
                    <input
                      type="text" name="supportHours" value={profile.supportHours} onChange={handleChange} maxLength={50}
                      placeholder="VD: 08:00 - 23:00"
                      className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary"
                    />
                    <div className="flex justify-between">
                      <p className="text-xs text-gray-500">Hiển thị ở sidebar trang gian hàng.</p>
                      <p className="text-xs text-gray-500">{(profile.supportHours || '').length}/50</p>
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}

          {/* ===================== TAB: HÌNH ẢNH & BANNER ===================== */}
          {activeTab === 'images' && (
            <>
              {/* Avatar / Logo */}
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <div className="mb-6">
                  <h3 className="text-lg font-bold text-white">Logo / Avatar gian hàng</h3>
                  <p className="text-xs text-gray-500 mt-1">Hiển thị dạng hình tròn bên cạnh tên gian hàng. Tỷ lệ 1:1, khuyến nghị 200×200px.</p>
                </div>

                <div className="flex flex-col sm:flex-row items-start gap-8">
                  {/* Preview */}
                  <div className="flex flex-col items-center gap-3">
                    <div className="w-28 h-28 rounded-full border-4 border-primary/30 overflow-hidden bg-gradient-to-br from-indigo-900 to-purple-900 flex items-center justify-center text-white font-black text-3xl relative group">
                      {profile.avatarUrl ? (
                        <img src={profile.avatarUrl} alt="Avatar" className="w-full h-full object-cover" />
                      ) : (
                        <span>{profile.shopName?.[0]?.toUpperCase() || 'S'}</span>
                      )}
                    </div>
                    {profile.avatarUrl && (
                      <button
                        onClick={() => setProfile(p => ({ ...p, avatarUrl: '' }))}
                        className="text-xs text-red-400 hover:text-red-300 flex items-center gap-1"
                      >
                        <X className="w-3 h-3" /> Xóa ảnh
                      </button>
                    )}
                  </div>

                  {/* Upload area */}
                  <div className="flex-1">
                    <input
                      ref={avatarInputRef}
                      type="file" accept="image/*" className="hidden"
                      onChange={(e) => e.target.files?.[0] && handleUploadImage(e.target.files[0], 'avatarUrl')}
                    />
                    <div
                      onClick={() => avatarInputRef.current?.click()}
                      className="w-full h-40 border-2 border-dashed border-white/20 hover:border-primary/50 rounded-2xl flex flex-col items-center justify-center gap-3 cursor-pointer transition-colors group bg-white/[0.02] hover:bg-white/5"
                    >
                      {uploadingAvatar ? (
                        <Loader2 className="w-8 h-8 animate-spin text-primary" />
                      ) : (
                        <>
                          <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                            <Upload className="w-6 h-6 text-primary" />
                          </div>
                          <div className="text-center">
                            <p className="text-sm font-medium text-white">Bấm để tải ảnh lên</p>
                            <p className="text-xs text-gray-500 mt-1">PNG, JPG, WEBP · Tối đa 5MB</p>
                          </div>
                        </>
                      )}
                    </div>
                    {profile.avatarUrl && (
                      <div className="mt-3 p-3 bg-green-500/10 border border-green-500/20 rounded-lg">
                        <p className="text-xs text-green-400 break-all">{profile.avatarUrl}</p>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Banner */}
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <div className="mb-6">
                  <h3 className="text-lg font-bold text-white">Ảnh Banner gian hàng</h3>
                  <p className="text-xs text-gray-500 mt-1">Hiển thị ở đầu trang gian hàng công khai. Tỷ lệ 16:5, khuyến nghị 1280×400px.</p>
                </div>

                {/* Banner Preview */}
                <div className="w-full h-40 rounded-2xl overflow-hidden mb-6 relative border border-white/10">
                  {profile.bannerUrl ? (
                    <>
                      <img src={profile.bannerUrl} alt="Banner" className="w-full h-full object-cover" />
                      <button
                        onClick={() => setProfile(p => ({ ...p, bannerUrl: '' }))}
                        className="absolute top-3 right-3 bg-black/60 hover:bg-black/80 text-white p-1.5 rounded-lg transition-colors"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </>
                  ) : (
                    <div className="w-full h-full bg-gradient-to-br from-indigo-900 via-purple-900 to-red-900 flex items-center justify-center">
                      <p className="text-white/40 text-sm">Chưa có ảnh banner</p>
                    </div>
                  )}
                </div>

                {/* Upload */}
                <input
                  ref={bannerInputRef}
                  type="file" accept="image/*" className="hidden"
                  onChange={(e) => e.target.files?.[0] && handleUploadImage(e.target.files[0], 'bannerUrl')}
                />
                <div
                  onClick={() => bannerInputRef.current?.click()}
                  className="w-full h-36 border-2 border-dashed border-white/20 hover:border-primary/50 rounded-2xl flex flex-col items-center justify-center gap-3 cursor-pointer transition-colors group bg-white/[0.02] hover:bg-white/5"
                >
                  {uploadingBanner ? (
                    <Loader2 className="w-8 h-8 animate-spin text-primary" />
                  ) : (
                    <>
                      <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                        <Upload className="w-6 h-6 text-primary" />
                      </div>
                      <div className="text-center">
                        <p className="text-sm font-medium text-white">Bấm để tải banner lên</p>
                        <p className="text-xs text-gray-500 mt-1">PNG, JPG, WEBP · Tối đa 5MB · Nên dùng 1280×400px</p>
                      </div>
                    </>
                  )}
                </div>

                {profile.bannerUrl && (
                  <div className="mt-3 p-3 bg-green-500/10 border border-green-500/20 rounded-lg">
                    <p className="text-xs text-green-400 break-all">{profile.bannerUrl}</p>
                  </div>
                )}
              </div>

              <div className="bg-blue-500/10 border border-blue-500/20 rounded-xl p-4 flex gap-3">
                <Info className="w-5 h-5 text-blue-400 shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-blue-300">Lưu ý</p>
                  <p className="text-xs text-blue-400/80 mt-1">Sau khi tải ảnh lên thành công, bạn cần nhấn <strong>"Lưu thay đổi"</strong> để xác nhận lưu vào hồ sơ gian hàng.</p>
                </div>
              </div>
            </>
          )}

          {/* ===================== TAB: CHÍNH SÁCH & FAQ ===================== */}
          {activeTab === 'policies' && (
            <>
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <div className="flex justify-between items-center mb-6">
                  <div>
                    <h3 className="text-lg font-bold text-white">Chính sách của shop</h3>
                    <p className="text-xs text-gray-500 mt-1">Hiển thị ở trang công khai gian hàng.</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setProfile(p => ({ ...p, policies: [...p.policies, { title: '', content: '' }] }))}
                    className="flex items-center gap-1.5 text-xs font-medium bg-white/5 hover:bg-white/10 text-white px-3 py-1.5 rounded-lg transition-colors border border-white/10"
                  >
                    <Plus className="w-3.5 h-3.5" /> Thêm chính sách
                  </button>
                </div>
                {profile.policies.length === 0 && (
                  <div className="text-center py-10 border-2 border-dashed border-white/10 rounded-xl">
                    <Shield className="w-8 h-8 text-gray-600 mx-auto mb-3" />
                    <p className="text-sm text-gray-500">Chưa có chính sách nào. Nhấn "+ Thêm chính sách" để bắt đầu.</p>
                  </div>
                )}
                <div className="space-y-4">
                  {profile.policies.map((policy, index) => (
                    <div key={index} className="border border-white/10 rounded-xl bg-[#0a0b0d] overflow-hidden">
                      <div className="flex justify-between items-center bg-white/5 px-4 py-3 border-b border-white/10">
                        <span className="text-sm font-medium text-gray-300">Chính sách {index + 1}</span>
                        <button type="button" onClick={() => setProfile(p => ({ ...p, policies: p.policies.filter((_, i) => i !== index) }))} className="text-gray-500 hover:text-red-400 transition-colors">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                      <div className="p-4 space-y-3">
                        <input type="text" value={policy.title} maxLength={100}
                          onChange={(e) => { const n = [...profile.policies]; n[index].title = e.target.value; setProfile({ ...profile, policies: n }); }}
                          placeholder="Tiêu đề (VD: Chính sách bảo hành)"
                          className="w-full bg-transparent border border-white/10 rounded-lg px-4 py-2.5 text-sm text-white focus:outline-none focus:border-primary" />
                        <textarea value={policy.content} maxLength={500}
                          onChange={(e) => { const n = [...profile.policies]; n[index].content = e.target.value; setProfile({ ...profile, policies: n }); }}
                          placeholder="Nội dung chính sách..."
                          className="w-full bg-transparent border border-white/10 rounded-lg px-4 py-3 text-sm text-gray-300 focus:outline-none focus:border-primary min-h-[100px] resize-y" />
                        <div className="text-right text-xs text-gray-500">{policy.content.length}/500</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
                <div className="flex justify-between items-center mb-6">
                  <div>
                    <h3 className="text-lg font-bold text-white">Câu hỏi thường gặp (FAQ)</h3>
                    <p className="text-xs text-gray-500 mt-1">Hiển thị ở trang công khai gian hàng.</p>
                  </div>
                  <button type="button"
                    onClick={() => setProfile(p => ({ ...p, faqs: [...p.faqs, { question: '', answer: '' }] }))}
                    className="flex items-center gap-1.5 text-xs font-medium bg-white/5 hover:bg-white/10 text-white px-3 py-1.5 rounded-lg transition-colors border border-white/10">
                    <Plus className="w-3.5 h-3.5" /> Thêm câu hỏi
                  </button>
                </div>
                {profile.faqs.length === 0 && (
                  <div className="text-center py-10 border-2 border-dashed border-white/10 rounded-xl">
                    <Info className="w-8 h-8 text-gray-600 mx-auto mb-3" />
                    <p className="text-sm text-gray-500">Chưa có câu hỏi nào. Nhấn "+ Thêm câu hỏi" để bắt đầu.</p>
                  </div>
                )}
                <div className="space-y-4">
                  {profile.faqs.map((faq, index) => (
                    <div key={index} className="border border-white/10 rounded-xl bg-[#0a0b0d] overflow-hidden">
                      <div className="flex justify-between items-center bg-white/5 px-4 py-3 border-b border-white/10">
                        <span className="text-sm font-medium text-gray-300">Câu hỏi {index + 1}</span>
                        <button type="button" onClick={() => setProfile(p => ({ ...p, faqs: p.faqs.filter((_, i) => i !== index) }))} className="text-gray-500 hover:text-red-400 transition-colors">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                      <div className="p-4 space-y-3">
                        <input type="text" value={faq.question} maxLength={150}
                          onChange={(e) => { const n = [...profile.faqs]; n[index].question = e.target.value; setProfile({ ...profile, faqs: n }); }}
                          placeholder="Câu hỏi..."
                          className="w-full bg-transparent border border-white/10 rounded-lg px-4 py-2.5 text-sm text-white focus:outline-none focus:border-primary" />
                        <textarea value={faq.answer} maxLength={500}
                          onChange={(e) => { const n = [...profile.faqs]; n[index].answer = e.target.value; setProfile({ ...profile, faqs: n }); }}
                          placeholder="Trả lời..."
                          className="w-full bg-transparent border border-white/10 rounded-lg px-4 py-3 text-sm text-gray-300 focus:outline-none focus:border-primary min-h-[100px] resize-y" />
                        <div className="text-right text-xs text-gray-500">{faq.answer.length}/500</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}

          {/* ===================== TAB: CÀI ĐẶT KHÁC ===================== */}
          {activeTab === 'settings' && (
            <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6 shadow-sm">
              <h3 className="text-lg font-bold text-white mb-6">Thống kê hiệu suất</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                {[
                  { label: 'Đánh giá tích cực', value: '100%', sub: 'Chưa có dữ liệu' },
                  { label: 'Giờ hỗ trợ', value: profile.supportHours || '-', sub: 'Hiển thị công khai' },
                  { label: 'Đơn hoàn thành', value: '0', sub: 'Tổng đơn hàng' },
                  { label: 'Tham gia từ', value: '-', sub: 'Ngày tạo gian hàng' },
                ].map((item, i) => (
                  <div key={i} className="space-y-1">
                    <p className="text-xs text-gray-400">{item.label}</p>
                    <p className="text-xl font-bold text-white">{item.value}</p>
                    <p className="text-xs text-gray-500">{item.sub}</p>
                  </div>
                ))}
              </div>
              <p className="text-xs text-gray-500 mt-6 pt-4 border-t border-white/5">Các chỉ số được hệ thống cập nhật mỗi ngày.</p>
            </div>
          )}
        </div>

        {/* Right Column (Widgets) */}
        <div className="w-full lg:w-[300px] shrink-0 space-y-6">

          {/* Widget: Preview */}
          <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5 shadow-sm">
            <div className="flex justify-between items-center mb-4">
              <h4 className="text-sm font-bold text-white">Xem trước gian hàng</h4>
              {profile.shopSlug && (
                <Link href={`/vi/sellers/${profile.shopSlug}`} target="_blank" className="text-xs font-medium text-gray-400 hover:text-white flex items-center gap-1 transition-colors">
                  Xem trang <ExternalLink className="w-3 h-3" />
                </Link>
              )}
            </div>

            <div className="bg-[#0a0b0d] rounded-xl overflow-hidden border border-white/10">
              {/* Banner mini */}
              <div className="h-28 relative overflow-hidden">
                {profile.bannerUrl ? (
                  <img src={profile.bannerUrl} alt="Banner" className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full bg-gradient-to-br from-indigo-900 to-purple-900" />
                )}
                {/* Avatar overlay */}
                <div className="absolute bottom-0 left-4 transform translate-y-1/2">
                  <div className="w-12 h-12 rounded-full border-2 border-[#0a0b0d] overflow-hidden bg-gradient-to-br from-indigo-700 to-purple-700 flex items-center justify-center text-white font-black">
                    {profile.avatarUrl ? (
                      <img src={profile.avatarUrl} alt="Avatar" className="w-full h-full object-cover" />
                    ) : (
                      <span className="text-base">{profile.shopName?.[0]?.toUpperCase() || 'S'}</span>
                    )}
                  </div>
                </div>
              </div>

              <div className="p-4 pt-8">
                <h4 className="text-sm font-bold text-white leading-snug mb-1">
                  {profile.shopName || 'Tên gian hàng'}
                </h4>
                <p className="text-xs text-gray-400 line-clamp-2 mb-4 leading-relaxed">
                  {profile.description || 'Chưa có mô tả...'}
                </p>
                <div className="flex items-center justify-between bg-white/5 rounded-lg p-3 text-center">
                  <div>
                    <div className="flex items-center justify-center gap-0.5 text-yellow-500 mb-0.5">
                      <Star className="w-3 h-3 fill-current" />
                      <span className="text-xs font-bold">5.0</span>
                    </div>
                    <span className="text-[10px] text-gray-500">Đánh giá</span>
                  </div>
                  <div className="w-px h-6 bg-white/10"></div>
                  <div>
                    <div className="text-xs font-bold text-white mb-0.5">0</div>
                    <span className="text-[10px] text-gray-500">Đơn đã bán</span>
                  </div>
                  <div className="w-px h-6 bg-white/10"></div>
                  <div>
                    <div className="text-xs font-bold text-green-400 mb-0.5">●</div>
                    <span className="text-[10px] text-gray-500">Online</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Widget: Quick Links */}
          <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5 shadow-sm">
            <h4 className="text-sm font-bold text-white mb-4">Liên kết nhanh</h4>
            <div className="space-y-1">
              {quickLinks.map((link, idx) => (
                <Link key={idx} href={link.href} className="flex items-center justify-between py-2.5 text-sm text-gray-300 hover:text-white transition-colors group">
                  <span>{link.label}</span>
                  <ChevronRight className="w-4 h-4 text-gray-600 group-hover:text-white transition-colors" />
                </Link>
              ))}
            </div>
          </div>

          {/* Widget: Support */}
          <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5 shadow-sm">
            <h4 className="text-sm font-bold text-white mb-1">Hỗ trợ cần thiết?</h4>
            <p className="text-xs text-gray-500 mb-4">Gặp vấn đề khi quản lý gian hàng?</p>
            <button className="w-full flex items-center justify-center gap-2 py-2.5 bg-red-500/10 text-red-500 hover:bg-red-500/20 text-sm font-semibold rounded-xl transition-colors">
              <HeadphonesIcon className="w-4 h-4" /> Liên hệ hỗ trợ
            </button>
          </div>
        </div>
      </div>

      {/* Bottom Sticky Footer */}
      <div className="fixed bottom-0 left-0 md:left-64 right-0 bg-[#0a0b0d]/90 backdrop-blur-md border-t border-white/5 p-4 flex justify-end gap-3 z-20">
        <button className="px-6 py-2.5 text-sm font-semibold text-gray-300 hover:text-white transition-colors">
          Hủy bỏ
        </button>
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-6 py-2.5 flex items-center gap-2 text-sm font-semibold bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white rounded-xl transition-colors shadow-lg shadow-red-600/20"
        >
          {saving && <Loader2 className="w-4 h-4 animate-spin" />}
          {saving ? 'Đang lưu...' : 'Lưu thay đổi'}
        </button>
      </div>
    </div>
  );
}
