// Bleu SmartDER — Authentication layer
// Real Supabase auth wrapped around the static prototype.
// AuthGate decides whether to render the sign-in/sign-up screens or the
// underlying <App />. Profile (role + tenant_id) is derived from the
// signed-in user's email via BLEU_CONFIG mappings in index.html.

const _sb = window.supabase.createClient(
  window.BLEU_CONFIG.SUPABASE_URL,
  window.BLEU_CONFIG.SUPABASE_ANON_KEY
);
window.sb = _sb;

const AuthContext = React.createContext(null);
function useAuth() { return React.useContext(AuthContext); }

function deriveProfile(user) {
  if (!user) return null;
  const email = (user.email || '').toLowerCase();
  const cfg = window.BLEU_CONFIG;
  const isAdmin = cfg.ADMIN_EMAILS.includes(email);
  const mappedTenant = cfg.TENANT_EMAIL_MAP[email] || null;
  return {
    email,
    name: user.user_metadata?.full_name || email.split('@')[0],
    role: isAdmin ? 'admin' : 'tenant',
    tenantId: mappedTenant || 't-ahmed', // unmapped signups view Ahmed's demo data
    isDemoMapped: isAdmin || mappedTenant != null,
  };
}

// ============= Auth screens =============

function AuthShell({ children, mode, onSwitch }) {
  return (
    <div className="auth-shell">
      <div className="auth-bg" aria-hidden="true" />
      <div className="auth-card">
        <div className="auth-brand">
          <img src="assets/bleu-logo.png" alt="Bleu SmartDER" />
          <div>
            <div className="auth-brand-name"><span>Bleu</span> SmartDER</div>
            <div className="auth-brand-sub">Low-bandwidth DER management platform</div>
          </div>
        </div>

        <div className="auth-tabs">
          <button data-on={mode === 'signin'} onClick={() => mode !== 'signin' && onSwitch('signin')}>Sign in</button>
          <button data-on={mode === 'signup'} onClick={() => mode !== 'signup' && onSwitch('signup')}>Create account</button>
        </div>

        {children}

        <div className="auth-disclaimer">
          Demo environment · simulated productive-use DER data. Live deployment
          will connect to real inverter, BMS and smart-meter telemetry.
        </div>
      </div>
    </div>
  );
}

function SignInScreen({ onSwitch, onSubmit, error, submitting }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');

  function handleSubmit(e) {
    e.preventDefault();
    if (!email || !password) return;
    onSubmit(email.trim().toLowerCase(), password);
  }

  return (
    <AuthShell mode="signin" onSwitch={onSwitch}>
      <form className="auth-form" onSubmit={handleSubmit}>
        <label className="auth-field">
          <span className="auth-lbl">Email</span>
          <input type="email" autoComplete="username"
            value={email} onChange={e => setEmail(e.target.value)}
            placeholder="you@example.com" required />
        </label>
        <label className="auth-field">
          <span className="auth-lbl">Password</span>
          <input type="password" autoComplete="current-password"
            value={password} onChange={e => setPassword(e.target.value)}
            placeholder="••••••••" required minLength={8} />
        </label>

        {error && <div className="auth-error">{error}</div>}

        <button type="submit" className="auth-submit" disabled={submitting}>
          {submitting ? 'Signing in…' : 'Sign in'}
        </button>
      </form>

      <div className="auth-footnote">
        New here? <a onClick={() => onSwitch('signup')}>Create a tenant account</a>.
      </div>
    </AuthShell>
  );
}

function SignUpScreen({ onSwitch, onSubmit, error, submitting, success }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [orgName, setOrgName] = React.useState('');
  const [tenantType, setTenantType] = React.useState('farm');

  function handleSubmit(e) {
    e.preventDefault();
    if (!email || !password) return;
    onSubmit({
      email: email.trim().toLowerCase(),
      password,
      metadata: { full_name: name, org_name: orgName, tenant_type: tenantType },
    });
  }

  if (success) {
    return (
      <AuthShell mode="signup" onSwitch={onSwitch}>
        <div className="auth-success">
          <div className="auth-success-ico">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
          </div>
          <h3>Tenant account created</h3>
          <p>
            We sent a confirmation link to <strong>{success.email}</strong>.
            Once confirmed, an operator will commission your devices and your
            real telemetry will replace the demo data.
          </p>
          <button className="auth-submit" onClick={() => onSwitch('signin')}>Back to sign in</button>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell mode="signup" onSwitch={onSwitch}>
      <form className="auth-form" onSubmit={handleSubmit}>
        <label className="auth-field">
          <span className="auth-lbl">Full name</span>
          <input type="text" autoComplete="name"
            value={name} onChange={e => setName(e.target.value)}
            placeholder="Your name" required />
        </label>
        <label className="auth-field">
          <span className="auth-lbl">Organisation</span>
          <input type="text"
            value={orgName} onChange={e => setOrgName(e.target.value)}
            placeholder="Farm, cooperative, cold storage…" required />
        </label>
        <label className="auth-field">
          <span className="auth-lbl">Tenant type</span>
          <select value={tenantType} onChange={e => setTenantType(e.target.value)}>
            <option value="farm">Farm / irrigation</option>
            <option value="cold_storage">Cold storage / packhouse</option>
            <option value="cooperative">Cooperative energy hub</option>
            <option value="agro_processing">Agro-processing</option>
            <option value="other">Other productive-use site</option>
          </select>
        </label>
        <label className="auth-field">
          <span className="auth-lbl">Email</span>
          <input type="email" autoComplete="email"
            value={email} onChange={e => setEmail(e.target.value)}
            placeholder="you@example.com" required />
        </label>
        <label className="auth-field">
          <span className="auth-lbl">Password</span>
          <input type="password" autoComplete="new-password"
            value={password} onChange={e => setPassword(e.target.value)}
            placeholder="At least 8 characters" required minLength={8} />
        </label>

        {error && <div className="auth-error">{error}</div>}

        <button type="submit" className="auth-submit" disabled={submitting}>
          {submitting ? 'Creating account…' : 'Create tenant account'}
        </button>
      </form>

      <div className="auth-footnote">
        By creating an account you'll see the Bleu SmartDER MVP populated with
        demo data while an operator commissions your devices.
        Already registered? <a onClick={() => onSwitch('signin')}>Sign in</a>.
      </div>
    </AuthShell>
  );
}

// ============= AuthGate =============

function AuthGate({ children }) {
  const [loading, setLoading] = React.useState(true);
  const [session, setSession] = React.useState(null);
  const [mode, setMode] = React.useState('signin');
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [signupSuccess, setSignupSuccess] = React.useState(null);

  React.useEffect(() => {
    _sb.auth.getSession().then(({ data }) => {
      setSession(data.session);
      setLoading(false);
    });
    const { data: sub } = _sb.auth.onAuthStateChange((_evt, s) => {
      setSession(s);
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  async function signIn(email, password) {
    setSubmitting(true); setError('');
    const { error } = await _sb.auth.signInWithPassword({ email, password });
    setSubmitting(false);
    if (error) setError(friendlyAuthError(error.message));
  }

  async function signUp({ email, password, metadata }) {
    setSubmitting(true); setError('');
    const { data, error } = await _sb.auth.signUp({
      email, password,
      options: { data: metadata },
    });
    setSubmitting(false);
    if (error) { setError(friendlyAuthError(error.message)); return; }
    if (data.session) {
      // Email confirmation is OFF — user is already signed in
      setSignupSuccess(null);
    } else {
      // Email confirmation is ON
      setSignupSuccess({ email });
    }
  }

  async function signOut() {
    await _sb.auth.signOut();
    setMode('signin');
  }
  window.bleuSignOut = signOut;

  if (loading) {
    return (
      <div className="auth-shell">
        <div className="auth-bg" />
        <div className="auth-loader">Loading…</div>
      </div>
    );
  }

  if (!session) {
    return mode === 'signup'
      ? <SignUpScreen
          onSwitch={(m) => { setMode(m || 'signin'); setError(''); setSignupSuccess(null); }}
          onSubmit={signUp} error={error} submitting={submitting} success={signupSuccess} />
      : <SignInScreen
          onSwitch={(m) => { setMode(m || 'signup'); setError(''); }}
          onSubmit={signIn}
          error={error} submitting={submitting} />;
  }

  const profile = deriveProfile(session.user);
  return (
    <AuthContext.Provider value={{ session, user: session.user, profile, signOut }}>
      {children}
    </AuthContext.Provider>
  );
}

function friendlyAuthError(msg) {
  if (!msg) return 'Something went wrong. Please try again.';
  const m = msg.toLowerCase();
  if (m.includes('invalid login credentials')) return 'Wrong email or password.';
  if (m.includes('email not confirmed')) return 'Please confirm your email first (check your inbox).';
  if (m.includes('user already registered')) return 'That email is already registered. Try signing in instead.';
  if (m.includes('password should be at least')) return 'Password must be at least 8 characters.';
  return msg;
}

Object.assign(window, { AuthGate, useAuth });
