/* ============================================================
   ELECTROMED — Login / Sign-in page
   Full-screen branded auth gate. On submit calls onLogin().
   ============================================================ */
function Login({ onLogin }) {
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [show, setShow] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  const submit = async (e) => {
    e && e.preventDefault();
    setBusy(true);
    setError('');

    try {
      const response = await api.login(email, pw);
      api.setToken(response.token, response.user);
      onLogin({
        email: response.user.email,
        name:  response.user.name,
        branch: response.user.branch_id || 'All',
        role:  response.user.role,
        token: response.token,
        user:  response.user,
      });
    } catch (err) {
      setError(err.message || 'Login failed. Please try again.');
      setBusy(false);
    }
  };

  return (
    <div className="login-wrap">
      {/* Brand panel */}
      <div className="login-brand">
        <div className="login-brand-inner">
          <div className="row" style={{ gap: 13, alignItems: 'center' }}>
            <div style={{ width: 46, height: 46, borderRadius: 13, background: 'rgba(255,255,255,.1)', display: 'grid', placeItems: 'center' }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.3" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 19, color: '#fff', letterSpacing: '-.01em' }}>Electromed Corporation</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.6)', letterSpacing: '.14em', fontWeight: 700, marginTop: 2 }}>RESPIRATORY · SLEEP CARE</div>
            </div>
          </div>

          <div style={{ marginTop: 'auto' }}>
            <h1 style={{ color: '#fff', fontSize: 34, fontWeight: 800, lineHeight: 1.12, letterSpacing: '-.02em', textWrap: 'balance' }}>
              Sales, rentals &amp; service — one platform.
            </h1>
            <p style={{ color: 'rgba(255,255,255,.66)', fontSize: 15, marginTop: 14, lineHeight: 1.6, maxWidth: 380 }}>
              Quotations, GST invoicing, rental agreements, workshop bills and accounting reports across all branches.
            </p>
            <div style={{ display: 'grid', gap: 12, marginTop: 28 }}>
              {[['Multi-company GST & Non-GST invoicing', Icons.receipt], ['Consolidated rental agreements & deposits', Icons.rental], ['Accounting reports, printable to PDF', Icons.chart]].map(([t, I], ix) => (
                <div key={ix} className="row" style={{ gap: 11 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: 'rgba(169,236,110,.14)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><I size={16} style={{ color: 'var(--lime)' }} /></span>
                  <span style={{ color: 'rgba(255,255,255,.82)', fontSize: 13.5, fontWeight: 500 }}>{t}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="tiny" style={{ color: 'rgba(255,255,255,.4)', marginTop: 'auto', paddingTop: 28 }}>
            Multi-branch operations across Pakistan
          </div>
        </div>
      </div>

      {/* Form panel */}
      <div className="login-form-panel">
        <form className="login-card" onSubmit={submit}>
          <div style={{ marginBottom: 26 }}>
            <div style={{ fontWeight: 800, fontSize: 24, letterSpacing: '-.02em' }}>Sign in</div>
            <div className="tiny muted" style={{ marginTop: 5 }}>Welcome back. Enter your credentials to continue.</div>
          </div>

          <label className="fld" style={{ marginBottom: 14 }}><span>Work Email</span>
            <input className="input-block" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@electromed.pk" autoComplete="username" />
          </label>

          <label className="fld" style={{ marginBottom: 14 }}><span>Password</span>
            <div style={{ position: 'relative' }}>
              <input className="input-block" type={show ? 'text' : 'password'} value={pw} onChange={(e) => setPw(e.target.value)} style={{ paddingRight: 64 }} autoComplete="current-password" />
              <button type="button" className="login-eye" onClick={() => setShow((v) => !v)}>{show ? 'Hide' : 'Show'}</button>
            </div>
          </label>

          {error &&<div style={{ background: 'rgba(255,59,48,.1)', color: '#f53c3c', padding: '10px 12px', borderRadius: 8, fontSize: 13, marginBottom: 18 }}>{error}</div>}

          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 20 }}>
            <label className="row" style={{ gap: 8, cursor: 'pointer', fontSize: 13 }}>
              <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: 'var(--lime-700)' }} />
              <span className="muted">Keep me signed in</span>
            </label>
            <a href="#" className="tiny" style={{ color: 'var(--lime-700)', fontWeight: 700, textDecoration: 'none' }} onClick={(e) => e.preventDefault()}>Forgot password?</a>
          </div>

          <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '13px', fontSize: 15 }} disabled={busy}>
            {busy ? 'Signing in…' : <>Sign in <Icons.chevR size={16} stroke={2.5} /></>}
          </button>

        </form>

        <div className="tiny muted" style={{ textAlign: 'center', marginTop: 22 }}>© 2026 Electromed Corporation · v1.0</div>
      </div>
    </div>
  );
}

window.Login = Login;

/* ============================================================
   Accept Invite — shown when the user visits /accept-invite?token=xxx
   ============================================================ */
function AcceptInvite({ token, onLogin }) {
  const [invite,  setInvite]  = useState(null);
  const [loading, setLoading] = useState(true);
  const [tokenErr, setTokenErr] = useState('');
  const [name,    setName]    = useState('');
  const [pw,      setPw]      = useState('');
  const [pw2,     setPw2]     = useState('');
  const [show,    setShow]    = useState(false);
  const [busy,    setBusy]    = useState(false);
  const [err,     setErr]     = useState('');

  useEffect(() => {
    api.getInviteByToken(token)
      .then(r  => { setInvite(r.invite); setLoading(false); })
      .catch(e => { setTokenErr(e.message || 'Invalid invite link'); setLoading(false); });
  }, [token]);

  const submit = async (e) => {
    e && e.preventDefault();
    if (!name.trim())  { setErr('Full name is required'); return; }
    if (pw.length < 6) { setErr('Password must be at least 6 characters'); return; }
    if (pw !== pw2)    { setErr('Passwords do not match'); return; }
    setBusy(true); setErr('');
    try {
      const res = await api.acceptInvite(token, { name: name.trim(), password: pw });
      api.setToken(res.token, res.user);
      // Full reload to / — token is in localStorage, app boots authenticated
      window.location.replace('/');
    } catch (e) {
      setErr(e.message || 'Failed to create account');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="login-wrap">
      <div className="login-brand">
        <div className="login-brand-inner">
          <div className="row" style={{ gap: 13, alignItems: 'center' }}>
            <div style={{ width: 46, height: 46, borderRadius: 13, background: 'rgba(255,255,255,.1)', display: 'grid', placeItems: 'center' }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.3" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 19, color: '#fff' }}>Electromed Corporation</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.6)', letterSpacing: '.14em', fontWeight: 700, marginTop: 2 }}>RESPIRATORY · SLEEP CARE</div>
            </div>
          </div>
          <div style={{ marginTop: 'auto' }}>
            <h1 style={{ color: '#fff', fontSize: 30, fontWeight: 800, lineHeight: 1.15, letterSpacing: '-.02em' }}>You've been invited to join the team.</h1>
            <p style={{ color: 'rgba(255,255,255,.66)', fontSize: 14.5, marginTop: 14, lineHeight: 1.6, maxWidth: 340 }}>Set up your password to activate your account and get access to the Electromed platform.</p>
          </div>
          <div className="tiny" style={{ color: 'rgba(255,255,255,.4)', marginTop: 'auto', paddingTop: 28 }}>Multi-branch operations across Pakistan</div>
        </div>
      </div>

      <div className="login-form-panel">
        {loading ? (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', paddingTop: 80 }}>Validating invite…</div>
        ) : tokenErr ? (
          <div className="login-card">
            <div style={{ fontWeight: 800, fontSize: 22, marginBottom: 12 }}>Invalid Invite</div>
            <div style={{ background: 'rgba(255,59,48,.1)', color: '#f53c3c', padding: '13px 15px', borderRadius: 10, lineHeight: 1.5 }}>{tokenErr}</div>
            <button type="button" className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', marginTop: 18, padding: 12 }} onClick={() => { window.history.replaceState({}, '', '/'); window.location.reload(); }}>← Back to Sign In</button>
          </div>
        ) : (
          <form className="login-card" onSubmit={submit}>
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontWeight: 800, fontSize: 24, letterSpacing: '-.02em' }}>Set Up Your Account</div>
              <div className="tiny muted" style={{ marginTop: 5 }}>
                Joining as <b>{invite && invite.role}</b> · <span className="mono" style={{ fontSize: 12 }}>{invite && invite.email}</span>
              </div>
            </div>

            <label className="fld" style={{ marginBottom: 14 }}><span>Full Name</span>
              <input className="input-block" value={name} onChange={e => setName(e.target.value)} placeholder="Your full name" autoFocus autoComplete="name" />
            </label>
            <label className="fld" style={{ marginBottom: 14 }}><span>Create Password</span>
              <div style={{ position: 'relative' }}>
                <input className="input-block" type={show ? 'text' : 'password'} value={pw} onChange={e => setPw(e.target.value)} placeholder="Minimum 6 characters" style={{ paddingRight: 64 }} autoComplete="new-password" />
                <button type="button" className="login-eye" onClick={() => setShow(v => !v)}>{show ? 'Hide' : 'Show'}</button>
              </div>
            </label>
            <label className="fld" style={{ marginBottom: 20 }}><span>Confirm Password</span>
              <input className="input-block" type={show ? 'text' : 'password'} value={pw2} onChange={e => setPw2(e.target.value)} placeholder="Repeat password" autoComplete="new-password" />
            </label>

            {err && <div style={{ background: 'rgba(255,59,48,.1)', color: '#f53c3c', padding: '10px 12px', borderRadius: 8, fontSize: 13, marginBottom: 16 }}>{err}</div>}

            <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '13px', fontSize: 15 }} disabled={busy}>
              {busy ? 'Creating account…' : 'Create Account & Sign In'}
            </button>

            <div className="login-demo" style={{ marginTop: 16 }}>
              <Icons.shield size={14} style={{ color: 'var(--ink-3)' }} />
              <span className="tiny muted">Your account will be created with the role assigned by your admin.</span>
            </div>
          </form>
        )}
        <div className="tiny muted" style={{ textAlign: 'center', marginTop: 22 }}>© 2026 Electromed Corporation · v1.0</div>
      </div>
    </div>
  );
}
window.AcceptInvite = AcceptInvite;
