/* global React */
const { useState: useStateSim, useMemo: useMemoSim } = React;

function Simulator({ savingsPct = 16, onSubmit }) {
  const [stage, setStage] = useStateSim(0); // 0=form, 1=upload, 2=done
  const [bill, setBill] = useStateSim(280);
  const [name, setName] = useStateSim("");
  const [phone, setPhone] = useStateSim("");
  const [city, setCity] = useStateSim("");
  const [file, setFile] = useStateSim(null);
  const [filePreview, setFilePreview] = useStateSim(null);

  const monthly = useMemoSim(() => Math.round(bill * (savingsPct / 100)), [bill, savingsPct]);
  const annual = monthly * 12;

  const onFile = (e) => {
    const f = e.target.files?.[0];
    if (f) {
      setFile(f);
      const reader = new FileReader();
      reader.onload = (ev) => setFilePreview(ev.target.result);
      reader.readAsDataURL(f);
    }
  };

  return (
    <section className="section-sim" id="simular">
      <div className="container">
        <div className="sim-grid reveal">
          <div>
            <span className="eyebrow">Cadastre sua conta</span>
            <h2 className="section-title" style={{marginTop: 16}}>
              Veja sua <em>economia real</em><br/>antes mesmo de assinar.
            </h2>
            <p className="section-sub">
              Informe o valor médio da sua conta de luz e veja quanto você economiza todo mês. Sem custo, sem compromisso.
            </p>

            <div className="sim-result" style={{marginTop: 28}}>
              <div className="label">Sua economia estimada · todo mês</div>
              <div className="number">R${monthly}</div>
              <div className="breakdown">
                <div className="row">
                  <div className="lbl">Conta atual</div>
                  <div className="val">R$ {bill}</div>
                </div>
                <div className="row">
                  <div className="lbl">Após desconto</div>
                  <div className="val">R$ {bill - monthly}</div>
                </div>
              </div>
              <div className="annual">
                Em 12 meses: <strong>R$ {annual.toLocaleString("pt-BR")}</strong> economizados.
                Em 5 anos: <strong>R$ {(annual*5).toLocaleString("pt-BR")}</strong>.
              </div>
            </div>
          </div>

          <div className="sim-card">
            <div className="sim-stage-pill">
              <span className={`dot ${stage>=0?"active":""}`}></span>
              <span>Etapa {stage+1} de 2</span>
              <span className={`dot ${stage>=1?"active":""}`}></span>
            </div>

            {stage === 0 && (
              <>
                <h3>Qual o valor da sua conta de luz?</h3>
                <p className="sub">Informe o valor médio em reais. Pode ser aproximado.</p>

                <div className="field" style={{marginTop: 16}}>
                  <label style={{fontSize: 13, color: "var(--green-700)", fontWeight: 600}}>Valor da conta CEMIG (R$)</label>
                  <input
                    type="number"
                    min="50"
                    max="50000"
                    placeholder="Digite aqui · Ex: 280"
                    value={bill}
                    onChange={(e)=>setBill(Math.max(0, +e.target.value || 0))}
                    style={{fontSize: 24, fontWeight: 700, fontFamily: "var(--font-display)", color: "var(--green-900)", borderColor: "var(--green-400)"}}
                  />
                  <input type="range" min="80" max="2000" step="10" value={Math.min(2000, Math.max(80, bill))}
                    onChange={(e)=>setBill(+e.target.value)}
                    style={{accentColor:"var(--green-700)", marginTop: 6}}/>
                  <div style={{display:"flex", justifyContent:"space-between", fontFamily:"var(--font-mono)", fontSize:11, color:"var(--ink-500)"}}>
                    <span>R$ 80</span><span>R$ 2.000+</span>
                  </div>
                </div>

                <div className="fields-row">
                  <div className="field">
                    <label>Seu nome</label>
                    <input type="text" placeholder="Nome completo" value={name} onChange={(e)=>setName(e.target.value)}/>
                  </div>
                  <div className="field">
                    <label>Cidade</label>
                    <input type="text" placeholder="Belo Horizonte" value={city} onChange={(e)=>setCity(e.target.value)}/>
                  </div>
                </div>

                <div className="field">
                  <label>WhatsApp</label>
                  <input type="tel" placeholder="(31) 9 9999-9999" value={phone} onChange={(e)=>setPhone(e.target.value)}/>
                </div>

                <div className="btn-anim btn-anim-block">
    
                  <button className="btn btn-primary btn-full" onClick={()=>setStage(1)}>
                    <div className="dots_border"></div>
                    <span className="text_button">Próximo: enviar conta (opcional)</span>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
                  </button>
                </div>
              </>
            )}

            {stage === 1 && (
              <>
                <h3>Mande sua conta (opcional)</h3>
                <p className="sub">Foto ou PDF. A gente analisa e devolve uma simulação exata em até 24h.</p>

                <label className={`upload-area ${file?"has-file":""}`}>
                  <input type="file" accept="image/*,.pdf" onChange={onFile} style={{display:"none"}}/>
                  {!file && (
                    <>
                      <div className="ic">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 3v12M7 8l5-5 5 5M5 21h14"/></svg>
                      </div>
                      <div className="ttl">Clique pra subir uma foto da sua conta</div>
                      <div className="hint">JPG, PNG ou PDF · até 10MB</div>
                    </>
                  )}
                  {file && (
                    <div className="filename">
                      {filePreview && filePreview.startsWith("data:image") ? (
                        <img src={filePreview} alt="conta"/>
                      ) : (
                        <div style={{width:56,height:56,background:"var(--green-100)",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center"}}>PDF</div>
                      )}
                      <div>
                        <div style={{fontWeight:600, fontSize:14}}>{file.name}</div>
                        <div style={{fontSize:12, color:"var(--ink-500)"}}>{Math.round(file.size/1024)}KB · pronta para envio</div>
                      </div>
                    </div>
                  )}
                </label>

                <div style={{display:"flex", gap:10}}>
                  <button className="btn btn-ghost" onClick={()=>setStage(0)}><div className="dots_border"></div><span className="text_button">Voltar</span></button>
                  <div className="btn-anim" style={{flex:1}}>
      
                    <button className="btn btn-primary btn-full"
                      onClick={()=>{ setStage(2); onSubmit?.({name,phone,city,bill,file}); }}>
                      <div className="dots_border"></div>
                      <span className="text_button">Receber simulação no WhatsApp</span>
                    </button>
                  </div>
                </div>
              </>
            )}

            {stage === 2 && (
              <div style={{textAlign:"center", padding:"24px 0"}}>
                <div style={{width:64, height:64, borderRadius:"50%", background:"var(--green-100)", margin:"0 auto 16px", display:"flex", alignItems:"center", justifyContent:"center"}}>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--green-700)" strokeWidth="2.5"><path d="M5 13l4 4L19 7"/></svg>
                </div>
                <h3>Cadastro recebido!</h3>
                <p className="sub">Em até 24h você recebe a simulação completa no WhatsApp <strong>{phone || "(31) 97142-5778"}</strong>.</p>
                <button className="btn btn-wa" onClick={()=>window.open("https://wa.me/5531971425778","_blank")} style={{marginTop: 14}}>
                  <div className="dots_border"></div>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.5-.1-.6.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6l.4-.5c.1-.2.2-.3.2-.5 0-.2 0-.4-.1-.5-.1-.1-.6-1.5-.9-2.1-.2-.5-.4-.4-.6-.5h-.5c-.2 0-.5.1-.7.3-.3.3-.9.9-.9 2.2 0 1.3.9 2.5 1 2.7.1.2 1.8 2.7 4.4 3.8 1.5.6 2.1.7 2.8.6.4 0 1.3-.5 1.5-1 .2-.5.2-1 .1-1.1-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.4c1.4.8 3.1 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
                  <span className="text_button">Falar agora no WhatsApp</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

window.Simulator = Simulator;
