// Login.jsx
// Cloudflare's official test sitekey — always passes. Replace with your real
// sitekey from https://dash.cloudflare.com/?to=/:account/turnstile (free)
// before going to production.
const TURNSTILE_SITEKEY = '1x00000000000000000000AA';

function CloudflareTurnstile({ onVerify, onExpire }) {
  const ref = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  React.useEffect(() => {
    let cancelled = false;

    const ensureScript = () => new Promise((resolve) => {
      if (window.turnstile) return resolve();
      const existing = document.querySelector('script[data-turnstile]');
      if (existing) {
        existing.addEventListener('load', resolve, { once: true });
        return;
      }
      const s = document.createElement('script');
      s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
      s.async = true;
      s.defer = true;
      s.dataset.turnstile = '1';
      s.addEventListener('load', resolve, { once: true });
      document.head.appendChild(s);
    });

    ensureScript().then(() => {
      if (cancelled || !ref.current || !window.turnstile) return;
      widgetIdRef.current = window.turnstile.render(ref.current, {
        sitekey: TURNSTILE_SITEKEY,
        theme: 'light',
        callback: (token) => onVerify && onVerify(token),
        'expired-callback': () => onExpire && onExpire(),
        'error-callback': () => onExpire && onExpire(),
      });
    });

    return () => {
      cancelled = true;
      if (widgetIdRef.current && window.turnstile) {
        try { window.turnstile.remove(widgetIdRef.current); } catch (e) {}
      }
    };
  }, []);

  return <div ref={ref} style={{marginBottom: 20, minHeight: 65}}/>;
}

// Email → role mapping. In production this is a server lookup against the
// directory of registered users; the role + landing page are returned with the
// auth token. Here we mock that with a static map for the prototype.
const EMAIL_ROLE_MAP = {
  'admin@powleecrane.com':       { role: 'Admin',      landing: 'dashboard',     name: 'Wei Ming Lim',   initials: 'WM', password: 'PowLee-Admin#26' },
  'dispatch@powleecrane.com':    { role: 'Operation',  landing: 'bookings',      name: 'Sarah Tan',       initials: 'ST', password: 'PowLee-Dispatch#26' },
  'razak@powleecrane.com':       { role: 'Operator',   landing: 'mobile',        name: 'Razak Hassan',   initials: 'RH', password: 'PowLee-Razak#26' },
  'faizal@powleecrane.com':      { role: 'Rigger',     landing: 'mobile',        name: 'Ahmad Faizal',    initials: 'AF', password: 'PowLee-Faizal#26' },
  'workshop@powleecrane.com':    { role: 'Mechanic',   landing: 'rm',            name: 'Awei',  initials: 'AW', password: 'PowLee-Workshop#26' },
  'finance@powleecrane.com':     { role: 'Finance',    landing: 'export',        name: 'Aminah Yusof',    initials: 'AY', password: 'PowLee-Finance#26' },
  'mgmt@powleecrane.com':        { role: 'Management', landing: 'analytics',     name: 'David Ng',        initials: 'DN', password: 'PowLee-Mgmt#26' },
};

function LoginPage({ onLogin }) {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [show, setShow] = React.useState(false);
  const [cfToken, setCfToken] = React.useState(null);
  const [error, setError] = React.useState(null);
  const cfChecked = !!cfToken;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!cfChecked) return;
    const acct = EMAIL_ROLE_MAP[email.trim().toLowerCase()];
    if (!acct) {
      setError('No account matches that email. Contact admin@powleecrane.com to be added.');
      return;
    }
    if (pass !== acct.password) {
      setError('Incorrect password for that account. Check your credentials and try again.');
      return;
    }
    setError(null);
    onLogin(acct);
  };

  return (
    <div className="login">
      <div className="login__hero">
        <div className="login__brand">
          <img src="assets/powlee-logo.png" alt="Pow Lee" className="login__brand-logo"/>
          <div className="login__brand-name">
            POW LEE CRANE &amp; ENGINEERING SDN. BHD.
          </div>
        </div>

        <div className="login__hero-content">
          <div className="login__eyebrow">Our Vision</div>
          <h1>Dispatch a crane.<br/>Track every lift.</h1>
          <p style={{fontStyle: 'italic', fontSize: 17, color: 'rgba(255,255,255,0.85)', borderLeft: '2px solid var(--color-yellow)', paddingLeft: 18, maxWidth: 460}}>“To be the most trusted mobile crane solutions provider in Southern Malaysia.”</p>
        </div>

        <div className="login__stats">
          <div>
            <div className="login__stat-num">100%</div>
            <div className="login__stat-label">Certified Crews</div>
          </div>
          <div>
            <div className="login__stat-num">20+</div>
            <div className="login__stat-label">Years In JB</div>
          </div>
          <div>
            <div className="login__stat-num">24/7</div>
            <div className="login__stat-label">Dispatch</div>
          </div>
        </div>
      </div>

      <div className="login__form-wrap">
        <form className="login__form" onSubmit={handleSubmit}>
          <h2>Sign in</h2>
          <div className="login__form-sub">Sign in with your Pow Lee email — you'll be taken to the right workspace automatically based on your role.</div>

          <div className="field" style={{marginBottom: 16, marginTop: 24}}>
            <label>Email</label>
            <div style={{position: 'relative'}}>
              <Mail size={16} style={{position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)'}}/>
              <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); setError(null); }} style={{paddingLeft: 38, width: '100%'}} placeholder="you@powleecrane.com"/>
            </div>
          </div>

          <div className="field" style={{marginBottom: 8}}>
            <label>Password</label>
            <div style={{position: 'relative'}}>
              <Lock size={16} style={{position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)'}}/>
              <input type={show ? 'text' : 'password'} value={pass} onChange={(e) => { setPass(e.target.value); setError(null); }} style={{paddingLeft: 38, paddingRight: 60, width: '100%'}} placeholder="Enter your password"/>
              <button type="button" onClick={() => setShow(!show)} style={{position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', fontSize: 12, fontWeight: 600, color: 'var(--color-navy)', padding: '4px 8px'}}>
                {show ? 'Hide' : 'Show'}
              </button>
            </div>
          </div>

          <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '8px 0 24px', fontSize: 13}}>
            <label style={{display: 'flex', alignItems: 'center', gap: 6, color: 'var(--color-grey-700)'}}>
              <input type="checkbox" defaultChecked/> Stay signed in
            </label>
            <a href="#" style={{fontSize: 13}}>Forgot password?</a>
          </div>

          <CloudflareTurnstile onVerify={(t) => setCfToken(t)} onExpire={() => setCfToken(null)}/>

          {error ? (
            <div style={{padding: '10px 12px', background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.3)', borderRadius: 8, color: 'var(--color-danger)', fontSize: 13, marginBottom: 16, display: 'flex', gap: 8, alignItems: 'flex-start'}}>
              <AlertTriangle size={16} style={{flexShrink: 0, marginTop: 1}}/> <span>{error}</span>
            </div>
          ) : null}

          <button type="submit" className="btn btn--primary btn--lg btn--block"
            disabled={!cfChecked}
            style={!cfChecked ? {opacity: 0.5, cursor: 'not-allowed'} : {}}>
            Sign In
            <ChevRight size={18}/>
          </button>

          <div style={{textAlign: 'center', marginTop: 24, fontSize: 12, color: 'var(--color-grey-500)'}}>
            v1.0 prototype · PWA-ready · Add to home screen for fastest access
          </div>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage });
