const { useState, useEffect } = React;

function App() {
  const [userName, setUserName] = useState('');
  const [isLogged, setIsLogged] = useState(false);
  const [choices, setChoices] = useState(null);
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    const savedName = localStorage.getItem('colinha_nome');
    const savedChoices = localStorage.getItem('colinha_choices');
    if (savedName) {
      setUserName(savedName);
      setIsLogged(true);
    }
    if (savedChoices) {
      setChoices(JSON.parse(savedChoices));
    }
  }, []);

  const handleLogin = (name) => {
    localStorage.setItem('colinha_nome', name);
    setUserName(name);
    setIsLogged(true);
  };

  const handleSaveChoices = (newChoices) => {
    localStorage.setItem('colinha_choices', JSON.stringify(newChoices));
    setChoices(newChoices);
    setIsEditing(false);
    window.scrollTo(0, 0);
  };

  const handleClear = () => {
    if(confirm("Tem certeza que deseja sair e apagar seus dados deste celular?")) {
      localStorage.removeItem('colinha_nome');
      localStorage.removeItem('colinha_choices');
      setUserName('');
      setIsLogged(false);
      setChoices(null);
      setIsEditing(false);
    }
  };

  if (!isLogged) {
    return <Login onLogin={handleLogin} />;
  }

  if (!choices || isEditing) {
    return <Selecao onSave={handleSaveChoices} initialChoices={choices || {}} onCancel={choices ? () => {setIsEditing(false); window.scrollTo(0,0);} : null} />;
  }

  return <Colinha choices={choices} onEdit={() => {setIsEditing(true); window.scrollTo(0,0);}} onLogout={handleClear} userName={userName} />;
}

function Login({ onLogin }) {
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (name.trim()) onLogin(name.trim());
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 p-4">
      <div className="bg-white p-8 rounded-xl shadow-lg w-full max-w-md border-t-8 border-brverde">
        <h1 className="text-3xl font-bold text-center mb-2 text-brverde">Colinha Eleitoral</h1>
        <p className="text-center text-gray-600 mb-8">Crie e salve sua colinha no seu celular.</p>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label className="block text-xl font-medium text-gray-700 mb-2">Qual o seu nome?</label>
            <input 
              type="text" 
              className="w-full px-4 py-4 text-xl border-2 border-gray-300 rounded-lg focus:ring-brverde focus:border-brverde" 
              placeholder="Digite seu nome..."
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
            />
          </div>
          <button type="submit" className="w-full bg-brverde hover:bg-green-700 text-white text-2xl font-bold py-4 px-4 rounded-lg shadow-md transition-colors">
            Entrar
          </button>
        </form>
        <p className="text-sm text-gray-500 text-center mt-6">
          Seus dados ficam salvos apenas no seu celular.
        </p>
      </div>
    </div>
  );
}

function TabelaSelecao({ id, label, options, value, onChange, digits }) {
  const isOutroSelected = value && value.isOutro;

  return (
    <div id={id} className="mb-10 p-2 md:p-6 bg-gray-50 rounded-xl border-2 border-gray-200 overflow-hidden scroll-mt-24">
      <h2 className="text-2xl font-bold text-gray-800 mb-4 px-2">{label}</h2>
      
      <div className="overflow-x-auto">
        <table className="w-full text-left border-collapse bg-white">
          <thead>
            <tr className="bg-green-100 border-b-2 border-green-200">
              <th className="p-3 text-sm font-bold text-green-900 w-12 text-center">Sel.</th>
              <th className="p-3 text-sm font-bold text-green-900 min-w-[200px]">Candidato (Número)</th>
              <th className="p-3 text-sm font-bold text-green-900 min-w-[200px]">Motivo / Alinhamento</th>
              <th className="p-3 text-sm font-bold text-green-900 min-w-[150px]">Perfil / Atuação</th>
              <th className="p-3 text-sm font-bold text-green-900 min-w-[150px]">Região</th>
            </tr>
          </thead>
          <tbody>
            {options.map((o) => {
              const isSelected = value && !value.isOutro && value.numero === o.numero;
              return (
                <tr 
                  key={o.numero} 
                  onClick={() => onChange({ ...o, isOutro: false })}
                  className={`border-b border-gray-200 cursor-pointer hover:bg-green-50 transition-colors ${isSelected ? 'bg-green-100' : ''}`}
                >
                  <td className="p-3 text-center border-r border-gray-100">
                    <div className={`w-6 h-6 mx-auto rounded-full border-2 flex items-center justify-center ${isSelected ? 'border-brverde bg-brverde' : 'border-gray-400'}`}>
                      {isSelected && <div className="w-2.5 h-2.5 bg-white rounded-full"></div>}
                    </div>
                  </td>
                  <td className="p-3 border-r border-gray-100">
                    <div className="font-bold text-gray-800">{o.nome}</div>
                    <div className="text-xl font-black text-brverde">{o.numero}</div>
                  </td>
                  <td className="p-3 text-sm text-gray-700 border-r border-gray-100">{o.arg1}</td>
                  <td className="p-3 text-sm text-gray-700 border-r border-gray-100">{o.arg2}</td>
                  <td className="p-3 text-sm text-gray-700 font-semibold">{o.regiao}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div 
        onClick={() => {
          if (!isOutroSelected) onChange({ nome: '', numero: '', isOutro: true });
        }}
        className={`mt-4 p-4 border-2 rounded-lg cursor-pointer transition-colors ${isOutroSelected ? 'border-bramarelo bg-yellow-50' : 'border-gray-300 bg-white hover:bg-gray-100'}`}
      >
        <div className="flex items-center gap-3 mb-2">
          <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center ${isOutroSelected ? 'border-yellow-600 bg-yellow-500' : 'border-gray-400'}`}>
            {isOutroSelected && <div className="w-2.5 h-2.5 bg-white rounded-full"></div>}
          </div>
          <span className="font-bold text-lg text-gray-700">Outro candidato (Digitar manualmente)</span>
        </div>

        {isOutroSelected && (
          <div className="pl-9 mt-4 space-y-3">
            <input 
              type="text" 
              placeholder="Nome do candidato" 
              className="w-full p-3 border-2 border-yellow-300 rounded text-lg focus:border-yellow-500 outline-none"
              value={value?.nome || ''}
              onChange={(e) => onChange({ ...value, nome: e.target.value, isOutro: true })}
            />
            <input 
              type="number" 
              placeholder={`Número (${digits} dígitos)`} 
              className="w-full p-3 border-2 border-yellow-300 rounded text-xl font-bold focus:border-yellow-500 outline-none"
              value={value?.numero || ''}
              onChange={(e) => onChange({ ...value, numero: e.target.value, isOutro: true })}
            />
          </div>
        )}
      </div>
    </div>
  );
}

function Selecao({ onSave, initialChoices, onCancel }) {
  const [depFederal, setDepFederal] = useState(initialChoices.depFederal || null);
  const [depEstadual, setDepEstadual] = useState(initialChoices.depEstadual || null);
  const [senador1, setSenador1] = useState(initialChoices.senador1 || null);
  const [senador2, setSenador2] = useState(initialChoices.senador2 || null);
  
  const [missing, setMissing] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    
    const missingFields = [];
    if (!depFederal) missingFields.push({ id: 'sec-depFederal', nome: 'Deputado Federal' });
    if (!depEstadual) missingFields.push({ id: 'sec-depEstadual', nome: 'Deputado Estadual' });
    if (!senador1) missingFields.push({ id: 'sec-senador1', nome: 'Primeiro Senador' });
    if (!senador2) missingFields.push({ id: 'sec-senador2', nome: 'Segundo Senador' });

    if (missingFields.length > 0) {
      setMissing(missingFields);
      // Optional: scroll automatically to the first missing field or the error message
      document.getElementById('error-box')?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      return;
    }
    
    setMissing([]);
    onSave({ depFederal, depEstadual, senador1, senador2 });
  };

  const scrollTo = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <div className="max-w-5xl mx-auto p-4 md:p-6 pb-24">
      <div className="bg-white rounded-xl shadow-md p-4 md:p-8 border-t-8 border-brverde mb-6">
        <h1 className="text-3xl font-bold text-brverde mb-2">Tabela de Escolha</h1>
        <p className="text-gray-600 text-lg mb-8">
          Leia as informações nas colunas da tabela abaixo e marque a sua escolha para cada cargo.
        </p>
        
        <form onSubmit={handleSubmit}>
          
          <TabelaSelecao 
            id="sec-depFederal"
            label="1º - Deputado Federal (4 números)" 
            options={candidatosData.deputadosFederais} 
            value={depFederal} 
            onChange={(v) => { setDepFederal(v); setMissing(missing.filter(m => m.id !== 'sec-depFederal')); }} 
            digits={4}
          />
          
          <TabelaSelecao 
            id="sec-depEstadual"
            label="2º - Deputado Estadual (5 números)" 
            options={candidatosData.deputadosEstaduais} 
            value={depEstadual} 
            onChange={(v) => { setDepEstadual(v); setMissing(missing.filter(m => m.id !== 'sec-depEstadual')); }} 
            digits={5}
          />

          <TabelaSelecao 
            id="sec-senador1"
            label="3º - Primeiro Senador (3 números)" 
            options={candidatosData.senadores} 
            value={senador1} 
            onChange={(v) => { setSenador1(v); setMissing(missing.filter(m => m.id !== 'sec-senador1')); }} 
            digits={3}
          />

          <TabelaSelecao 
            id="sec-senador2"
            label="4º - Segundo Senador (3 números)" 
            options={candidatosData.senadores.filter(s => !(senador1 && !senador1.isOutro && s.numero === senador1.numero))} 
            value={senador2} 
            onChange={(v) => { setSenador2(v); setMissing(missing.filter(m => m.id !== 'sec-senador2')); }} 
            digits={3}
          />

          <div className="mb-6 p-6 bg-green-50 rounded-xl border-2 border-brverde opacity-90">
            <h2 className="text-2xl font-bold text-gray-800 mb-2">Governador e Presidente</h2>
            <p className="text-gray-600 mb-4">Estas opções já estão fixadas na sua colinha.</p>
            <div className="flex flex-col md:flex-row gap-4">
              <div className="flex-1 bg-white p-4 rounded-lg border border-green-200">
                <span className="block font-bold text-gray-700 text-sm uppercase">5º - Governador</span>
                <span className="block text-2xl font-black text-brverde mt-1">22 - Zucco</span>
              </div>
              <div className="flex-1 bg-white p-4 rounded-lg border border-green-200">
                <span className="block font-bold text-gray-700 text-sm uppercase">6º - Presidente</span>
                <span className="block text-2xl font-black text-brverde mt-1">22 - Bolsonaro</span>
              </div>
            </div>
          </div>
          
          {missing.length > 0 && (
            <div id="error-box" className="mb-6 p-5 bg-red-50 border-2 border-red-500 rounded-xl">
              <h3 className="text-xl font-bold text-red-700 mb-3"><i className="fa-solid fa-triangle-exclamation mr-2"></i>Atenção: Faltam algumas escolhas</h3>
              <p className="text-red-600 mb-4">Por favor, escolha um candidato para os seguintes cargos antes de salvar:</p>
              <div className="flex flex-col gap-2">
                {missing.map((m) => (
                  <div key={m.id} className="flex items-center justify-between bg-white p-3 rounded border border-red-200 shadow-sm">
                    <span className="font-bold text-gray-800">{m.nome}</span>
                    <button type="button" onClick={() => scrollTo(m.id)} className="bg-red-100 hover:bg-red-200 text-red-700 px-4 py-2 rounded-lg font-bold transition-colors flex items-center gap-2">
                      Ir para escolher <i className="fa-solid fa-arrow-up"></i>
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="flex flex-col sm:flex-row gap-4 mt-8">
            {onCancel && (
              <button type="button" onClick={onCancel} className="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 text-xl font-bold py-4 px-6 rounded-xl transition-colors">
                Cancelar Alteração
              </button>
            )}
            <button type="submit" className="flex-1 bg-brverde hover:bg-green-700 text-white text-2xl font-bold py-4 px-6 rounded-xl shadow-lg transition-colors">
              Salvar Colinha
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function UrnaBoxes({ numero, isYellow }) {
  const chars = String(numero).split('');
  return (
    <div className="flex flex-wrap mt-2">
      {chars.map((char, i) => (
        <div key={i} className={`w-[45px] h-[55px] md:w-[50px] md:h-[65px] flex items-center justify-center text-3xl font-black border-2 rounded shadow-sm mx-0.5 ${isYellow ? 'border-bramarelo bg-yellow-50 text-yellow-900' : 'border-gray-400 bg-white text-gray-800'}`}>
          {char}
        </div>
      ))}
    </div>
  );
}

function ColinhaItem({ cargo, candidato, isFixed }) {
  const isYellow = candidato?.isOutro;
  
  return (
    <div className={`mb-4 p-4 md:p-5 rounded-xl border-l-8 shadow-sm ${isYellow ? 'border-l-bramarelo border-y-2 border-r-2 border-bramarelo bg-yellow-50' : 'border-l-brverde border-y-2 border-r-2 border-gray-200 bg-white'}`}>
      <h3 className="text-xs md:text-sm uppercase tracking-widest text-gray-500 font-bold mb-1">{cargo}</h3>
      {isYellow && <span className="inline-block px-2 py-1 bg-bramarelo text-yellow-900 text-[10px] font-bold rounded mb-2 uppercase">Inserido Manualmente</span>}
      
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="text-2xl md:text-3xl font-bold text-gray-800 leading-tight">
            {candidato?.nome || 'Não definido'}
          </div>
          <UrnaBoxes numero={candidato?.numero || ''} isYellow={isYellow} />
        </div>

        {/* Informações mantidas na colinha */}
        {!isYellow && !isFixed && (candidato?.arg1 || candidato?.regiao) && (
          <div className="mt-3 md:mt-0 md:ml-4 flex-1 bg-gray-50 p-3 rounded-lg border border-gray-100 text-sm text-gray-700">
            {candidato.arg1 && <div className="mb-1"><span className="font-semibold text-brverde">Por que escolhi:</span> {candidato.arg1}</div>}
            {candidato.arg2 && <div className="mb-1 text-gray-600">{candidato.arg2}</div>}
            {candidato.regiao && <div><span className="font-semibold text-gray-800">Região:</span> {candidato.regiao}</div>}
          </div>
        )}
      </div>
    </div>
  );
}

function Colinha({ choices, onEdit, onLogout, userName }) {
  return (
    <div className="max-w-3xl mx-auto p-4 md:p-6 pb-12">
      
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-xl md:text-2xl font-bold text-brverde">Olá, {userName}</h1>
        <button onClick={onLogout} className="text-gray-500 hover:text-gray-700 bg-gray-200 px-3 py-2 rounded-lg text-sm font-bold">
          <i className="fa-solid fa-right-from-bracket"></i> Sair
        </button>
      </div>

      <div className="bg-gray-200 p-4 rounded-t-2xl shadow-inner border-b-4 border-brverde">
        <h2 className="text-center font-black text-2xl text-gray-700 uppercase tracking-widest">
          Sua Colinha
        </h2>
        <p className="text-center text-sm text-gray-600 font-medium mt-1">Leve junto no dia da votação para lembrar dos seus escolhidos</p>
      </div>

      <div className="bg-gray-100 p-3 md:p-5 rounded-b-2xl shadow-xl border-2 border-t-0 border-gray-300">
        
        <ColinhaItem cargo="1º - Deputado Federal" candidato={choices.depFederal} />
        <ColinhaItem cargo="2º - Deputado Estadual" candidato={choices.depEstadual} />
        <ColinhaItem cargo="3º - Primeiro Senador" candidato={choices.senador1} />
        <ColinhaItem cargo="4º - Segundo Senador" candidato={choices.senador2} />
        <ColinhaItem cargo="5º - Governador" candidato={{ nome: 'Zucco', numero: '22', isOutro: false }} isFixed={true} />
        <ColinhaItem cargo="6º - Presidente" candidato={{ nome: 'Bolsonaro', numero: '22', isOutro: false }} isFixed={true} />

        <div className="mt-8 mb-2">
          <button onClick={onEdit} className="w-full bg-white border-2 border-brverde text-brverde hover:bg-green-50 text-xl font-bold py-4 rounded-xl shadow-sm transition-colors flex items-center justify-center gap-2">
            <i className="fa-solid fa-pen-to-square"></i> Alterar Escolhas
          </button>
        </div>
      </div>
      
    </div>
  );
}

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