// Login + OTP screens

function LoginPage({ onLogin }) {
  const [stage, setStage] = useState("login");      // 'login' | 'otp'
  const [error, setError] = useState(null);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [otp, setOtp] = useState("");

  const [submitting, setSubmitting] = useState(false);

  const submitLogin = async (e) => {
    e.preventDefault();
    setError(null);
    if (!username || !password) { setError("Inserisci username e password."); return; }
    setSubmitting(true);
    try {
      const res = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.error || "Credenziali non valide");
      } else if (data.stage === "otp") {
        setStage("otp");
      } else {
        onLogin(data.user);
      }
    } catch {
      setError("Errore di rete. Riprova.");
    } finally {
      setSubmitting(false);
    }
  };

  const submitOtp = async (e) => {
    e.preventDefault();
    if (otp.length !== 6) { setError("Il codice deve essere di 6 cifre."); return; }
    setSubmitting(true);
    try {
      const res = await fetch("/api/verify-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: otp }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.error || "Codice non valido o scaduto");
      } else {
        onLogin(data.user);
      }
    } catch {
      setError("Errore di rete. Riprova.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="login-page" data-screen-label="00 Login">

      {/* HERO */}
      <div className="login-hero" style={{position:"relative", overflow:"hidden", padding:0}}>

        {/* Grafico SVG di sfondo */}
        <svg viewBox="0 0 600 480" xmlns="http://www.w3.org/2000/svg"
          style={{position:"absolute", inset:0, width:"100%", height:"100%", opacity:0.18}}>
          {/* Griglia */}
          {[80,160,240,320,400].map(y => (
            <line key={y} x1="0" y1={y} x2="600" y2={y} stroke="#6ea8fe" strokeWidth="0.5" strokeDasharray="4 8"/>
          ))}
          {[100,200,300,400,500].map(x => (
            <line key={x} x1={x} y1="0" x2={x} y2="480" stroke="#6ea8fe" strokeWidth="0.5" strokeDasharray="4 8"/>
          ))}
          {/* Moving average blu */}
          <polyline points="0,380 60,340 120,310 180,260 240,230 300,200 360,175 420,155 480,130 540,110 600,90"
            fill="none" stroke="#6ea8fe" strokeWidth="2" strokeLinecap="round"/>
          {/* Moving average arancio */}
          <polyline points="0,400 60,370 120,355 180,310 240,290 300,265 360,240 420,210 480,190 540,165 600,140"
            fill="none" stroke="#f59e0b" strokeWidth="1.5" strokeDasharray="6 3" strokeLinecap="round"/>
          {/* Area sotto la curva blu */}
          <polygon points="0,380 60,340 120,310 180,260 240,230 300,200 360,175 420,155 480,130 540,110 600,90 600,480 0,480"
            fill="url(#grad)" opacity="0.3"/>
          <defs>
            <linearGradient id="grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#6ea8fe" stopOpacity="0.5"/>
              <stop offset="100%" stopColor="#6ea8fe" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* Candele */}
          {[
            [40, 360, 320, 305, 375],
            [90, 335, 295, 285, 348],
            [140, 305, 268, 260, 318],
            [190, 268, 232, 225, 275],
            [240, 238, 198, 192, 245],
            [290, 208, 172, 165, 215],
            [340, 182, 148, 140, 190],
            [390, 160, 126, 120, 168],
            [440, 138, 106, 100, 145],
            [490, 116, 86,  80,  123],
            [540, 98,  72,  66,  105],
          ].map(([x, o, c, l, h], i) => {
            const bullish = c < o;
            const color = bullish ? "#22c55e" : "#ef4444";
            const top = Math.min(o, c), bot = Math.max(o, c);
            return (
              <g key={i}>
                <line x1={x} y1={l} x2={x} y2={h} stroke={color} strokeWidth="1.2"/>
                <rect x={x-6} y={top} width={12} height={Math.max(2, bot - top)} fill={color} rx="1"/>
              </g>
            );
          })}
        </svg>

        {/* Overlay gradiente per leggibilità */}
        <div style={{
          position:"absolute", inset:0,
          background:"linear-gradient(135deg, oklch(0.12 0.02 255 / 0.85) 0%, oklch(0.10 0.015 255 / 0.75) 100%)",
        }}/>

        {/* Contenuto */}
        <div style={{
          position:"relative", zIndex:1,
          display:"flex", flexDirection:"column", height:"100%",
          padding:"36px 40px",
        }}>
          <div className="login-brand">
            <div className="mark"><Icon name="trending" size={16} strokeWidth={2.2}/></div>
            <span>BVF Analyzer</span>
          </div>

          <div style={{marginTop:"auto", marginBottom:"auto"}}>
            <h1 style={{
              fontSize:"clamp(36px,4vw,52px)", fontWeight:700, lineHeight:1.1,
              letterSpacing:"-0.03em",
            }}>
              BVF<br/>
              <em style={{
                fontStyle:"normal",
                background:"linear-gradient(90deg, #6ea8fe 0%, #74cfd8 100%)",
                WebkitBackgroundClip:"text", WebkitTextFillColor:"transparent",
              }}>Stock Analyzer</em>
            </h1>
            <p className="tagline" style={{marginTop:18, maxWidth:340, lineHeight:1.65}}>
              Analisi multi-layer in tempo reale: AI Agent, modello tecnico-statistico e sentiment news su ogni ticker del watchlist.
            </p>
          </div>

          <p style={{fontSize:11.5, color:"var(--text-faint)"}}>
            v2.4 · Solo per uso interno · Accesso monitorato
          </p>
        </div>
      </div>

      {/* FORM */}
      <div className="login-form-side">
        {stage === "login" ? (
          <form className="login-form" onSubmit={submitLogin} data-screen-label="00a Login form">
            <div>
              <h2>Accesso</h2>
              <p className="subtitle" style={{marginTop: 6}}>Autenticazione a due fattori via Telegram.</p>
            </div>

            {error && (
              <div className="error-msg">
                <Icon name="x" size={14}/>
                <span>{error}</span>
              </div>
            )}

            <div className="field">
              <label>Username</label>
              <input className="input" autoFocus value={username}
                     autoCapitalize="none" autoCorrect="off" spellCheck={false}
                     autoComplete="username" inputMode="text"
                     onChange={e => setUsername(e.target.value)} placeholder="Username"/>
            </div>

            <div className="field">
              <label>Password</label>
              <div className="input-wrap">
                <input className="input with-icon" type={showPwd ? "text" : "password"}
                       value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••"/>
                <button type="button" className="input-icon-btn" onClick={()=>setShowPwd(s=>!s)} title={showPwd ? "Nascondi" : "Mostra"}>
                  <Icon name={showPwd ? "eyeOff" : "eye"} size={15}/>
                </button>
              </div>
            </div>

            <button type="submit" className="btn btn-primary btn-block" style={{padding: "12px 14px"}} disabled={submitting}>
              {submitting ? "Accesso in corso…" : <><span>Accedi</span><Icon name="arrowRight" size={15}/></>}
            </button>

            <div style={{textAlign: "center", color: "var(--text-faint)", fontSize: 12}}>
              Sistema interno · accesso riservato
            </div>
          </form>
        ) : (
          <form className="login-form" onSubmit={submitOtp} data-screen-label="00b OTP form">
            <button type="button" className="btn btn-ghost btn-sm" style={{alignSelf:"flex-start", padding:"4px 8px"}} onClick={()=>{setStage("login");setOtp("");setError(null);}}>
              <Icon name="arrowLeft" size={13}/> Indietro
            </button>

            <div>
              <h2>Codice di verifica</h2>
              <p className="subtitle" style={{marginTop: 6}}>
                Inviato sul tuo Telegram. Scade fra <span className="mono">9:42</span>.
              </p>
            </div>

            {error && (
              <div className="error-msg">
                <Icon name="x" size={14}/>
                <span>{error}</span>
              </div>
            )}

            <div className="field">
              <label>Codice a 6 cifre</label>
              <input className="input otp-input mono" inputMode="numeric" maxLength={6}
                     value={otp} onChange={e => setOtp(e.target.value.replace(/\D/g, ""))} autoFocus
                     placeholder="• • • • • •"/>
            </div>

            <button type="submit" className="btn btn-primary btn-block" style={{padding: "12px 14px"}} disabled={submitting}>
              {submitting ? "Verifica in corso…" : <><span>Verifica</span><Icon name="check" size={15}/></>}
            </button>

            <div style={{textAlign:"center", fontSize:12, color:"var(--text-muted)"}}>
              Non hai ricevuto il codice?{" "}
              <a href="#" style={{color: "var(--accent)"}} onClick={e => {e.preventDefault();}}>Reinvia</a>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
