'use client';

import { useEffect, useRef, useState, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useSearchParams } from 'next/navigation';
import toast from 'react-hot-toast';
import api from '@/lib/axios';
import ScratchCard from '@/components/ScratchCard';
import Confetti from '@/components/Confetti';
import { formatTimestamp, formatPromoPeriod } from '@/lib/dateUtils';

const schema = z.object({
  promotion_id: z.string().min(1, 'Pilih promosi'),
  imei: z.string().min(1, 'IMEI wajib diisi').max(20, 'IMEI maksimal 20 karakter'),
  outlet_code: z.string().min(1, 'Pilih atau scan outlet'),
});
type FormData = z.infer<typeof schema>;

interface Promotion {
  id: number;
  name: string;
  reward_method: string;
  description?: string;
  start_date?: string;
  end_date?: string;
  start_time?: string | null;
  end_time?: string | null;
  start_datetime?: string | null;
  end_datetime?: string | null;
  banner_image?: string | null;
}
interface ClaimResult {
  claim_id: number;
  status: string;
  lottery_number?: string;
  reward_data?: { reward_name?: string; reward_type?: string; reward_value?: number; } | null;
}
interface ClaimHistory {
  id: number; imei: string; status: string; lottery_number: string | null;
  points_awarded: number; claimed_at: string; processed_at: string | null;
  promotion: { id: number; name: string } | null;
  device_model: { model_name: string; brand: string } | null;
}

const statusConfig: Record<string, { label: string; className: string }> = {
  pending:  { label: 'Menunggu',   className: 'bg-yellow-100 text-yellow-700' },
  approved: { label: 'Disetujui',  className: 'bg-green-100 text-green-700' },
  rejected: { label: 'Ditolak',    className: 'bg-red-100 text-red-700' },
  expired:  { label: 'Kadaluarsa', className: 'bg-gray-100 text-gray-500' },
};

const methodLabel: Record<string, string> = {
  hadiah_langsung: 'Hadiah Langsung',
  undian: 'Undian',
  point_reward: 'Point Reward',
};
const methodColor: Record<string, string> = {
  hadiah_langsung: 'bg-blue-100 text-blue-700',
  undian: 'bg-yellow-100 text-yellow-700',
  point_reward: 'bg-green-100 text-green-700',
};

// ── Error Modal ───────────────────────────────────────────────────────────────
function ErrorModal({ message, onClose }: { message: string; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 text-center">
        {/* Icon bulat silang merah */}
        <div className="flex items-center justify-center mb-4">
          <div className="w-16 h-16 rounded-full bg-red-100 flex items-center justify-center">
            <svg className="w-8 h-8 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
        </div>
        <h3 className="text-base font-bold text-gray-800 mb-2">Klaim Gagal</h3>
        <p className="text-sm text-gray-600 leading-relaxed">{message}</p>
        <button onClick={onClose}
          className="mt-5 w-full bg-red-600 text-white py-2.5 rounded-lg text-sm font-medium hover:bg-red-700 transition">
          Tutup
        </button>
      </div>
    </div>
  );
}

// ── Math CAPTCHA ──────────────────────────────────────────────────────────────
function MathCaptcha({ onVerified }: { onVerified: (ok: boolean) => void }) {
  const [a] = useState(() => Math.floor(Math.random() * 9) + 1);
  const [b] = useState(() => Math.floor(Math.random() * 9) + 1);
  const [input, setInput] = useState('');
  const [error, setError] = useState(false);

  const verify = () => {
    if (parseInt(input) === a + b) {
      onVerified(true);
    } else {
      setError(true);
      setInput('');
      setTimeout(() => setError(false), 1500);
    }
  };

  return (
    <div className="border border-gray-200 rounded-xl p-4 bg-gray-50">
      <p className="text-xs text-gray-500 mb-2 font-medium">Verifikasi: Berapa hasil dari</p>
      <div className="flex items-center gap-3">
        <span className="text-lg font-bold text-gray-800 bg-white border rounded-lg px-3 py-1.5 select-none">
          {a} + {b} = ?
        </span>
        <input
          type="number" value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && verify()}
          placeholder="Jawaban"
          className={`w-24 border rounded-lg px-3 py-1.5 text-sm text-center focus:outline-none focus:ring-2 ${error ? 'border-red-400 ring-red-300 bg-red-50' : 'focus:ring-blue-500'}`}
          autoComplete="off"
        />
        <button type="button" onClick={verify}
          className="bg-blue-700 text-white px-3 py-1.5 rounded-lg text-sm hover:bg-blue-800">
          ✓
        </button>
      </div>
      {error && <p className="text-red-500 text-xs mt-1">Jawaban salah, coba lagi.</p>}
    </div>
  );
}

// ── Promotion Picker Modal ────────────────────────────────────────────────────
function PromotionPickerModal({
  promotions, onSelect, onClose,
}: {
  promotions: Promotion[];
  onSelect: (p: Promotion) => void;
  onClose: () => void;
}) {
  const [search, setSearch] = useState('');
  const filtered = promotions.filter(p =>
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    (p.description ?? '').toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/50 px-0 sm:px-4">
      <div className="bg-white w-full sm:max-w-lg rounded-t-2xl sm:rounded-2xl shadow-xl flex flex-col max-h-[85vh]">
        {/* Header */}
        <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b">
          <h2 className="text-base font-bold text-gray-800">Pilih Promosi</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">✕</button>
        </div>

        {/* Search */}
        <div className="px-4 py-3">
          <input
            value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Cari nama promosi..."
            className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            autoFocus
          />
        </div>

        {/* List */}
        <div className="overflow-y-auto flex-1 px-4 pb-4 space-y-3">
          {filtered.length === 0 ? (
            <p className="text-center text-gray-400 text-sm py-8">Tidak ada promosi ditemukan.</p>
          ) : filtered.map(p => (
            <button key={p.id} onClick={() => onSelect(p)}
              className="w-full text-left bg-white border border-gray-200 rounded-xl overflow-hidden hover:border-blue-400 hover:shadow-md transition group">
              {/* Banner */}
              {p.banner_image ? (
                <div className="w-full aspect-square bg-gray-100 overflow-hidden">
                  <img src={p.banner_image} alt={p.name}
                    className="w-full h-full object-contain group-hover:scale-105 transition-transform duration-300" />
                </div>
              ) : (
                <div className="w-full aspect-square bg-gradient-to-r from-blue-500 to-indigo-600 flex items-center justify-center">
                  <span className="text-white text-2xl">🎁</span>
                </div>
              )}
              {/* Info */}
              <div className="p-3">
                <div className="flex items-start justify-between gap-2">
                  <p className="font-semibold text-gray-800 text-sm leading-tight">{p.name}</p>
                  <span className={`flex-shrink-0 text-xs px-2 py-0.5 rounded-full font-medium ${methodColor[p.reward_method] ?? 'bg-gray-100 text-gray-600'}`}>
                    {methodLabel[p.reward_method] ?? p.reward_method}
                  </span>
                </div>
                {p.description && (
                  <p className="text-xs text-gray-500 mt-1 line-clamp-2">{p.description}</p>
                )}
                {(p.start_date || p.end_date) && (
                  <p className="text-xs text-gray-400 mt-1.5">
                    📅 {formatPromoPeriod(p.start_date, p.end_date, p.start_datetime, p.end_datetime)}
                  </p>
                )}
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────
export default function ClaimPage() {
  const [promotions, setPromotions]           = useState<Promotion[]>([]);
  const [selectedPromo, setSelectedPromo]     = useState<Promotion | null>(null);
  const [showPicker, setShowPicker]           = useState(false);
  const [loading, setLoading]                 = useState(false);
  const [result, setResult]                   = useState<ClaimResult | null>(null);
  const [budgetExhausted, setBudgetExhausted] = useState(false);
  const [errorModal, setErrorModal]           = useState<string | null>(null);
  const [captchaVerified, setCaptchaVerified] = useState(false);
  const [showScratch, setShowScratch]         = useState(false);
  const [showConfetti, setShowConfetti]       = useState(false);
  const [scanning, setScanning]               = useState(false);
  const [detectedOutlet, setDetectedOutlet]   = useState<string | null>(null);
  const [outletFromUrl, setOutletFromUrl]     = useState(false);
  const [outletLabel, setOutletLabel]         = useState<string | null>(null);
  const [outletLoading, setOutletLoading]     = useState(false);
  const [activeTab, setActiveTab]             = useState<'form' | 'history'>('form');
  const [history, setHistory]                 = useState<ClaimHistory[]>([]);
  const [historyLoading, setHistoryLoading]   = useState(false);
  const [historyPage, setHistoryPage]         = useState(1);
  const [historyLastPage, setHistoryLastPage] = useState(1);
  const [imeiScanning, setImeiScanning]     = useState(false);
  const scannerRef    = useRef<any>(null);
  const imeiScannerRef = useRef<any>(null);
  const scanDivId     = 'qr-reader';
  const imeiScanDivId = 'imei-barcode-reader';
  const searchParams  = useSearchParams();
  const presetPromotionId = searchParams.get('promotion_id');

  const { register, handleSubmit, setValue, reset, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const fetchHistory = useCallback(async (page = 1) => {
    setHistoryLoading(true);
    try {
      const res = await api.get(`/end-user/claims?page=${page}`);
      setHistory(res.data.data ?? []);
      setHistoryPage(res.data.meta?.current_page ?? 1);
      setHistoryLastPage(res.data.meta?.last_page ?? 1);
    } catch { toast.error('Gagal memuat riwayat klaim'); }
    finally { setHistoryLoading(false); }
  }, []);

  useEffect(() => {
    api.get('/end-user/promotions').then((r) => {
      const list: Promotion[] = r.data.data ?? [];
      setPromotions(list);
      
      if (presetPromotionId) {
        // If promotion_id in URL, auto-select it
        const found = list.find(p => String(p.id) === presetPromotionId);
        if (found) { 
          setSelectedPromo(found); 
          setValue('promotion_id', presetPromotionId); 
        }
      } else if (list.length > 0) {
        // Auto-show picker if there are promotions and no preset
        setTimeout(() => setShowPicker(true), 300);
      }
    }).catch(() => {});

    const stored = sessionStorage.getItem('outlet_code');
    if (stored) {
      setValue('outlet_code', stored);
      setDetectedOutlet(stored);
      fetchOutletLabel(stored);
      if (sessionStorage.getItem('outlet_from_url') === '1') setOutletFromUrl(true);
    }
  }, [setValue, presetPromotionId]);

  useEffect(() => {
    if (activeTab === 'history') fetchHistory(1);
  }, [activeTab, fetchHistory]);

  const handleSelectPromo = (p: Promotion) => {
    setSelectedPromo(p);
    setValue('promotion_id', String(p.id));
    setShowPicker(false);
  };

  const startScan = async () => {
    const { Html5Qrcode } = await import('html5-qrcode');
    setScanning(true);
    await new Promise(r => setTimeout(r, 50));
    try {
      const scanner = new Html5Qrcode(scanDivId);
      scannerRef.current = scanner;
      await scanner.start({ facingMode: 'environment' }, { fps: 10, qrbox: 250 },
        (text: string) => {
          let code = text;
          try { const url = new URL(text); const p = url.searchParams.get('outlet'); if (p) code = p; } catch {}
          setValue('outlet_code', code); setDetectedOutlet(code); fetchOutletLabel(code);
          sessionStorage.setItem('outlet_code', code);
          toast.success('QR Code berhasil dipindai');
          scanner.stop().then(() => setScanning(false));
        }, () => {});
    } catch {
      const isInsecure = location.protocol !== 'https:' && location.hostname !== 'localhost';
      toast.error(isInsecure ? 'Kamera membutuhkan koneksi HTTPS.' : 'Gagal membuka kamera.');
      setScanning(false);
    }
  };

  const stopScan = () => scannerRef.current?.stop().then(() => setScanning(false)).catch(() => setScanning(false));

  const fetchOutletLabel = async (code: string) => {
    setOutletLoading(true);
    try { const res = await api.get(`/outlet-info/${code}`); const d = res.data.data; setOutletLabel(`${d.name} - ${d.city}`); }
    catch { setOutletLabel(code); }
    finally { setOutletLoading(false); }
  };

  const clearOutlet = () => {
    setValue('outlet_code', ''); setDetectedOutlet(null); setOutletFromUrl(false); setOutletLabel(null);
    sessionStorage.removeItem('outlet_code'); sessionStorage.removeItem('outlet_from_url');
  };

  const startImeiScan = async () => {
    const { Html5Qrcode } = await import('html5-qrcode');
    await new Promise(r => setTimeout(r, 50));
    setImeiScanning(true);
    await new Promise(r => setTimeout(r, 50));
    try {
      const scanner = new Html5Qrcode(imeiScanDivId);
      imeiScannerRef.current = scanner;
      await scanner.start({ facingMode: 'environment' }, { fps: 10, qrbox: { width: 280, height: 100 } },
        (text: string) => { setValue('imei', text.slice(0, 20)); toast.success('Barcode IMEI berhasil dipindai'); scanner.stop().then(() => setImeiScanning(false)); },
        () => {});
    } catch {
      const isInsecure = location.protocol !== 'https:' && location.hostname !== 'localhost';
      toast.error(isInsecure ? 'Kamera membutuhkan koneksi HTTPS.' : 'Gagal membuka kamera.');
      setImeiScanning(false);
    }
  };

  const stopImeiScan = () => imeiScannerRef.current?.stop().then(() => setImeiScanning(false)).catch(() => setImeiScanning(false));

  const onSubmit = async (data: FormData) => {
    if (!captchaVerified) {
      setErrorModal('Harap selesaikan verifikasi CAPTCHA terlebih dahulu.');
      return;
    }
    setLoading(true); setResult(null);
    try {
      const res = await api.post('/end-user/claims', { ...data, promotion_id: Number(data.promotion_id) });
      setResult(res.data.data);
      setCaptchaVerified(false);

      // Tampilkan scratch card untuk hadiah_langsung
      const isHadiahLangsung = selectedPromo?.reward_method === 'hadiah_langsung';
      if (isHadiahLangsung && res.data.data?.reward_data?.reward_name) {
        setShowScratch(true);
      } else {
        toast.success('Klaim berhasil diajukan!');
      }
    } catch (err: any) {
      if (err.response?.data?.code === 'BUDGET_EXHAUSTED') {
        setBudgetExhausted(true);
      } else {
        const msg = err.response?.data?.code === 'TOO_MANY_ATTEMPTS'
          ? '⏳ ' + (err.response?.data?.message ?? 'Terlalu banyak percobaan. Coba lagi dalam 5 menit.')
          : (err.response?.data?.message ?? 'Klaim gagal. Silakan coba lagi.');
        setErrorModal(msg);
      }
      setCaptchaVerified(false); // reset captcha setelah gagal
    } finally { setLoading(false); }
  };

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-6">Klaim Hadiah</h1>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 rounded-xl p-1 mb-6 max-w-xs">
        {(['form', 'history'] as const).map(t => (
          <button key={t} onClick={() => setActiveTab(t)}
            className={`flex-1 py-2 text-sm font-medium rounded-lg transition ${activeTab === t ? 'bg-white text-blue-700 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
            {t === 'form' ? 'Ajukan Klaim' : 'Riwayat'}
          </button>
        ))}
      </div>

      {/* Budget Exhausted Modal */}
      {budgetExhausted && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="bg-white rounded-2xl shadow-xl p-6 max-w-sm w-full text-center">
            <div className="text-5xl mb-3">😔</div>
            <h2 className="text-lg font-bold text-gray-800 mb-2">Reward Sudah Habis</h2>
            <p className="text-sm text-gray-600 mb-5">Mohon maaf reward sudah habis.</p>
            <button onClick={() => setBudgetExhausted(false)} className="bg-blue-700 text-white px-6 py-2 rounded-lg text-sm hover:bg-blue-800">Tutup</button>
          </div>
        </div>
      )}

      {/* Error Modal */}
      {errorModal && <ErrorModal message={errorModal} onClose={() => setErrorModal(null)} />}

      {/* Confetti */}
      {showConfetti && <Confetti />}

      {/* Scratch Card Modal */}
      {showScratch && result && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-sm p-6 text-center">
            <h2 className="text-xl font-bold text-gray-800 mb-1">🎉 Klaim Berhasil!</h2>
            <p className="text-sm text-gray-500 mb-5">Gosok kartu untuk reveal hadiahmu</p>

            <ScratchCard
              rewardName={result.reward_data?.reward_name ?? 'Hadiah Spesial'}
              rewardValue={result.reward_data?.reward_value}
              onFullyScratched={() => {
                setShowConfetti(true);
                setTimeout(() => setShowConfetti(false), 4000);
              }}
            />

            <button
              onClick={() => {
                setShowScratch(false);
                setResult(null);
                reset();
                clearOutlet();
                setSelectedPromo(null);
              }}
              className="mt-5 w-full bg-blue-700 text-white py-2.5 rounded-xl font-medium hover:bg-blue-800 transition text-sm"
            >
              Selesai
            </button>
          </div>
        </div>
      )}

      {/* Promotion Picker Modal */}
      {showPicker && (
        <PromotionPickerModal
          promotions={promotions}
          onSelect={handleSelectPromo}
          onClose={() => setShowPicker(false)}
        />
      )}

      {/* Form Tab */}
      {activeTab === 'form' && (
        result && !showScratch ? (
          // Success card untuk undian & point_reward (hadiah_langsung pakai scratch card)
          <div className="bg-green-50 border border-green-200 rounded-2xl p-6 text-center">
            <div className="text-4xl mb-3">🎉</div>
            <h2 className="text-lg font-bold text-green-700 mb-1">Klaim Berhasil!</h2>
            <p className="text-sm text-gray-600">ID Klaim: <strong>#{result.claim_id}</strong></p>
            <p className="text-sm text-gray-600">Status: <strong>{statusConfig[result.status]?.label ?? result.status}</strong></p>
            {result.lottery_number && <p className="text-sm text-gray-600 mt-1">Nomor Undian: <strong>{result.lottery_number}</strong></p>}
            {result.status === 'approved' && result.reward_data?.reward_name && (
              <div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-xl p-4">
                <p className="text-xs text-yellow-600 font-medium uppercase tracking-wide mb-1">Hadiah Anda</p>
                <p className="text-lg font-bold text-yellow-800">{result.reward_data.reward_name}</p>
                {result.reward_data.reward_value != null && result.reward_data.reward_value > 0 && (
                  <p className="text-sm text-yellow-700 mt-0.5">Senilai Rp {result.reward_data.reward_value.toLocaleString('id-ID')}</p>
                )}
              </div>
            )}
            <div className="flex gap-3 justify-center mt-4">
              <button onClick={() => { setResult(null); reset(); clearOutlet(); setSelectedPromo(null); }}
                className="bg-blue-700 text-white px-5 py-2 rounded-lg text-sm hover:bg-blue-800">Klaim Lagi</button>
              <button onClick={() => { setResult(null); setActiveTab('history'); }}
                className="bg-gray-100 text-gray-700 px-5 py-2 rounded-lg text-sm hover:bg-gray-200">Lihat Riwayat</button>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit(onSubmit)} className="bg-white rounded-2xl shadow-sm p-6 space-y-5 max-w-lg">

            {/* Promotion Picker */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Pilih Promosi <span className="text-red-500">*</span></label>
              <input type="hidden" {...register('promotion_id')} />

              {presetPromotionId && selectedPromo ? (
                <div className="border border-blue-200 rounded-xl overflow-hidden">
                  {selectedPromo.banner_image && (
                    <img src={selectedPromo.banner_image} alt={selectedPromo.name} className="w-full h-28 object-cover" />
                  )}
                  <div className="p-3 flex items-start justify-between gap-2">
                    <div>
                      <p className="font-semibold text-gray-800 text-sm">{selectedPromo.name}</p>
                      {selectedPromo.description && <p className="text-xs text-gray-500 mt-0.5 line-clamp-1">{selectedPromo.description}</p>}
                      <span className={`inline-block mt-1 text-xs px-2 py-0.5 rounded-full font-medium ${methodColor[selectedPromo.reward_method] ?? 'bg-gray-100 text-gray-600'}`}>
                        {methodLabel[selectedPromo.reward_method] ?? selectedPromo.reward_method}
                      </span>
                    </div>
                    <button type="button" onClick={() => { setSelectedPromo(null); setValue('promotion_id', ''); setShowPicker(true); }}
                      className="text-xs text-gray-400 hover:text-red-500 flex-shrink-0 mt-0.5">✕ Ganti</button>
                  </div>
                </div>
              ) : selectedPromo ? (
                /* Selected promo card */
                <div className="border border-blue-200 rounded-xl overflow-hidden">
                  {selectedPromo.banner_image && (
                    <img src={selectedPromo.banner_image} alt={selectedPromo.name} className="w-full h-28 object-cover" />
                  )}
                  <div className="p-3 flex items-start justify-between gap-2">
                    <div>
                      <p className="font-semibold text-gray-800 text-sm">{selectedPromo.name}</p>
                      {selectedPromo.description && <p className="text-xs text-gray-500 mt-0.5 line-clamp-1">{selectedPromo.description}</p>}
                      <span className={`inline-block mt-1 text-xs px-2 py-0.5 rounded-full font-medium ${methodColor[selectedPromo.reward_method] ?? 'bg-gray-100 text-gray-600'}`}>
                        {methodLabel[selectedPromo.reward_method] ?? selectedPromo.reward_method}
                      </span>
                    </div>
                    <button type="button" onClick={() => { setSelectedPromo(null); setValue('promotion_id', ''); }}
                      className="text-xs text-gray-400 hover:text-red-500 flex-shrink-0 mt-0.5">✕ Ganti</button>
                  </div>
                </div>
              ) : (
                <button type="button" onClick={() => setShowPicker(true)}
                  className="w-full border-2 border-dashed border-gray-300 rounded-xl py-6 text-center hover:border-blue-400 hover:bg-blue-50 transition group">
                  <div className="text-3xl mb-1 group-hover:scale-110 transition-transform">🎁</div>
                  <p className="text-sm text-gray-500 group-hover:text-blue-600">Ketuk untuk memilih promosi</p>
                </button>
              )}
              {errors.promotion_id && <p className="text-red-500 text-xs mt-1">{errors.promotion_id.message}</p>}
            </div>

            {/* IMEI */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">IMEI Perangkat <span className="text-red-500">*</span></label>
              <div className="flex gap-2">
                <input {...register('imei')} placeholder="Ketik atau scan barcode IMEI" maxLength={20}
                  autoComplete="off"
                  className="flex-1 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                <button type="button" onClick={imeiScanning ? stopImeiScan : startImeiScan}
                  className={`px-3 py-2 text-sm rounded-lg text-white transition ${imeiScanning ? 'bg-red-500 hover:bg-red-600' : 'bg-gray-600 hover:bg-gray-700'}`}>
                  {imeiScanning ? 'Stop' : '📷 Scan'}
                </button>
              </div>
              <div id={imeiScanDivId} className={`mt-3 rounded-lg overflow-hidden ${imeiScanning ? '' : 'hidden'}`} />
              {errors.imei && <p className="text-red-500 text-xs mt-1">{errors.imei.message}</p>}
            </div>

            {/* Outlet */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Outlet <span className="text-red-500">*</span></label>
              {detectedOutlet ? (
                <div className="flex items-center gap-2 bg-sky-50 border border-sky-200 rounded-lg px-3 py-2">
                  <span className="text-sky-700 text-sm flex-1">🏪 <strong>{outletLoading ? 'Memuat...' : (outletLabel ?? detectedOutlet)}</strong></span>
                  {!outletFromUrl && (
                    <button type="button" onClick={clearOutlet} className="text-xs text-gray-400 hover:text-red-500">✕ Hapus</button>
                  )}
                </div>
              ) : (
                <div className="flex gap-2">
                  <input {...register('outlet_code')} placeholder="Scan atau ketik kode outlet"
                    autoComplete="off"
                    className="flex-1 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                  <button type="button" onClick={scanning ? stopScan : startScan}
                    className={`px-3 py-2 text-sm rounded-lg text-white transition ${scanning ? 'bg-red-500 hover:bg-red-600' : 'bg-gray-600 hover:bg-gray-700'}`}>
                    {scanning ? 'Stop' : '📷 Scan'}
                  </button>
                </div>
              )}
              <div id={scanDivId} className={`mt-3 rounded-lg overflow-hidden ${scanning ? '' : 'hidden'}`} />
              {errors.outlet_code && <p className="text-red-500 text-xs mt-1">{errors.outlet_code.message}</p>}
            </div>

            {/* CAPTCHA */}
            {!captchaVerified ? (
              <MathCaptcha onVerified={setCaptchaVerified} />
            ) : (
              <div className="flex items-center gap-2 text-green-600 text-sm bg-green-50 border border-green-200 rounded-xl px-4 py-2.5">
                <svg className="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                </svg>
                Verifikasi berhasil
              </div>
            )}

            <button type="submit" disabled={loading || !captchaVerified}
              className="w-full bg-blue-700 text-white py-2.5 rounded-lg font-medium hover:bg-blue-800 disabled:opacity-60">
              {loading ? 'Memproses...' : 'Ajukan Klaim'}
            </button>
          </form>
        )
      )}

      {/* History Tab */}
      {activeTab === 'history' && (
        <div>
          {historyLoading ? (
            <div className="text-center py-12 text-gray-400 text-sm">Memuat riwayat...</div>
          ) : history.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3">📋</div>
              <p className="text-gray-500 text-sm">Belum ada riwayat klaim.</p>
              <button onClick={() => setActiveTab('form')} className="mt-4 bg-blue-700 text-white px-5 py-2 rounded-lg text-sm hover:bg-blue-800">Ajukan Klaim Pertama</button>
            </div>
          ) : (
            <div className="space-y-3">
              {history.map((c) => {
                const st = statusConfig[c.status] ?? { label: c.status, className: 'bg-gray-100 text-gray-500' };
                return (
                  <div key={c.id} className="bg-white rounded-xl shadow-sm p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <p className="font-semibold text-gray-800 text-sm truncate">{c.promotion?.name ?? '-'}</p>
                        <p className="text-xs text-gray-500 mt-0.5">{c.device_model ? `${c.device_model.brand} ${c.device_model.model_name}` : '-'}</p>
                        <p className="text-xs text-gray-400 mt-0.5 font-mono">IMEI: {c.imei}</p>
                      </div>
                      <span className={`flex-shrink-0 text-xs px-2.5 py-1 rounded-full font-medium ${st.className}`}>{st.label}</span>
                    </div>
                    <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-50">
                      <span className="text-xs text-gray-400">{formatTimestamp(c.claimed_at)}</span>
                      <div className="flex items-center gap-3 text-xs text-gray-500">
                        {c.lottery_number && <span>🎟 {c.lottery_number}</span>}
                        {c.points_awarded > 0 && <span>⭐ {c.points_awarded} poin</span>}
                        <span className="text-gray-300">#{c.id}</span>
                      </div>
                    </div>
                  </div>
                );
              })}
              {historyLastPage > 1 && (
                <div className="flex justify-center gap-2 pt-2">
                  <button disabled={historyPage <= 1} onClick={() => fetchHistory(historyPage - 1)} className="px-3 py-1.5 text-sm rounded-lg border disabled:opacity-40 hover:bg-gray-50">← Sebelumnya</button>
                  <span className="px-3 py-1.5 text-sm text-gray-500">{historyPage} / {historyLastPage}</span>
                  <button disabled={historyPage >= historyLastPage} onClick={() => fetchHistory(historyPage + 1)} className="px-3 py-1.5 text-sm rounded-lg border disabled:opacity-40 hover:bg-gray-50">Berikutnya →</button>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
