// Login.jsx
'use strict';
const { useState } = React;

const DEMO_EMAIL = 'demo@demoservicos.com';
const DEMO_PASS  = 'demo123';

function Login({ onLogin }) {
  const [email, setEmail]     = useState('');
  const [pass, setPass]       = useState('');
  const [showPass, setShow]   = useState(false);
  const [err, setErr]         = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = e => {
    e.preventDefault();
    setErr('');
    if (!email || !pass) { setErr('Preencha e-mail e senha para continuar.'); return; }
    setLoading(true);
    setTimeout(() => {
      if (email.trim().toLowerCase() === DEMO_EMAIL && pass === DEMO_PASS) {
        onLogin({ name: 'Ademir Machado', email: DEMO_EMAIL, role: 'Administrador' });
      } else {
        setErr('Credenciais inválidas. Use o acesso demo abaixo.');
        setLoading(false);
      }
    }, 800);
  };

  const fillDemo = () => { setEmail(DEMO_EMAIL); setPass(DEMO_PASS); setErr(''); };

  const inputCls = 'w-full pl-11 pr-4 py-3 rounded-xl border border-slate-200 text-sm transition-all ' +
    'hover:border-slate-300 focus:border-accent focus:ring-4 focus:ring-orange-100 bg-slate-50/60 focus:bg-white';

  return (
    <div className="relative min-h-screen flex items-center justify-center overflow-hidden px-4"
      style={{
        backgroundColor: '#0A1F44',
        backgroundImage: 'linear-gradient(150deg, #0d2856 0%, #0A1F44 45%, #06152d 100%)',
        paddingTop:    'max(1.5rem, env(safe-area-inset-top))',
        paddingBottom: 'max(1.5rem, env(safe-area-inset-bottom))',
        paddingLeft:   'max(1rem, env(safe-area-inset-left))',
        paddingRight:  'max(1rem, env(safe-area-inset-right))',
      }}>

      {/* Atmosfera: dois glows sutis, sem poluição visual */}
      <div aria-hidden style={{
        position:'absolute', top:-180, right:-140, width:520, height:520, borderRadius:'50%',
        background:'radial-gradient(circle, rgba(255,107,53,0.26) 0%, transparent 68%)',
        filter:'blur(60px)', pointerEvents:'none',
      }} />
      <div aria-hidden style={{
        position:'absolute', bottom:-200, left:-160, width:540, height:540, borderRadius:'50%',
        background:'radial-gradient(circle, rgba(59,130,246,0.20) 0%, transparent 68%)',
        filter:'blur(60px)', pointerEvents:'none',
      }} />

      {/* Textura de serviço (chaves + engrenagens) — SVG transparente, some no centro */}
      <svg aria-hidden className="absolute inset-0 w-full h-full pointer-events-none"
        preserveAspectRatio="xMidYMid slice"
        style={{
          maskImage:'radial-gradient(ellipse 62% 58% at 50% 46%, transparent 34%, black 82%)',
          WebkitMaskImage:'radial-gradient(ellipse 62% 58% at 50% 46%, transparent 34%, black 82%)',
        }}>
        <defs>
          <pattern id="svc-tools" patternUnits="userSpaceOnUse" width="168" height="168" patternTransform="rotate(-9)">
            <g fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              {/* chave inglesa */}
              <g transform="translate(6 12) scale(1.5)">
                <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
              </g>
              {/* engrenagem */}
              <g transform="translate(96 92) scale(1.35)">
                <circle cx="12" cy="12" r="3"/>
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
              </g>
            </g>
            {/* toque de marca: uma chave em laranja bem discreta */}
            <g fill="none" stroke="rgba(255,107,53,0.09)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <g transform="translate(112 6) scale(1.05)">
                <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
              </g>
            </g>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#svc-tools)"/>
      </svg>

      <div className="relative w-full max-w-[400px] anim-fade z-10">
        {/* Marca */}
        <div className="flex justify-center mb-6">
          <BrandLogo size={44} theme="dark" showTagline={true} />
        </div>

        {/* Card do formulário */}
        <div className="relative rounded-2xl p-7 sm:p-8 bg-white"
          style={{ boxShadow:'0 30px 70px -20px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06)' }}>

          <div className="mb-6">
            <h1 className="text-xl font-extrabold tracking-tight" style={{ color:'#0A1F44' }}>Bem-vindo de volta</h1>
            <p className="text-sm text-slate-500 mt-1">Entre com suas credenciais para acessar o painel.</p>
          </div>

          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            <div>
              <label className="block text-[13px] font-semibold mb-1.5" style={{ color:'#334155' }}>E-mail</label>
              <div className="relative">
                <Icon name="Mail" size={16} color="#94A3B8" style={{ position:'absolute', left:14, top:'50%', transform:'translateY(-50%)' }} />
                <input type="email" value={email} onChange={e=>setEmail(e.target.value)}
                  placeholder="seu@email.com" autoComplete="email"
                  className={inputCls} style={{ color:'#1E293B' }} />
              </div>
            </div>

            <div>
              <label className="block text-[13px] font-semibold mb-1.5" style={{ color:'#334155' }}>Senha</label>
              <div className="relative">
                <Icon name="Lock" size={16} color="#94A3B8" style={{ position:'absolute', left:14, top:'50%', transform:'translateY(-50%)' }} />
                <input type={showPass ? 'text' : 'password'} value={pass} onChange={e=>setPass(e.target.value)}
                  placeholder="••••••••" autoComplete="current-password"
                  className={inputCls + ' !pr-11'} style={{ color:'#1E293B' }} />
                <button type="button" onClick={()=>setShow(s=>!s)} tabIndex={-1}
                  aria-label={showPass ? 'Ocultar senha' : 'Mostrar senha'}
                  className="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-md text-slate-400 hover:text-slate-600 transition-colors">
                  <Icon name={showPass ? 'EyeOff' : 'Eye'} size={16} color="currentColor" />
                </button>
              </div>
            </div>

            {err && (
              <div className="flex items-center gap-2 px-3.5 py-2.5 rounded-xl bg-red-50 border border-red-100 anim-fade">
                <Icon name="AlertCircle" size={15} color="#EF4444" />
                <p className="text-[13px] text-red-600">{err}</p>
              </div>
            )}

            <button type="submit" disabled={loading}
              className="w-full py-3 rounded-xl font-bold text-white text-sm transition-all hover:opacity-95 active:scale-[0.98] disabled:opacity-60 flex items-center justify-center gap-2 mt-1"
              style={{
                background:'linear-gradient(135deg, #FF7E47 0%, #FF6B35 50%, #E5541F 100%)',
                boxShadow:'0 10px 22px -6px rgba(255,107,53,0.6), inset 0 1px 0 rgba(255,255,255,0.25)',
              }}>
              {loading
                ? <><Icon name="RefreshCw" size={15} color="white" className="anim-pulse" />Entrando...</>
                : <>Entrar no Sistema<Icon name="ChevronDoubleRight" size={15} color="white" /></>}
            </button>
          </form>

          {/* Divisor */}
          <div className="flex items-center gap-3 my-5">
            <div className="h-px flex-1 bg-slate-100" />
            <span className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">Acesso rápido</span>
            <div className="h-px flex-1 bg-slate-100" />
          </div>

          {/* Credenciais demo */}
          <button type="button" onClick={fillDemo}
            className="w-full text-left p-3.5 rounded-xl border transition-all hover:shadow-card active:scale-[0.99] group"
            style={{ borderColor:'#FFE0D3', background:'#FFF8F5' }}>
            <div className="flex items-center gap-2 mb-2.5">
              <span className="flex items-center justify-center w-6 h-6 rounded-lg flex-shrink-0"
                style={{ background:'linear-gradient(135deg,#FF7E47,#E5541F)' }}>
                <Icon name="Zap" size={13} color="white" />
              </span>
              <span className="text-[12px] font-bold tracking-wide" style={{ color:'#E5541F' }}>CONTA DEMONSTRAÇÃO</span>
              <span className="ml-auto text-[11px] font-medium text-slate-400 group-hover:text-accent transition-colors">
                Preencher →
              </span>
            </div>
            <div className="pl-8 space-y-1.5 text-xs">
              <div className="flex items-center gap-2">
                <span className="text-slate-400 text-[10px] uppercase tracking-wide w-12 flex-shrink-0">E-mail</span>
                <span className="font-mono font-semibold text-slate-700">{DEMO_EMAIL}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-slate-400 text-[10px] uppercase tracking-wide w-12 flex-shrink-0">Senha</span>
                <span className="font-mono font-semibold text-slate-700">{DEMO_PASS}</span>
              </div>
            </div>
          </button>
        </div>

        {/* Selos de confiança */}
        <div className="mt-6 flex items-center justify-center gap-4 text-[11px] flex-wrap" style={{ color:'rgba(255,255,255,0.5)' }}>
          <span className="flex items-center gap-1.5"><Icon name="ShieldCheck" size={13} color="rgba(255,255,255,0.55)"/>Dados protegidos</span>
          <span className="opacity-25">•</span>
          <span className="flex items-center gap-1.5"><Icon name="Zap" size={13} color="rgba(255,255,255,0.55)"/>Acesso instantâneo</span>
          <span className="opacity-25">•</span>
          <span className="flex items-center gap-1.5"><Icon name="CheckCircle" size={13} color="rgba(255,255,255,0.55)"/>Sem instalação</span>
        </div>

        <p className="text-center text-[11px] mt-5" style={{ color:'rgba(255,255,255,0.34)' }}>
          Desenvolvido pela <span style={{ color:'rgba(255,255,255,0.6)', fontWeight:600 }}>JuFlow Digital</span>
          <br className="sm:hidden"/> — Software sob medida para o seu negócio
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
