/* ============================================================
   AUTH — Sign In · Sign Up
   ============================================================ */

/* ---------- Shared shell ---------- */
function AuthShell({ children, mode }) {
  const { nav } = useStore();
  const isSignIn = mode === 'signin';
  return (
    <div style={{ minHeight: '82vh', display: 'grid', placeItems: 'center', padding: 'clamp(48px,8vw,96px) var(--gutter)' }}>
      <div style={{ width: '100%', maxWidth: 500 }}>

        {/* Brand mark */}
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <p className="eyebrow" style={{ marginBottom: 12 }}>Belle and Bloom Designs</p>
          <h1 style={{ fontSize: 'clamp(34px,5vw,52px)' }}>
            {isSignIn ? 'Welcome back' : 'Create account'}
          </h1>
          <p className="muted" style={{ marginTop: 10, fontSize: 15, lineHeight: 1.55 }}>
            {isSignIn
              ? 'Sign in to track orders, manage your wishlist and revisit past celebrations.'
              : 'Join to shop, save favourites and track every celebration.'}
          </p>
        </div>

        {/* Card */}
        <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 'clamp(28px,5vw,44px)', boxShadow: 'var(--shadow-md)' }}>
          {children}
        </div>

        {/* Switch link */}
        <p style={{ textAlign: 'center', fontSize: 14, color: 'var(--ink-soft)', marginTop: 24 }}>
          {isSignIn
            ? <>Don't have an account?{' '}<button className="link-btn" onClick={() => nav('signup')}>Sign up</button></>
            : <>Already have an account?{' '}<button className="link-btn" onClick={() => nav('signin')}>Sign in</button></>}
        </p>
      </div>
    </div>
  );
}

/* ---------- Sign In ---------- */
function SignInPage() {
  const { nav, login, toast } = useStore();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  const validate = () => {
    const e = {};
    if (!email) e.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(email)) e.email = 'Enter a valid email address';
    if (!password) e.password = 'Password is required';
    return e;
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    // Simulated auth — replace with real API call
    setTimeout(() => {
      login({ firstName: 'Ada', lastName: 'Okafor', email, phone: '+234 801 234 5678' });
      toast('Welcome back!', 'check');
      nav('account');
    }, 900);
  };

  const clr = (k) => setErrors(x => ({ ...x, [k]: '' }));

  return (
    <AuthShell mode="signin">
      <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

        <div className="field">
          <label>Email address</label>
          <input
            className={`input${errors.email ? ' input-error' : ''}`}
            type="email" value={email}
            onChange={e => { setEmail(e.target.value); clr('email'); }}
            placeholder="you@email.com"
            autoComplete="email"
          />
          {errors.email && <span className="field-error">{errors.email}</span>}
        </div>

        <div className="field">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <label style={{ margin: 0 }}>Password</label>
            <button type="button" className="link-btn" style={{ fontSize: 13 }}>Forgot password?</button>
          </div>
          <div style={{ position: 'relative' }}>
            <input
              className={`input${errors.password ? ' input-error' : ''}`}
              type={showPw ? 'text' : 'password'}
              value={password}
              onChange={e => { setPassword(e.target.value); clr('password'); }}
              placeholder="••••••••"
              autoComplete="current-password"
              style={{ paddingRight: 46 }}
            />
            <button
              type="button"
              onClick={() => setShowPw(s => !s)}
              style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-faint)', display: 'flex' }}
              aria-label={showPw ? 'Hide password' : 'Show password'}
            >
              {showPw ? <AuthEyeOff /> : <AuthEyeOn />}
            </button>
          </div>
          {errors.password && <span className="field-error">{errors.password}</span>}
        </div>

        <button className="btn btn-gold btn-block" type="submit" disabled={loading} style={{ marginTop: 4 }}>
          {loading ? <AuthSpinner /> : 'Sign in'}
        </button>

        <AuthDivider />

        <button
          type="button"
          className="btn btn-outline btn-block"
          style={{ fontSize: 13 }}
          onClick={() => nav('account')}
        >
          Continue as guest
        </button>

      </form>
    </AuthShell>
  );
}

/* ---------- Sign Up ---------- */
function SignUpPage() {
  const { nav, login, toast } = useStore();
  const [form, setForm] = useState({ firstName: '', lastName: '', email: '', phone: '', password: '', confirm: '' });
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  const set = (k) => (e) => { setForm(f => ({ ...f, [k]: e.target.value })); setErrors(x => ({ ...x, [k]: '' })); };

  const validate = () => {
    const e = {};
    if (!form.firstName.trim()) e.firstName = 'Required';
    if (!form.lastName.trim()) e.lastName = 'Required';
    if (!form.email) e.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(form.email)) e.email = 'Enter a valid email address';
    if (!form.phone.trim()) e.phone = 'Phone number is required';
    if (!form.password) e.password = 'Password is required';
    else if (form.password.length < 8) e.password = 'At least 8 characters required';
    if (form.confirm !== form.password) e.confirm = "Passwords don't match";
    return e;
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    // Simulated registration — replace with real API call
    setTimeout(() => {
      login({ firstName: form.firstName, lastName: form.lastName, email: form.email, phone: form.phone });
      toast('Account created — welcome!', 'check');
      nav('account');
    }, 1100);
  };

  return (
    <AuthShell mode="signup">
      <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div className="field">
            <label>First name</label>
            <input className={`input${errors.firstName ? ' input-error' : ''}`} value={form.firstName} onChange={set('firstName')} placeholder="Ada" autoComplete="given-name" />
            {errors.firstName && <span className="field-error">{errors.firstName}</span>}
          </div>
          <div className="field">
            <label>Last name</label>
            <input className={`input${errors.lastName ? ' input-error' : ''}`} value={form.lastName} onChange={set('lastName')} placeholder="Okafor" autoComplete="family-name" />
            {errors.lastName && <span className="field-error">{errors.lastName}</span>}
          </div>
        </div>

        <div className="field">
          <label>Email address</label>
          <input className={`input${errors.email ? ' input-error' : ''}`} type="email" value={form.email} onChange={set('email')} placeholder="you@email.com" autoComplete="email" />
          {errors.email && <span className="field-error">{errors.email}</span>}
        </div>

        <div className="field">
          <label>WhatsApp / Phone</label>
          <input className={`input${errors.phone ? ' input-error' : ''}`} type="tel" value={form.phone} onChange={set('phone')} placeholder="+234 801 234 5678" autoComplete="tel" />
          {errors.phone && <span className="field-error">{errors.phone}</span>}
        </div>

        <div className="field">
          <label>Password</label>
          <div style={{ position: 'relative' }}>
            <input
              className={`input${errors.password ? ' input-error' : ''}`}
              type={showPw ? 'text' : 'password'}
              value={form.password} onChange={set('password')}
              placeholder="At least 8 characters"
              autoComplete="new-password"
              style={{ paddingRight: 46 }}
            />
            <button
              type="button"
              onClick={() => setShowPw(s => !s)}
              style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-faint)', display: 'flex' }}
              aria-label={showPw ? 'Hide' : 'Show'}
            >
              {showPw ? <AuthEyeOff /> : <AuthEyeOn />}
            </button>
          </div>
          {errors.password && <span className="field-error">{errors.password}</span>}
          {form.password && !errors.password && (
            <PasswordStrength password={form.password} />
          )}
        </div>

        <div className="field">
          <label>Confirm password</label>
          <input className={`input${errors.confirm ? ' input-error' : ''}`} type="password" value={form.confirm} onChange={set('confirm')} placeholder="••••••••" autoComplete="new-password" />
          {errors.confirm && <span className="field-error">{errors.confirm}</span>}
        </div>

        <p style={{ fontSize: 12.5, color: 'var(--ink-faint)', lineHeight: 1.55 }}>
          By creating an account you agree to our{' '}
          <button type="button" className="link-btn" style={{ fontSize: 12.5 }} onClick={() => nav('policy', { id: 'privacy' })}>Privacy Policy</button>.
        </p>

        <button className="btn btn-gold btn-block" type="submit" disabled={loading} style={{ marginTop: 4 }}>
          {loading ? <AuthSpinner /> : 'Create account'}
        </button>

      </form>
    </AuthShell>
  );
}

/* ---------- Password strength meter ---------- */
function PasswordStrength({ password }) {
  const score = [/.{8,}/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter(r => r.test(password)).length;
  const labels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
  const colors = ['', 'var(--blush)', '#E8A838', 'var(--sage)', 'var(--sage-deep)'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
      <div style={{ display: 'flex', gap: 4, flex: 1 }}>
        {[1,2,3,4].map(i => (
          <div key={i} style={{ flex: 1, height: 3, borderRadius: 4, background: i <= score ? colors[score] : 'var(--line)', transition: 'background .3s' }} />
        ))}
      </div>
      <span style={{ fontSize: 11, color: colors[score], fontWeight: 500, minWidth: 40, textAlign: 'right' }}>{labels[score]}</span>
    </div>
  );
}

/* ---------- Small reusables ---------- */
function AuthDivider() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--ink-faint)', fontSize: 12 }}>
      <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      or
      <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
    </div>
  );
}

function AuthSpinner() {
  return (
    <span style={{
      display: 'inline-block', width: 18, height: 18,
      border: '2px solid rgba(255,255,255,.35)',
      borderTop: '2px solid #fff',
      borderRadius: '50%',
      animation: 'authSpin 0.7s linear infinite',
      verticalAlign: 'middle'
    }} />
  );
}

const AuthEyeOn  = () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" width={18} height={18}><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>;
const AuthEyeOff = () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" width={18} height={18}><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-10-7-10-7a18.45 18.45 0 0 1 5.06-6.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 10 7 10 7a18.5 18.5 0 0 1-2.16 3.19M1 1l22 22"/></svg>;

Object.assign(window, { SignInPage, SignUpPage });
