/* ═══════════════════════════════════════════════════════════════════
   LOGIN — Flowze
   iOS PWA · floating labels · haptics · Dynamic-Island toast
   ═══════════════════════════════════════════════════════════════════ */
const { useState, useRef, useEffect } = React;
const Icon = window.Icon;

const SUPABASE_URL = 'https://rziiztwvwdggyekstamr.supabase.co';
const SUPABASE_KEY = 'sb_publishable_LBwflM-nWvJ_RSIoldG_Gg_112ZWeAL';
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_KEY);

/* ── shared helpers ───────────────────────────────────────────── */
window.haptic = window.haptic || function (pattern = "light") {
  if (!navigator.vibrate) return;
  const p = { light: 8, medium: 14, heavy: [10, 30, 10], success: [12, 40, 12], error: [40, 60, 40] }[pattern] || 8;
  try { navigator.vibrate(p); } catch (e) {}
};

/* ── floating-label input ─────────────────────────────────────── */
function InField({ type = "text", icon, label, value, onChange, autoComplete, inputMode, error }) {
  const [focus, setFocus] = useState(false);
  const [show, setShow]   = useState(false);
  const isPass = type === "password";
  const t = isPass && show ? "text" : type;
  return (
    <div>
      <div className={
        "in-field" +
        (focus ? " is-focus" : "") +
        (value ? " has-value" : "") +
        (error ? " has-error" : "")
      }>
        <span className="ico">{icon}</span>
        <input
          type={t}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => { setFocus(true); window.haptic("light"); }}
          onBlur={() => setFocus(false)}
          autoComplete={autoComplete}
          inputMode={inputMode}
          aria-label={label}
        />
        <span className="lbl">{label}</span>
        {isPass && (
          <button className="eye" type="button"
            onClick={() => { setShow((s) => !s); window.haptic("light"); }}
            aria-label={show ? "Ocultar senha" : "Mostrar senha"}>
            {show ? (
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94" />
                <path d="M9.9 4.24A10.94 10.94 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19" />
                <path d="M14.12 14.12A3 3 0 1 1 9.88 9.88" />
                <line x1="1" y1="1" x2="23" y2="23" />
              </svg>
            ) : (
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
                <circle cx="12" cy="12" r="3" />
              </svg>
            )}
          </button>
        )}
      </div>
      {error && <div className="in-help err">{error}</div>}
    </div>
  );
}

/* ── toast (Dynamic-Island style) ─────────────────────────────── */
function useToast() {
  const [t, setT] = useState(null);
  const tref = useRef(null);
  const show = (title, msg, kind = "info") => {
    clearTimeout(tref.current);
    setT({ title, msg, kind, n: Date.now() });
    tref.current = setTimeout(() => setT(null), 2600);
  };
  return [t, show];
}

function Toast({ data }) {
  return (
    <div className="toast-host">
      <div className={"toast" + (data ? " is-show" : "")}>
        <div className={"toast-icon is-" + (data?.kind || "info")}>
          {data?.kind === "ok"   && <Icon.Check s={16} />}
          {data?.kind === "err"  && <Icon.X s={16} />}
          {data?.kind === "warn" && <Icon.Bell s={16} />}
          {(!data || data?.kind === "info") && <Icon.Sparkle s={16} />}
        </div>
        <div className="toast-body">
          <div className="toast-title">{data?.title || ""}</div>
          {data?.msg && <div className="toast-msg">{data.msg}</div>}
        </div>
      </div>
    </div>
  );
}

/* ── brand mark + wordmark ────────────────────────────────────── */
function Brand() {
  return (
    <div className="brand">
      <img src="src/flowz-icon.png" alt="FlowZ" className="brand-icon" />
      <div style={{ textAlign: "center" }}>
        <div className="brand-word">FLOWZ</div>
      </div>
      <div className="brand-voltz">
        <span className="brand-voltz-by">um app da</span>
        <img src="src/voltz-logo.png" alt="VoltZ" className="brand-voltz-logo" />
      </div>
    </div>
  );
}

/* ── social buttons ───────────────────────────────────────────── */
const GoogleIco = () => (
  <svg viewBox="0 0 24 24" width="18" height="18">
    <path fill="#4285F4" d="M23.49 12.27c0-.79-.07-1.54-.19-2.27H12v4.51h6.44c-.27 1.4-1.07 2.6-2.29 3.4v2.84h3.71c2.17-2 3.43-4.94 3.43-8.48z"/>
    <path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.93-2.92l-3.71-2.84c-1.06.73-2.46 1.16-4.22 1.16-3.24 0-5.99-2.18-6.97-5.12H1.18v2.84A11.99 11.99 0 0 0 12 24z"/>
    <path fill="#FBBC04" d="M5.03 14.28A7.18 7.18 0 0 1 4.66 12c0-.79.13-1.55.37-2.28V6.88H1.18A11.99 11.99 0 0 0 0 12c0 1.94.47 3.77 1.18 5.12l3.85-2.84z"/>
    <path fill="#EA4335" d="M12 4.76c1.77 0 3.35.61 4.6 1.8l3.27-3.27C17.94 1.19 15.24 0 12 0A11.99 11.99 0 0 0 1.18 6.88l3.85 2.84C6.01 6.78 8.76 4.76 12 4.76z"/>
  </svg>
);
const AppleIco = () => (
  <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
    <path d="M17.05 12.04c-.03-3 2.45-4.45 2.56-4.52-1.4-2.04-3.58-2.32-4.35-2.35-1.85-.19-3.6 1.09-4.54 1.09-.94 0-2.39-1.06-3.93-1.03-2.02.03-3.89 1.18-4.93 2.98-2.1 3.65-.54 9.04 1.5 12 .99 1.45 2.17 3.08 3.71 3.02 1.49-.06 2.05-.96 3.85-.96 1.8 0 2.31.96 3.88.93 1.6-.03 2.61-1.48 3.59-2.93 1.13-1.68 1.6-3.31 1.63-3.4-.04-.02-3.13-1.2-3.16-4.77zM14.07 3.27c.82-1 1.38-2.39 1.23-3.77-1.19.05-2.63.79-3.48 1.79-.76.88-1.43 2.3-1.25 3.65 1.32.1 2.68-.67 3.5-1.67z"/>
  </svg>
);

/* ── set-password form (invite / recovery flow) ───────────────── */
function SetPasswordForm({ showToast }) {
  const [pass,    setPass]    = useState("");
  const [confirm, setConfirm] = useState("");
  const [err,     setErr]     = useState({});
  const [loading, setLoading] = useState(false);
  const [ready,   setReady]   = useState(false);

  useEffect(() => {
    /* SDK v2 processes the hash automatically on getSession */
    sb.auth.getSession().then(({ data: { session } }) => {
      if (session) setReady(true);
      else showToast("Link inválido", "Este link expirou ou já foi usado.", "err");
    });
  }, []);

  const submit = async (e) => {
    e?.preventDefault();
    const next = {};
    if (!pass || pass.length < 6)   next.pass    = "Mínimo 6 caracteres";
    if (pass !== confirm)            next.confirm = "As senhas não coincidem";
    setErr(next);
    if (Object.keys(next).length) { window.haptic("error"); return; }

    setLoading(true);
    window.haptic("medium");
    const { error } = await sb.auth.updateUser({ password: pass });
    if (error) {
      setLoading(false);
      window.haptic("error");
      showToast("Erro", error.message, "err");
    } else {
      window.haptic("success");
      showToast("Senha criada!", "Entrando no seu palco…", "ok");
      setTimeout(() => { window.location.href = '/shows'; }, 900);
    }
  };

  const LockIco = (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
    </svg>
  );

  return (
    <div className="enter">
      <Brand />
      <header className="auth-head">
        <div className="auth-eyebrow">ASSINATURA CONFIRMADA</div>
        <h1 className="auth-h1">Crie sua <span className="accent">senha</span></h1>
        <p className="auth-sub">Escolha uma senha para acessar o FlowZ.</p>
      </header>

      <form className="auth-form" onSubmit={submit} noValidate>
        <div className="form-login-label">Nova senha</div>
        <InField
          label="Senha"
          value={pass}
          onChange={(v) => { setPass(v); if (err.pass) setErr({ ...err, pass: null }); }}
          type="password"
          autoComplete="new-password"
          icon={LockIco}
          error={err.pass}
        />
        <InField
          label="Confirmar senha"
          value={confirm}
          onChange={(v) => { setConfirm(v); if (err.confirm) setErr({ ...err, confirm: null }); }}
          type="password"
          autoComplete="new-password"
          icon={LockIco}
          error={err.confirm}
        />
        <button
          className={"cta" + (loading ? " is-loading" : "")}
          type="submit"
          disabled={loading || !ready}
        >
          {loading
            ? <><span className="cta-spinner"></span> Salvando…</>
            : <>Criar senha e entrar <Icon.ChevronR s={18} className="arrow" /></>}
        </button>
      </form>
    </div>
  );
}

/* ── main login page ──────────────────────────────────────────── */
function LoginPage() {
  const [email, setEmail] = useState("");
  const [pass,  setPass]  = useState("");
  const [err,   setErr]   = useState({});
  const [loading, setLoading] = useState(false);
  const [toast, showToast] = useToast();

  /* detect invite / password-recovery token in URL hash */
  const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, ''));
  const hashType   = hashParams.get('type');
  const isSetPass  = hashType === 'invite' || hashType === 'recovery';

  const isWelcome = new URLSearchParams(window.location.search).get("welcome") === "true";

  useEffect(() => {
    if (isSetPass) return; // SDK handles hash; SetPasswordForm takes over
    sb.auth.getSession().then(({ data: { session } }) => {
      if (session) window.location.href = '/shows';
    });
    if (isWelcome) showToast("Assinatura confirmada!", "Verifique seu email para criar sua senha.", "ok");
  }, []);

  const submit = async (e) => {
    e?.preventDefault();
    const next = {};
    if (!email)                                    next.email = "Informe seu email";
    else if (!/^[^@]+@[^@]+\.[^@]+$/.test(email)) next.email = "Email inválido";
    if (!pass) next.pass = "Informe sua senha";
    else if (pass.length < 6) next.pass = "Mínimo 6 caracteres";
    setErr(next);
    if (Object.keys(next).length) { window.haptic("error"); return; }

    setLoading(true);
    window.haptic("medium");

    const { error } = await sb.auth.signInWithPassword({ email, password: pass });

    if (error) {
      setLoading(false);
      window.haptic("error");
      showToast("Erro ao entrar", "Email ou senha incorretos", "err");
      setErr({ pass: "Email ou senha incorretos" });
    } else {
      window.haptic("success");
      showToast("Bem-vindo!", "Conectado ao palco", "ok");
      setTimeout(() => { window.location.href = '/shows'; }, 800);
    }
  };

  const social = async (name) => {
    window.haptic("light");
    showToast(name, "Redirecionando ao provedor…", "info");
    const provider = name === "Google" ? "google" : "apple";
    await sb.auth.signInWithOAuth({
      provider,
      options: { redirectTo: window.location.origin + '/shows' }
    });
  };

  const forgotPass = async (e) => {
    e.preventDefault();
    if (!email) { setErr({ ...err, email: "Informe seu email para recuperação" }); return; }
    const { error } = await sb.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + '/login/',
    });
    if (error) showToast("Erro", error.message, "err");
    else showToast("Recuperar senha", "Verifique seu email", "ok");
  };

  const bg = (
    <div className="auth-bg" aria-hidden="true">
      {window.LoopStage && window.BgLoginScene
        ? <window.LoopStage duration={12}><window.BgLoginScene /></window.LoopStage>
        : (<><span className="glow"/><span className="ring r1"/><span className="ring r2"/><span className="ring r3"/></>)
      }
    </div>
  );

  if (isSetPass) {
    return (
      <div className="auth">
        {bg}
        <Toast data={toast} />
        <SetPasswordForm showToast={showToast} />
      </div>
    );
  }

  return (
    <div className="auth">
      {bg}

      <Toast data={toast} />
      <div className="enter">
        <Brand />

        <header className="auth-head">
          <div className="auth-eyebrow">BEM-VINDO DE VOLTA</div>
          <h1 className="auth-h1">
            Entre no <span className="accent">seu palco</span>
          </h1>
          <p className="auth-sub">Acesse seu painel de pré-produção.</p>
        </header>

        <form className="auth-form" onSubmit={submit} noValidate>
          <div className="form-login-label">Faça seu login</div>
          <InField
            label="Email"
            value={email}
            onChange={(v) => { setEmail(v); if (err.email) setErr({ ...err, email: null }); }}
            type="email"
            inputMode="email"
            autoComplete="email"
            icon={<Icon.User s={18} />}
            error={err.email}
          />
          <div>
            <InField
              label="Senha"
              value={pass}
              onChange={(v) => { setPass(v); if (err.pass) setErr({ ...err, pass: null }); }}
              type="password"
              autoComplete="current-password"
              icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>}
              error={err.pass}
            />
            <div className="in-help">
              <span>Use no mínimo 6 caracteres</span>
              <a href="#esqueci" onClick={forgotPass}>Esqueci minha senha</a>
            </div>
          </div>

          <button className={"cta" + (loading ? " is-loading" : "")} type="submit" disabled={loading}>
            {loading ? (
              <><span className="cta-spinner"></span> Conectando…</>
            ) : (
              <>Entrar <Icon.ChevronR s={18} className="arrow" /></>
            )}
          </button>
        </form>

        <div className="divider"><span>ou continue com</span></div>

        <div className="social-row">
          <button className="social-btn" type="button" onClick={() => social("Google")}>
            <GoogleIco /> Google
          </button>
          <button className="social-btn" type="button" onClick={() => social("Apple")}>
            <AppleIco /> Apple
          </button>
        </div>

        <div className="auth-foot">
          Novo por aqui?
          <a href="/assinatura/">Criar conta</a>
        </div>

        <div className="trust-row">
          <span className="trust"><Icon.Check s={12} /> Dados seguros</span>
          <span className="trust"><Icon.Sparkle s={12} /> 100% nuvem</span>
          <span className="trust"><Icon.Bell s={12} /> Suporte 24/7</span>
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
