const { useState, useEffect, useRef, createContext, useContext, useCallback } = React;

// --- ÍCONES SVG ---
const Icons = {
  Dice: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2" /><path d="M12 12h.01" /><path d="M8 8h.01" /><path d="M16 16h.01" /><path d="M16 8h.01" /><path d="M8 16h.01" /></svg>,
  Users: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></svg>,
  Copy: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" /></svg>,
  Check: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>,
  Zap: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>,
  Target: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" /></svg>,
  Refresh: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" /><path d="M3 3v5h5" /></svg>,
  Volume2: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" /><path d="M15.54 8.46a5 5 0 0 1 0 7.07" /><path d="M19.07 4.93a10 10 0 0 1 0 14.14" /></svg>,
  VolumeX: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" /><line x1="23" y1="9" x2="17" y2="15" /><line x1="17" y1="9" x2="23" y2="15" /></svg>,
  AlertCircle: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>,
  Plus: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>,
  X: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>,
  Instagram: ({ className }) => <svg className={className} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="20" x="2" y="2" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg>,
  Tiktok: ({ className }) => <svg className={className} viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 2.23-1.13 4.45-2.88 5.84-2.14 1.71-5.18 2.21-7.79 1.34-2.9-1-5.06-3.8-5.32-6.84-.25-2.85 1.18-5.74 3.55-7.3 1.83-1.2 4.2-1.52 6.32-1.01V12.9c-1.35-.49-3.03-.42-4.2.45-1.16.85-1.74 2.37-1.5 3.8.22 1.25 1.18 2.44 2.38 2.89 1.48.56 3.26.31 4.54-.64 1.25-.94 1.93-2.52 1.89-4.11V0l-1.05.02z"/></svg>
};

// --- INTERNACIONALIZAÇÃO (i18n) ---
const translations = {
  pt: {
    appTitle: "LIVESHOP",
    appTitleSpan: "TURBO",
    tabNumbers: "Números",
    tabNames: "Nomes",
    drawBtn: "Sortear Agora",
    drawAgain: "Novo Sorteio",
    copy: "Copiar Resultado",
    copied: "Copiado!",
    min: "Mínimo",
    max: "Máximo",
    qty: "Quantidade a sortear",
    noRepeat: "Sem repetição de resultados",
    namesPlaceholder: "Digite um nome e pressione Enter",
    addName: "Adicionar",
    clearAll: "Limpar",
    namesCount: "participantes adicionados",
    namesQty: "Quantidade de ganhadores",
    errorMaxMin: "O máximo não pode ser menor que o mínimo.",
    errorInterval: "A quantidade ultrapassa o intervalo disponível.",
    errorEmpty: "A lista de nomes está vazia.",
    errorNamesQty: "A quantidade pedida ultrapassa o total de nomes na lista.",
    errorMax100: "Por segurança, o limite máximo é de 100 resultados por vez.",
    drawTime: "Sorteio realizado em",
    loading: "Sorteando...",
    lastWinners: "Últimos Ganhadores",
    clearHistory: "Limpar Histórico",
    importBtn: "Importar (Excel, Word, TXT)",
    remaining: " (Restam ",
    available: " disponíveis)",
    drawWord: "Sorteio "
  },
  es: {
    appTitle: "LIVESHOP",
    appTitleSpan: "TURBO",
    tabNumbers: "Números",
    tabNames: "Nombres",
    drawBtn: "Sortear Ahora",
    drawAgain: "Nuevo Sorteo",
    copy: "Copiar Resultado",
    copied: "¡Copiado!",
    min: "Mínimo",
    max: "Máximo",
    qty: "Cantidad a sortear",
    noRepeat: "Sin repetición",
    namesPlaceholder: "Escribe un nombre y presiona Enter",
    addName: "Añadir",
    clearAll: "Borrar",
    namesCount: "participantes añadidos",
    namesQty: "Cantidad de ganadores",
    errorMaxMin: "El máximo no puede ser menor que el mínimo.",
    errorInterval: "La cantidad supera el intervalo disponible.",
    errorEmpty: "La lista de nombres está vacía.",
    errorNamesQty: "La cantidad solicitada supera el total de nombres.",
    errorMax100: "Por seguridad, el límite máximo es de 100 resultados a la vez.",
    drawTime: "Sorteo realizado el",
    loading: "Sorteando...",
    lastWinners: "Últimos Ganadores",
    clearHistory: "Borrar Historial",
    importBtn: "Importar (Excel, Word, TXT)",
    remaining: " (Quedan ",
    available: " disponibles)",
    drawWord: "Sorteo "
  }
};

const I18nContext = createContext();

// --- HOOK DE ÁUDIO ---
const useAudioEffects = (enabled) => {
  const audioCtx = useRef(null);

  const initAudio = useCallback(() => {
    if (!audioCtx.current) {
      audioCtx.current = new (window.AudioContext || window.webkitAudioContext)();
    }
    if (audioCtx.current.state === 'suspended') {
      audioCtx.current.resume();
    }
  }, []);

  const playTick = useCallback(() => {
    if (!enabled || !audioCtx.current) return;
    const ctx = audioCtx.current;
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.connect(gain);
    gain.connect(ctx.destination);
    osc.type = 'triangle';
    osc.frequency.setValueAtTime(600, ctx.currentTime);
    osc.frequency.exponentialRampToValueAtTime(1200, ctx.currentTime + 0.03);
    gain.gain.setValueAtTime(0.05, ctx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.03);
    osc.start(ctx.currentTime);
    osc.stop(ctx.currentTime + 0.03);
  }, [enabled]);

  const playSuccess = useCallback(() => {
    if (!enabled || !audioCtx.current) return;
    const ctx = audioCtx.current;
    // Acorde Maj7 sintetizado: A4, C#5, E5, G#5
    const frequencies = [440, 554.37, 659.25, 830.61];
    frequencies.forEach((freq, index) => {
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.connect(gain);
      gain.connect(ctx.destination);
      osc.type = 'sine';
      osc.frequency.setValueAtTime(freq, ctx.currentTime);
      gain.gain.setValueAtTime(0, ctx.currentTime);
      gain.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.05 + (index * 0.02));
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 1.5 + (index * 0.2));
      osc.start(ctx.currentTime);
      osc.stop(ctx.currentTime + 2);
    });
  }, [enabled]);

  return { initAudio, playTick, playSuccess };
};

// --- COMPONENTES ---

const Header = ({ soundEnabled, setSoundEnabled }) => {
  const { lang, setLang, t } = useContext(I18nContext);

  return (
    <header className="flex items-center justify-between py-6 px-4 md:px-8 border-b border-dark-800 bg-dark-900/50 backdrop-blur-lg sticky top-0 z-50">
      <div className="flex items-center gap-3">
        <img src="assets/apple-touch-icon.png" alt="Logo" className="w-10 h-10 rounded-xl" />
        <h1 className="text-2xl md:text-3xl font-black tracking-tight">
          {t.appTitle} <span className="text-neon neon-text">{t.appTitleSpan}</span>
        </h1>
      </div>

      <div className="flex items-center gap-3 md:gap-4">
        <button
          onClick={() => setSoundEnabled(!soundEnabled)}
          className="p-2 rounded-full hover:bg-dark-800 transition-colors text-slate-400 hover:text-neon"
          title="Toggle Sound"
        >
          {soundEnabled ? <Icons.Volume2 className="w-5 h-5" /> : <Icons.VolumeX className="w-5 h-5" />}
        </button>
        <div className="flex bg-dark-800 rounded-lg p-1 border border-dark-700">
          <button
            onClick={() => setLang('pt')}
            className={`px-3 py-1 text-sm font-semibold rounded-md transition-all ${lang === 'pt' ? 'bg-neon text-dark-900 shadow-sm' : 'text-slate-400 hover:text-white'}`}
          >
            PT
          </button>
          <button
            onClick={() => setLang('es')}
            className={`px-3 py-1 text-sm font-semibold rounded-md transition-all ${lang === 'es' ? 'bg-neon text-dark-900 shadow-sm' : 'text-slate-400 hover:text-white'}`}
          >
            ES
          </button>
        </div>
      </div>
    </header>
  );
};

const TabsContainer = ({ active, onChange }) => {
  const { t } = useContext(I18nContext);

  return (
    <div className="flex gap-2 p-1 bg-dark-800/80 backdrop-blur-sm rounded-2xl border border-dark-700 mx-auto max-w-md w-full my-8">
      <button
        onClick={() => onChange('numbers')}
        className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl font-bold transition-all ${active === 'numbers' ? 'bg-dark-700 text-neon shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}
      >
        <Icons.Dice className="w-5 h-5" />
        {t.tabNumbers}
      </button>
      <button
        onClick={() => onChange('names')}
        className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl font-bold transition-all ${active === 'names' ? 'bg-dark-700 text-neon shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}
      >
        <Icons.Users className="w-5 h-5" />
        {t.tabNames}
      </button>
    </div>
  );
};

const FormNumbers = ({ pickedNumbers, onProcessDraw }) => {
  const { t } = useContext(I18nContext);
  const [min, setMin] = useState(1);
  const [max, setMax] = useState(100);
  const [qty, setQty] = useState(1);
  const [noRepeat, setNoRepeat] = useState(true);
  const [error, setError] = useState(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    setError(null);

    const minVal = parseInt(min), maxVal = parseInt(max), qtyVal = parseInt(qty);
    if (isNaN(minVal) || isNaN(maxVal) || isNaN(qtyVal)) return;

    if (maxVal < minVal) {
      setError(t.errorMaxMin);
      return;
    }

    if (noRepeat) {
      const remainingCount = (maxVal - minVal + 1) - pickedNumbers.filter(n => n >= minVal && n <= maxVal).length;
      if (qtyVal > remainingCount) {
        setError(t.errorInterval + t.remaining + remainingCount + t.available);
        return;
      }
    }

    if (qtyVal > 100) {
      setError(t.errorMax100);
      return;
    }

    onProcessDraw({ type: 'numbers', params: { min: minVal, max: maxVal, qty: qtyVal, noRepeat } });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="space-y-2">
          <label className="text-sm font-semibold text-slate-300 ml-1">{t.min}</label>
          <input type="number" min="0" value={min} onChange={e => setMin(e.target.value)} required
            className="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white text-lg font-medium focus:outline-none focus:border-neon focus:ring-1 focus:ring-neon transition-colors" />
        </div>
        <div className="space-y-2">
          <label className="text-sm font-semibold text-slate-300 ml-1">{t.max}</label>
          <input type="number" min="0" value={max} onChange={e => setMax(e.target.value)} required
            className="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white text-lg font-medium focus:outline-none focus:border-neon focus:ring-1 focus:ring-neon transition-colors" />
        </div>
      </div>

      <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-300 ml-1">{t.qty}</label>
        <input type="number" min="1" value={qty} onChange={e => setQty(e.target.value)} required
          className="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white text-lg font-medium focus:outline-none focus:border-neon focus:ring-1 focus:ring-neon transition-colors" />
      </div>

      <label className="flex items-center gap-3 cursor-pointer p-4 rounded-xl border border-dark-700 bg-dark-800/50 hover:bg-dark-800 transition-colors">
        <div className="relative flex items-center">
          <input type="checkbox" checked={noRepeat} onChange={e => setNoRepeat(e.target.checked)} className="sr-only peer" />
          <div className="w-6 h-6 border-2 border-slate-500 rounded-md peer-checked:bg-neon peer-checked:border-neon transition-colors"></div>
          <Icons.Check className={`absolute top-0.5 left-0.5 w-5 h-5 text-dark-900 opacity-0 peer-checked:opacity-100 transition-opacity`} />
        </div>
        <span className="font-semibold text-slate-200">{t.noRepeat}</span>
      </label>

      {error && (
        <div className="flex items-center gap-2 text-red-400 bg-red-400/10 p-3 rounded-lg border border-red-400/20">
          <Icons.AlertCircle className="w-5 h-5" />
          <p className="font-medium text-sm">{error}</p>
        </div>
      )}

      <button type="submit"
        className="w-full bg-neon text-dark-900 font-black text-xl py-4 rounded-2xl glow-effect flex items-center justify-center gap-2 pt-5 pb-5">
        <Icons.Target className="w-6 h-6" />
        {t.drawBtn}
      </button>
    </form>
  );
};

const FormNames = ({ namesList, setNamesList, onProcessDraw }) => {
  const { t } = useContext(I18nContext);
  const [currentName, setCurrentName] = useState("");
  const [qty, setQty] = useState(1);
  const [error, setError] = useState(null);

  const handleAddName = (e) => {
    e.preventDefault();
    const trimmed = currentName.trim();
    if (!trimmed) return;
    setNamesList(prev => [...prev, trimmed]);
    setCurrentName("");
    setError(null);
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddName(e);
    }
  };

  const handleRemoveName = (indexToRemove) => {
    setNamesList(prev => prev.filter((_, idx) => idx !== indexToRemove));
  };

  const handleClearAll = () => setNamesList([]);

  const addNamesToState = (lines) => {
    if (lines.length === 0) return;
    setNamesList(prev => {
      const ignoreWords = ['nome', 'name', 'nombre', 'nomes', 'names', 'nombres'];
      const validLines = lines.filter(item => !ignoreWords.includes(item.toLowerCase().trim()));
      return Array.from(new Set([...prev, ...validLines]));
    });
  };

  const handleFileUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const fileName = file.name.toLowerCase();

    // XLSX / XLS
    if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
          const lines = jsonData.flat().filter(item => item != null).map(c => String(c).trim()).filter(c => c.length > 0);
          addNamesToState(lines);
        } catch (err) {
          setError("Erro ao ler arquivo Excel.");
          console.error(err);
        }
        e.target.value = null;
      };
      reader.readAsArrayBuffer(file);
    }
    // DOCX
    else if (fileName.endsWith('.docx')) {
      const reader = new FileReader();
      reader.onload = (event) => {
        mammoth.extractRawText({ arrayBuffer: event.target.result })
          .then((result) => {
            const lines = result.value.split(/\r?\n/).map(line => line.trim()).filter(line => line.length > 0);
            addNamesToState(lines);
            e.target.value = null;
          })
          .catch((err) => {
            setError("Erro ao ler DOCX. Salve como .docx moderno (não .doc).");
            console.error(err);
            e.target.value = null;
          });
      };
      reader.readAsArrayBuffer(file);
    }
    // TXT / CSV
    else {
      const reader = new FileReader();
      reader.onload = (event) => {
        const lines = event.target.result.split(/\r?\n/).map(line => line.trim()).filter(line => line.length > 0);
        addNamesToState(lines);
        e.target.value = null;
      };
      reader.readAsText(file);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setError(null);

    if (namesList.length === 0) {
      setError(t.errorEmpty);
      return;
    }

    const qtyVal = parseInt(qty);
    if (isNaN(qtyVal) || qtyVal < 1) return;

    if (qtyVal > namesList.length) {
      setError(t.errorNamesQty);
      return;
    }

    if (qtyVal > 100) {
      setError(t.errorMax100);
      return;
    }

    onProcessDraw({ type: 'names', params: { names: namesList, qty: qtyVal } });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-3">
        <div className="flex flex-col gap-3">
          <div className="flex gap-2">
            <input
              type="text"
              placeholder={t.namesPlaceholder}
              value={currentName}
              onChange={e => setCurrentName(e.target.value)}
              onKeyDown={handleKeyDown}
              className="flex-1 bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white font-medium focus:outline-none focus:border-neon focus:ring-1 focus:ring-neon transition-colors"
            />
            <button
              type="button"
              onClick={handleAddName}
              className="bg-dark-700 hover:bg-dark-600 border border-dark-600 text-neon font-bold rounded-xl px-4 md:px-6 transition-colors flex items-center gap-2"
            >
              <Icons.Plus className="w-5 h-5" />
              <span className="hidden md:inline">{t.addName}</span>
            </button>
          </div>
          <div className="flex items-center">
            <label className="flex items-center gap-2 px-4 py-2 bg-dark-800 hover:bg-dark-700 border border-dark-600 rounded-xl cursor-pointer text-slate-300 text-sm font-semibold transition-colors w-full justify-center md:w-auto">
              <svg className="w-4 h-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
              </svg>
              {t.importBtn}
              <input type="file" accept=".txt,.csv,.xlsx,.xls,.docx" className="hidden" onChange={handleFileUpload} />
            </label>
          </div>
        </div>

        <div className="bg-dark-900 border border-dark-700 rounded-xl p-4 min-h-[120px] max-h-[250px] overflow-y-auto">
          {namesList.length === 0 ? (
            <div className="h-full flex items-center justify-center text-slate-500 font-medium py-6">
              {t.errorEmpty}
            </div>
          ) : (
            <div className="flex flex-wrap gap-2">
              {namesList.map((name, idx) => (
                <div key={idx} className="bg-dark-800 border border-dark-700 flex items-center gap-2 px-3 py-1.5 rounded-lg group animate-[popIn_0.2s_ease-out]">
                  <span className="text-slate-200 font-medium text-sm">{name}</span>
                  <button
                    type="button"
                    onClick={() => handleRemoveName(idx)}
                    className="text-slate-500 hover:text-red-400 opacity-50 group-hover:opacity-100 transition-all"
                  >
                    <Icons.X className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-400 font-medium">{namesList.length} {t.namesCount}</p>
          {namesList.length > 0 && (
            <button
              type="button"
              onClick={handleClearAll}
              className="text-xs font-semibold text-slate-500 hover:text-red-400 transition-colors"
            >
              {t.clearAll}
            </button>
          )}
        </div>
      </div>

      <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-300 ml-1">{t.namesQty}</label>
        <input type="number" min="1" max={namesList.length || 1} value={qty} onChange={e => setQty(e.target.value)} required
          className="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white text-lg font-medium focus:outline-none focus:border-neon focus:ring-1 focus:ring-neon transition-colors" />
      </div>

      {error && (
        <div className="flex items-center gap-2 text-red-400 bg-red-400/10 p-3 rounded-lg border border-red-400/20">
          <Icons.AlertCircle className="w-5 h-5" />
          <p className="font-medium text-sm">{error}</p>
        </div>
      )}

      <button type="submit"
        className="w-full bg-neon text-dark-900 font-black text-xl py-4 rounded-2xl glow-effect flex items-center justify-center gap-2 pt-5 pb-5">
        <Icons.Target className="w-6 h-6" />
        {t.drawBtn}
      </button>
    </form>
  );
};

const ResultDisplay = ({ drawData, onReset, playTick, playSuccess }) => {
  const { t, lang } = useContext(I18nContext);
  const [isAnimating, setIsAnimating] = useState(true);
  const [displayItems, setDisplayItems] = useState([]);
  const [copied, setCopied] = useState(false);

  const { results, type, source } = drawData;

  useEffect(() => {
    const startTime = Date.now();
    const duration = 2500;
    let lastTick = 0;

    const updateFrame = () => {
      const now = Date.now();
      const elapsed = now - startTime;

      if (elapsed < duration) {
        // Throttle updates to ~16fps to reduce CPU and Audio API overhead
        if (now - lastTick > 60) {
          const randomPicks = [];
          for (let i = 0; i < results.length; i++) {
            if (type === 'numbers') {
              randomPicks.push(Math.floor(Math.random() * (source.max - source.min + 1)) + source.min);
            } else {
              randomPicks.push(source.names[Math.floor(Math.random() * source.names.length)]);
            }
          }
          setDisplayItems(randomPicks);
          playTick();
          lastTick = now;
        }
        requestAnimationFrame(updateFrame);
      } else {
        setDisplayItems(results);
        setIsAnimating(false);
        playSuccess();
      }
    };

    requestAnimationFrame(updateFrame);
  }, []);

  const handleCopy = () => {
    navigator.clipboard.writeText(results.join(', '));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="flex flex-col items-center animate-[popIn_0.3s_ease-out]">
      <h2 className="text-xl md:text-2xl font-bold text-slate-300 mb-8 border-b border-dark-700 pb-4">
        {isAnimating ? t.loading : 'Vencedor(es)! 🎉'}
      </h2>

      <div className={`w-full p-8 md:p-12 bg-dark-900 rounded-3xl border border-dark-700/50 shadow-2xl relative overflow-hidden transition-all duration-300 ${!isAnimating && 'border-neon/50 shadow-[0_0_40px_rgba(0,255,127,0.15)]'}`}>
        {!isAnimating && (
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full h-full bg-neon/10 blur-[100px] pointer-events-none rounded-full"></div>
        )}

        <div className="relative z-10 flex flex-wrap justify-center gap-6 md:gap-8">
          {displayItems.map((item, idx) => (
            <div key={idx} className="flex items-center justify-center">
              <span className={`text-5xl md:text-7xl font-black text-center break-words max-w-full ${isAnimating ? 'text-slate-400 blur-[1px]' : 'text-neon neon-text result-enter'}`}>
                {item}
              </span>
            </div>
          ))}
        </div>
      </div>

      {!isAnimating && (
        <div className="mt-8 flex flex-col items-center w-full gap-6">
          <div className="flex gap-4 w-full md:w-auto">
            <button
              onClick={handleCopy}
              className="flex-1 md:flex-none flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-dark-800 border border-dark-700 text-white font-semibold hover:bg-dark-700 transition"
            >
              {copied ? <Icons.Check className="w-5 h-5 text-neon" /> : <Icons.Copy className="w-5 h-5" />}
              {copied ? t.copied : t.copy}
            </button>

            <button
              onClick={onReset}
              className="flex-1 md:flex-none flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-neon text-dark-900 font-bold glow-effect"
            >
              <Icons.Refresh className="w-5 h-5" />
              {t.drawAgain}
            </button>
          </div>

          <div className="text-sm font-medium text-slate-500 bg-dark-900/50 px-4 py-2 rounded-full border border-dark-800">
            {t.drawTime} {new Date().toLocaleString(lang === 'pt' ? 'pt-BR' : 'es-ES')}
          </div>
        </div>
      )}
    </div>
  );
};

// --- APP ---
const App = () => {
  const [lang, setLang] = useState(null);
  const [activeTab, setActiveTab] = useState('numbers');
  const [drawData, setDrawData] = useState(null);
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [history, setHistory] = useState([]);
  const [namesList, setNamesList] = useState([]);
  const [pickedNumbers, setPickedNumbers] = useState([]);

  const { initAudio, playTick, playSuccess } = useAudioEffects(soundEnabled);

  if (!lang) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-dark-900 px-4 relative z-0">
        <div className="absolute inset-0 bg-dark-900 z-[-1] overflow-hidden">
          <div className="absolute top-[20%] left-[20%] w-[40%] h-[40%] bg-neon/10 rounded-full blur-[100px]"></div>
          <div className="absolute bottom-[20%] right-[20%] w-[40%] h-[40%] bg-emerald-500/10 rounded-full blur-[100px]"></div>
        </div>

        <div className="bg-dark-800/80 backdrop-blur-xl border border-dark-700 rounded-3xl p-8 max-w-sm w-full shadow-2xl animate-[popIn_0.4s_ease-out] flex flex-col items-center">
          <div className="w-16 h-16 bg-gradient-to-br from-neon to-emerald-500 rounded-2xl flex items-center justify-center shadow-[0_0_20px_rgba(46,213,115,0.3)] mb-6">
            <svg className="w-8 h-8 text-dark-900" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
          </div>
          <h2 className="text-2xl font-bold text-center text-slate-200 mb-2">LiveShop Turbo</h2>
          <p className="text-sm text-center text-slate-400 mb-8">
            Escolha seu Idioma<br/>
            <span className="text-xs opacity-70">Elige tu Idioma</span>
          </p>

          <div className="flex flex-col gap-4 w-full">
            <button
              onClick={() => { setLang('pt'); initAudio(); }}
              className="w-full py-4 bg-dark-700 hover:bg-dark-600 border border-dark-600 hover:border-emerald-500/50 rounded-xl font-bold text-white transition-all hover:-translate-y-1 flex items-center justify-center gap-3 shadow-lg"
            >
              <span className="text-2xl">🇧🇷</span> Português
            </button>
            <button
              onClick={() => { setLang('es'); initAudio(); }}
              className="w-full py-4 bg-dark-700 hover:bg-dark-600 border border-dark-600 hover:border-yellow-500/50 rounded-xl font-bold text-white transition-all hover:-translate-y-1 flex items-center justify-center gap-3 shadow-lg"
            >
              <span className="text-2xl">🇪🇸</span> Español
            </button>
          </div>
        </div>
      </div>
    );
  }

  const t = translations[lang];

  const handleProcessDraw = ({ type, params }) => {
    initAudio();

    let results = [];
    let sourceObj = {};

    if (type === 'numbers') {
      const { min, max, qty, noRepeat } = params;
      sourceObj = { min, max };

      if (noRepeat) {
        // Array.from crashes the browser (OOM) for ranges > 100k — use Set-based sampling instead
        if (max - min > 100000) {
          const currentPicked = new Set(pickedNumbers);
          let safety = 0;
          while (results.length < qty && safety < 100000) {
            const r = Math.floor(Math.random() * (max - min + 1)) + min;
            if (!currentPicked.has(r)) {
              currentPicked.add(r);
              results.push(r);
            }
            safety++;
          }
          setPickedNumbers(Array.from(currentPicked));
        } else {
          let available = Array.from({ length: max - min + 1 }, (_, i) => min + i).filter(n => !pickedNumbers.includes(n));
          const actualQty = Math.min(qty, available.length);
          for (let i = 0; i < actualQty; i++) {
            const idx = Math.floor(Math.random() * available.length);
            results.push(available[idx]);
            available.splice(idx, 1);
          }
          setPickedNumbers(prev => [...prev, ...results]);
        }
      } else {
        for (let i = 0; i < qty; i++) {
          results.push(Math.floor(Math.random() * (max - min + 1)) + min);
        }
      }
    } else if (type === 'names') {
      const { names, qty } = params;
      sourceObj = { names };
      let available = [...names];
      for (let i = 0; i < qty; i++) {
        const idx = Math.floor(Math.random() * available.length);
        results.push(available[idx]);
        available.splice(idx, 1);
      }
      setNamesList(available);
    }

    setDrawData({ type, results, source: sourceObj });
  };

  const handleReset = () => {
    setHistory(prev => [
      { id: Date.now(), date: new Date(), items: drawData.results, type: drawData.type },
      ...prev
    ]);
    setDrawData(null);
  };

  return (
    <I18nContext.Provider value={{ lang, setLang, t }}>
      <div className="min-h-screen flex flex-col relative z-0">
        <div className="absolute top-[-20%] left-[-10%] w-[50%] h-[50%] bg-neon/10 rounded-full blur-[150px] pointer-events-none -z-10"></div>
        <div className="absolute bottom-[-20%] right-[-10%] w-[50%] h-[50%] bg-emerald-500/10 rounded-full blur-[150px] pointer-events-none -z-10"></div>

        <Header soundEnabled={soundEnabled} setSoundEnabled={setSoundEnabled} />

        <main className="flex-1 w-full max-w-3xl mx-auto px-4 py-8 md:py-12 flex flex-col justify-center">
          <div className={drawData ? 'hidden' : 'block'}>
            <div className="bg-dark-800/60 backdrop-blur-xl rounded-3xl border border-dark-700 shadow-2xl p-6 md:p-10 animate-[popIn_0.4s_ease-out]">
              <TabsContainer active={activeTab} onChange={setActiveTab} />

              <div className="mt-8 relative">
                <div className={activeTab === 'numbers' ? 'block' : 'hidden'}>
                  <FormNumbers pickedNumbers={pickedNumbers} onProcessDraw={handleProcessDraw} />
                </div>
                <div className={activeTab === 'names' ? 'block' : 'hidden'}>
                  <FormNames namesList={namesList} setNamesList={setNamesList} onProcessDraw={handleProcessDraw} />
                </div>
              </div>
            </div>

            {history.filter(h => h.type === activeTab).length > 0 && (
              <div className="mt-8 bg-dark-800/60 backdrop-blur-xl rounded-3xl border border-dark-700 shadow-2xl p-6 md:p-8 animate-[popIn_0.4s_ease-out]">
                <div className="flex items-center justify-between mb-6 pb-4 border-b border-dark-700">
                  <h3 className="text-xl font-bold text-slate-300 flex items-center gap-2">
                    <Icons.Target className="w-5 h-5 text-neon" />
                    {t.lastWinners}
                  </h3>
                  <button
                    onClick={() => {
                      setHistory(prev => prev.filter(h => h.type !== activeTab));
                      if (activeTab === 'numbers') setPickedNumbers([]);
                    }}
                    className="text-xs font-semibold text-slate-500 hover:text-red-400 transition-colors"
                  >
                    {t.clearHistory}
                  </button>
                </div>

                <div className="space-y-3 max-h-[300px] overflow-y-auto pr-2">
                  {history.filter(h => h.type === activeTab).map((record, index, arr) => (
                    <div key={record.id} className="bg-dark-900 border border-dark-700 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 hover:border-dark-600 transition-colors">
                      <div className="flex flex-wrap gap-2 flex-1">
                        {record.items.map((item, i) => (
                          <span key={i} className="bg-dark-800 border border-dark-600 text-neon font-bold px-3 py-1.5 rounded-lg shadow-sm">
                            {item}
                          </span>
                        ))}
                      </div>
                      <div className="text-right flex flex-col items-start md:items-end w-full md:w-auto">
                        <span className="text-xs font-medium text-slate-500 bg-dark-800 px-2 py-1 rounded-md">
                          {record.date.toLocaleTimeString(lang === 'pt' ? 'pt-BR' : 'es-ES')}
                        </span>
                        <span className="text-[10px] text-slate-600 font-semibold mt-1 uppercase tracking-wider">
                          {t.drawWord}{arr.length - index}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {drawData && (
            <ResultDisplay
              drawData={drawData}
              onReset={handleReset}
              playTick={playTick}
              playSuccess={playSuccess}
            />
          )}
        </main>

        <footer className="text-center py-8 text-dark-700 font-semibold text-sm flex flex-col items-center gap-5">
          <div className="flex gap-4">
            <a href="https://www.instagram.com/liveshop.turbo?igsh=MW1qMTZtN2xoeXRncw==" target="_blank" rel="noopener noreferrer" className="p-3 bg-dark-800 rounded-full hover:bg-dark-700 hover:-translate-y-1 text-slate-400 hover:text-neon transition border border-dark-600 shadow-lg" title="Instagram: liveshop.turbo">
              <Icons.Instagram className="w-5 h-5" />
            </a>
            <a href="https://www.tiktok.com/@rafasantos.liveshop" target="_blank" rel="noopener noreferrer" className="p-3 bg-dark-800 rounded-full hover:bg-dark-700 hover:-translate-y-1 text-slate-400 hover:text-neon transition border border-dark-600 shadow-lg" title="TikTok: rafasantos.liveshop">
              <Icons.Tiktok className="w-5 h-5" />
            </a>
            <a href="https://www.instagram.com/rafasantos.liveshop?igsh=MXEycngzcWcxbW5keg==" target="_blank" rel="noopener noreferrer" className="p-3 bg-dark-800 rounded-full hover:bg-dark-700 hover:-translate-y-1 text-slate-400 hover:text-neon transition border border-dark-600 shadow-lg" title="Instagram: rafasantos.liveshop">
              <Icons.Instagram className="w-5 h-5" />
            </a>
          </div>
          <div>Powered by LiveShop Turbo &copy; {new Date().getFullYear()}</div>
        </footer>
      </div>
    </I18nContext.Provider>
  );
};

// --- RENDER ---
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
