// frontend/src/pages/auth/LoginPage.jsx
// Full-bleed background image (left-anchored, vertically fitted), glass panel at 75% column.

import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import logoSrc from '@/assets/logos/bell_systems_horizontal_darkMode.png'
import bgSrc from '@/assets/images/login-widescreen.jpg'

// ─── Eye toggle icons ─────────────────────────────────────────────────────────

function IconEyeOpen() {
  return (
    <svg width="15" height="15" viewBox="0 0 15 15" fill="none" aria-hidden="true">
      <path d="M1 7.5S3.5 3 7.5 3 14 7.5 14 7.5 11.5 12 7.5 12 1 7.5 1 7.5Z"
        stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" />
      <circle cx="7.5" cy="7.5" r="2" stroke="currentColor" strokeWidth="1.2" />
    </svg>
  )
}

function IconEyeClosed() {
  return (
    <svg width="15" height="15" viewBox="0 0 15 15" fill="none" aria-hidden="true">
      <path d="M1 7.5S3.5 3 7.5 3 14 7.5 14 7.5 11.5 12 7.5 12 1 7.5 1 7.5Z"
        stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" />
      <circle cx="7.5" cy="7.5" r="2" stroke="currentColor" strokeWidth="1.2" />
      <line x1="2" y1="2" x2="13" y2="13" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
    </svg>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function LoginPage() {
  const [email,     setEmail]     = useState('')
  const [password,  setPassword]  = useState('')
  const [showPwd,   setShowPwd]   = useState(false)
  const [error,     setError]     = useState('')
  const [isLoading, setIsLoading] = useState(false)

  const { login } = useAuth()
  const navigate  = useNavigate()

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setIsLoading(true)
    try {
      await login(email, password)
      navigate('/', { replace: true })
    } catch (err) {
      setError(err.message || 'Invalid credentials. Please try again.')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      <style>{`
        .login-root {
          position: fixed;
          inset: 0;
          overflow: hidden;
        }

        /* ── Background image: left-anchored, vertically-fitted ── */
        .login-bg {
          position: absolute;
          inset: 0;
          background-image: url(${bgSrc});
          background-repeat: no-repeat;
          background-position: left center;
          background-color: var(--color-bg-base);
          /* cover = always fill the viewport in both dimensions, keeping aspect ratio.
             left center = never clip the left edge; excess bleeds off to the right or bottom. */
          background-size: cover;
        }

        /* ── Subtle dark veil so right-side content is legible ── */
        .login-bg::after {
          content: '';
          position: absolute;
          inset: 0;
          background: linear-gradient(
            to right,
            rgba(10, 14, 20, 0.05) 0%,
            rgba(10, 14, 20, 0.50) 55%,
            rgba(10, 14, 20, 0.72) 100%
          );
        }

        /* ── Right-column anchor — positions content at 75% horizontally ── */
        .login-col {
          position: relative;
          z-index: 1;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          /* nudge the flex child to the 75% horizontal mark */
          justify-content: flex-end;
          padding-right: calc((100vw - 360px) * 0.25);
        }

        /* ── Form panel — no container, just width + entrance ── */
        .login-panel {
          position: relative;
          width: 360px;
          padding: var(--space-4);
          animation: login-rise 0.4s cubic-bezier(0.22, 1, 0.36, 1) both;
        }

        /* ── Soft dark radial glow behind the content — not a box ── */
        .login-panel::before {
          content: '';
          position: absolute;
          inset: -60px -80px;
          background: radial-gradient(ellipse 80% 90% at 50% 50%, rgba(0, 0, 0, 0.22) 0%, transparent 50%);
          z-index: -1;
          pointer-events: none;
        }

        @keyframes login-rise {
          from { opacity: 0; transform: translateY(18px); }
          to   { opacity: 1; transform: translateY(0);    }
        }

        /* ── Logo row ── */
        .login-logo {
          display: flex;
          justify-content: center;
          margin-bottom: var(--space-10);
        }

        /* ── Error banner ── */
        .login-error {
          display: flex;
          align-items: center;
          gap: var(--space-2);
          padding: var(--space-3) 0;
          margin-bottom: var(--space-4);
          font-size: var(--font-size-sm);
          color: var(--color-danger);
        }

        /* ── Form fields ── */
        .login-form-fields {
          display: flex;
          flex-direction: column;
          gap: var(--space-5);
        }

        /* ── "Forgot password?" row — below the field ── */
        .login-pwd-label-row {
          display: flex;
          justify-content: flex-end;
          margin-top: var(--space-2);
        }

        .login-forgot {
          background: none;
          border: none;
          padding: 0;
          cursor: pointer;
          font-size: var(--font-size-xs);
          font-family: var(--font-family-base);
          font-weight: var(--font-weight-normal);
          color: var(--color-text-muted);
          opacity: 0.5;
          transition: opacity var(--transition-fast);
        }
        .login-forgot:hover { opacity: 0.8; }

        /* ── Eye toggle ── */
        .login-eye-wrap {
          position: relative;
        }
        .login-eye-btn {
          position: absolute;
          right: var(--space-3);
          top: 50%;
          transform: translateY(-50%);
          background: none;
          border: none;
          padding: var(--space-2);
          cursor: pointer;
          color: var(--color-text-muted);
          display: flex;
          align-items: center;
          border-radius: var(--radius-md);
          transition: color var(--transition-fast);
        }
        .login-eye-btn:hover { color: var(--color-text-secondary); }

        /* ── Submit row ── */
        .login-submit {
          margin-top: var(--space-2);
        }

        /* ── Responsive: collapse to center on narrow screens ── */
        @media (max-width: 640px) {
          .login-col {
            justify-content: center;
            padding-right: var(--space-4);
            padding-left: var(--space-4);
          }
          .login-panel {
            width: 100%;
          }
        }
      `}</style>

      <div className="login-root">
        {/* Full-bleed background */}
        <div className="login-bg" />

        {/* Right-column layout */}
        <div className="login-col">
          <div className="login-panel">

            {/* Logo */}
            <div className="login-logo">
              <img
                src={logoSrc}
                alt="BellSystems"
                style={{ height: '26px', width: 'auto' }}
                draggable={false}
              />
            </div>

            {/* Error */}
            {error && (
              <div className="login-error" role="alert">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true" style={{ flexShrink: 0 }}>
                  <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.2" />
                  <line x1="7" y1="4" x2="7" y2="7.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
                  <circle cx="7" cy="9.5" r="0.8" fill="currentColor" />
                </svg>
                {error}
              </div>
            )}

            {/* Form */}
            <form onSubmit={handleSubmit} noValidate>
              <div className="login-form-fields">

                {/* EMAIL */}
                <FormField
                  name="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="Email"
                  required
                  disabled={isLoading}
                  inputProps={{ autoComplete: 'email' }}
                />

                {/* PASSWORD */}
                <div>
                  <div className="login-eye-wrap">
                    <FormField
                      name="password"
                      type={showPwd ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="Password"
                      required
                      disabled={isLoading}
                      inputProps={{
                        autoComplete: 'current-password',
                        style: { paddingRight: 'var(--space-10)' },
                      }}
                    />
                    <button
                      type="button"
                      className="login-eye-btn"
                      aria-label={showPwd ? 'Hide password' : 'Show password'}
                      onClick={() => setShowPwd((v) => !v)}
                    >
                      {showPwd ? <IconEyeOpen /> : <IconEyeClosed />}
                    </button>
                  </div>

                  <div className="login-pwd-label-row">
                    <button type="button" className="login-forgot">
                      Forgot password?
                    </button>
                  </div>
                </div>

                {/* SIGN IN */}
                <div className="login-submit">
                  <Button
                    type="submit"
                    variant="primary"
                    size="lg"
                    loading={isLoading}
                    disabled={isLoading}
                    style={{ width: '100%' }}
                  >
                    Sign in
                  </Button>
                </div>

              </div>
            </form>

          </div>
        </div>
      </div>
    </>
  )
}
