// Landing page with Sign Up / Log In flows
// Uses window.supabaseClient (CDN singleton from src/supabase.js)

const { useState: useAuthState, useEffect: useAuthEffect, useRef: useAuthRef } = React;

const SUPER_ADMIN_EMAIL = 'owner@perdura.capital'; // set to your actual email

function toSlug(str) {
  return str.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
}

// ─── Root auth page: landing → signup | login ─────────────────────────────────

function AuthPage({ onAuthenticated }) {
  const [mode, setMode] = useAuthState('landing'); // landing | signup | login | forgot

  if (mode === 'signup')  return <SignupForm         onBack={() => setMode('landing')} onAuthenticated={onAuthenticated} />;
  if (mode === 'login')   return <LoginForm          onBack={() => setMode('landing')} onAuthenticated={onAuthenticated} onForgot={() => setMode('forgot')} />;
  if (mode === 'forgot')  return <ForgotPasswordForm onBack={() => setMode('login')} />;
  return <LandingScreen onSignup={() => setMode('signup')} onLogin={() => setMode('login')} />;
}

// ─── Landing hero ─────────────────────────────────────────────────────────────

function LandingScreen({ onSignup, onLogin }) {
  return (
    <div className="pc-land-root">
      <div className="pc-land-bg" />
      <div className="pc-land-grid-lines" />
      <div className="pc-land-inner">
        <div className="pc-land-hero">
          <div className="pc-land-badge">Financial Intelligence Platform</div>
          <div className="pc-land-wordmark">
            <PerduraMark size={36} />
            <span className="pc-land-wordmark-text">PerduraCFO</span>
          </div>
          <div className="pc-land-tagline">
            Your business,<br/><em>in plain English.</em>
          </div>
          <p className="pc-land-description">
            Real-time CFO intelligence for growing businesses — powered by your accounting data.
          </p>
          <ul className="pc-land-bullets">
            {[
              'Connect QuickBooks, Xero, or NetSuite in minutes',
              'Live P&L, cash flow, ratios and KPIs',
              'AI insights that drive smarter decisions',
            ].map(b => (
              <li key={b} className="pc-land-bullet">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ color: "var(--accent)", flexShrink: 0 }}><polyline points="20 6 9 17 4 12"/></svg>
                {b}
              </li>
            ))}
          </ul>
          <div className="pc-land-cta-row">
            <button className="pc-land-btn-primary"  onClick={onLogin}>Sign in</button>
            <button className="pc-land-btn-secondary" onClick={onSignup}>Create account</button>
          </div>
          <div className="pc-land-footer-note">
            Powered by <strong>Perdura Capital LLC</strong> · Enterprise-grade security
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Sign Up ──────────────────────────────────────────────────────────────────

function SignupForm({ onBack, onAuthenticated }) {
  const [email,       setEmail]       = useAuthState('');
  const [password,    setPassword]    = useAuthState('');
  const [company,     setCompany]     = useAuthState('');
  const [subdomain,   setSubdomain]   = useAuthState('');
  const [subStatus,   setSubStatus]   = useAuthState('idle'); // idle | checking | ok | taken
  const [error,       setError]       = useAuthState('');
  const [loading,     setLoading]     = useAuthState(false);
  const [confirmed,   setConfirmed]   = useAuthState(false); // email confirmation pending
  const checkTimer = useAuthRef(null);

  // Auto-suggest subdomain from company name
  useAuthEffect(() => {
    if (company) {
      const slug = toSlug(company);
      setSubdomain(slug);
      checkSubdomain(slug);
    }
  }, [company]);

  function handleSubdomainChange(e) {
    const val = toSlug(e.target.value) || e.target.value.toLowerCase().replace(/\s/g, '-');
    setSubdomain(val);
    clearTimeout(checkTimer.current);
    setSubStatus('idle');
    if (val.length >= 2) {
      checkTimer.current = setTimeout(() => checkSubdomain(val), 400);
    }
  }

  async function checkSubdomain(slug) {
    if (!slug || slug.length < 2) return;
    setSubStatus('checking');
    try {
      const { data } = await window.supabaseClient
        .from('companies')
        .select('id')
        .eq('subdomain', slug)
        .maybeSingle();
      setSubStatus(data ? 'taken' : 'ok');
    } catch {
      setSubStatus('idle');
    }
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    if (password.length < 8) { setError('Password must be at least 8 characters.'); return; }
    if (!subdomain || subdomain.length < 2) { setError('Subdomain must be at least 2 characters.'); return; }
    if (subStatus === 'taken') { setError('That subdomain is already taken.'); return; }

    setLoading(true);
    try {
      const db = window.supabaseClient;

      // 1. Create auth user
      const { data: authData, error: authErr } = await db.auth.signUp({ email, password });
      if (authErr) throw authErr;

      const userId = authData.user?.id;
      if (!userId) {
        // Email confirmation is required — show a friendly screen
        setConfirmed(true);
        return;
      }

      // 2. Insert company
      const { data: co, error: coErr } = await db
        .from('companies')
        .insert({ name: company, subdomain })
        .select()
        .single();
      if (coErr) throw coErr;

      // 3. Insert company_users as Owner / Active
      const { error: cuErr } = await db
        .from('company_users')
        .insert({ user_id: userId, company_id: co.id, role: 'Owner', status: 'Active' });
      if (cuErr) throw cuErr;

      // 4. Redirect to setup wizard on their subdomain
      window.location.href = `https://${subdomain}.cfodash.app/setup`;
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  const subHint = () => {
    if (!subdomain || subdomain.length < 2) return null;
    if (subStatus === 'checking') return <span className="pc-auth-hint neutral">Checking availability…</span>;
    if (subStatus === 'ok')       return <span className="pc-auth-hint ok">✓ Available</span>;
    if (subStatus === 'taken')    return <span className="pc-auth-hint err">Already taken</span>;
    return null;
  };

  if (confirmed) {
    return (
      <div className="pc-land-root">
        <div className="pc-land-bg" />
        <div className="pc-land-grid-lines" />
        <div className="pc-land-inner">
          <div className="pc-auth-card" style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, marginBottom: 16 }}>✉️</div>
            <div className="pc-auth-title">Check your email</div>
            <div className="pc-auth-sub" style={{ marginBottom: 24 }}>
              We sent a confirmation link to <strong style={{ color: 'var(--text)' }}>{email}</strong>.
              Click it to activate your account, then come back and log in.
            </div>
            <button className="pc-auth-submit" style={{ marginTop: 0 }} onClick={onBack}>
              Back to log in
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pc-land-root">
      <div className="pc-land-bg" />
      <div className="pc-land-grid-lines" />
      <div className="pc-land-inner">
        <div className="pc-auth-card">
          <div className="pc-auth-card-logo">
            <PerduraMark size={24} />
            <span className="pc-auth-card-brand">PerduraCFO</span>
          </div>
          <div className="pc-auth-title">Create your account</div>
          <div className="pc-auth-sub">Get set up in under 2 minutes.</div>

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

          <form onSubmit={handleSubmit}>
            <div className="pc-auth-field">
              <label className="pc-auth-label">Email</label>
              <input className="pc-auth-input" type="email" required placeholder="you@company.com"
                value={email} onChange={e => setEmail(e.target.value)} />
            </div>
            <div className="pc-auth-field">
              <label className="pc-auth-label">Password</label>
              <input className="pc-auth-input" type="password" required placeholder="8+ characters"
                value={password} onChange={e => setPassword(e.target.value)} />
            </div>
            <div className="pc-auth-field">
              <label className="pc-auth-label">Company name</label>
              <input className="pc-auth-input" type="text" required placeholder="Acme Inc."
                value={company} onChange={e => setCompany(e.target.value)} />
            </div>
            <div className="pc-auth-field">
              <label className="pc-auth-label">Subdomain</label>
              <div className={`pc-auth-subdomain-row${subStatus === 'taken' ? ' error' : ''}`}>
                <span className="pc-auth-subdomain-prefix">https://</span>
                <input
                  className="pc-auth-subdomain-input"
                  type="text"
                  required
                  placeholder="acme"
                  value={subdomain}
                  onChange={handleSubdomainChange}
                />
                <span className="pc-auth-subdomain-suffix">.cfodash.app</span>
              </div>
              {subHint()}
            </div>
            <button className="pc-auth-submit" type="submit"
              disabled={loading || subStatus === 'taken' || subStatus === 'checking'}>
              {loading ? 'Creating account…' : 'Create account'}
            </button>
          </form>

          <div className="pc-auth-toggle">
            Already have an account?{" "}
            <button onClick={onBack}>Sign in</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Log In ───────────────────────────────────────────────────────────────────

function LoginForm({ onBack, onAuthenticated, onForgot }) {
  const [email,    setEmail]    = useAuthState('');
  const [password, setPassword] = useAuthState('');
  const [error,    setError]    = useAuthState('');
  const [loading,  setLoading]  = useAuthState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const db = window.supabaseClient;

      const { data, error: authErr } = await db.auth.signInWithPassword({ email, password });
      if (authErr) throw authErr;

      const userId = data.user.id;

      // Super-admin bypass — check app_metadata claim
      const isSuperAdmin = data.user?.app_metadata?.super_admin === true;
      if (isSuperAdmin) {
        const SD = window.PerduraSubdomain || { type: "root" };
        // On cfodash.app subdomains: redirect to admin subdomain if not already there
        if (SD.type === "subdomain" || SD.type === "app") {
          window.location.replace("https://admin.cfodash.app");
          return;
        }
        // On root, admin, localhost, or any preview URL: just sign in directly
        onAuthenticated(data.user);
        return;
      }

      // Look up company membership
      const { data: membership } = await db
        .from('company_users')
        .select('company_id, companies(subdomain)')
        .eq('user_id', userId)
        .eq('status', 'Active')
        .maybeSingle();

      if (membership?.companies?.subdomain) {
        const SD = window.PerduraSubdomain || { type: "root" };
        // Already on the correct subdomain — hand off without redirect
        if (SD.type === "subdomain" && SD.slug === membership.companies.subdomain) {
          onAuthenticated(data.user);
        } else {
          window.location.replace(`https://${membership.companies.subdomain}.cfodash.app`);
        }
      } else {
        // No company yet — hand off to app.jsx to show wizard
        onAuthenticated(data.user);
      }
    } catch (err) {
      setError(err.message || 'Invalid email or password.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="pc-land-root">
      <div className="pc-land-bg" />
      <div className="pc-land-grid-lines" />
      <div className="pc-land-inner">
        <div className="pc-auth-card">
          <div className="pc-auth-card-logo">
            <PerduraMark size={24} />
            <span className="pc-auth-card-brand">PerduraCFO</span>
          </div>
          <div className="pc-auth-title">Welcome back</div>
          <div className="pc-auth-sub">Sign in to your financial dashboard.</div>

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

          <form onSubmit={handleSubmit}>
            <div className="pc-auth-field">
              <label className="pc-auth-label">Email</label>
              <input className="pc-auth-input" type="email" required placeholder="you@company.com"
                value={email} onChange={e => setEmail(e.target.value)} />
            </div>
            <div className="pc-auth-field">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
                <label className="pc-auth-label" style={{ margin: 0 }}>Password</label>
                <button type="button" className="pc-auth-link-btn" onClick={onForgot}>Forgot password?</button>
              </div>
              <input className="pc-auth-input" type="password" required placeholder="Password"
                value={password} onChange={e => setPassword(e.target.value)} />
            </div>
            <button className="pc-auth-submit" type="submit" disabled={loading}>
              {loading ? 'Signing in…' : 'Sign in'}
            </button>
          </form>

          <div className="pc-auth-toggle">
            Don't have an account?{" "}
            <button onClick={onBack}>Create one</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Set New Password (after clicking email reset link) ───────────────────────

function ResetPasswordForm({ onDone }) {
  const [password,  setPassword]  = useAuthState('');
  const [confirm,   setConfirm]   = useAuthState('');
  const [error,     setError]     = useAuthState('');
  const [loading,   setLoading]   = useAuthState(false);
  const [done,      setDone]      = useAuthState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    if (password.length < 8) { setError('Password must be at least 8 characters.'); return; }
    if (password !== confirm) { setError('Passwords do not match.'); return; }
    setLoading(true);
    try {
      const { error: updateErr } = await window.supabaseClient.auth.updateUser({ password });
      if (updateErr) throw updateErr;
      setDone(true);
      setTimeout(() => onDone(), 2000);
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="pc-land-root">
      <div className="pc-land-bg" />
      <div className="pc-land-grid-lines" />
      <div className="pc-land-inner">
        <div className="pc-auth-card">
          {done ? (
            <div style={{ textAlign: 'center', padding: '16px 0' }}>
              <div style={{ fontSize: 32, marginBottom: 16 }}>✓</div>
              <div className="pc-auth-title">Password updated</div>
              <div className="pc-auth-sub">Taking you to your dashboard…</div>
            </div>
          ) : (
            <>
              <div className="pc-auth-title">Set new password</div>
              <div className="pc-auth-sub">Choose a strong password for your account.</div>

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

              <form onSubmit={handleSubmit}>
                <div className="pc-auth-field">
                  <label className="pc-auth-label">New password</label>
                  <input className="pc-auth-input" type="password" required placeholder="8+ characters"
                    value={password} onChange={e => setPassword(e.target.value)} />
                </div>
                <div className="pc-auth-field">
                  <label className="pc-auth-label">Confirm password</label>
                  <input className="pc-auth-input" type="password" required placeholder="Re-enter password"
                    value={confirm} onChange={e => setConfirm(e.target.value)} />
                </div>
                <button className="pc-auth-submit" type="submit" disabled={loading}>
                  {loading ? 'Saving…' : 'Set new password'}
                </button>
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Forgot Password ──────────────────────────────────────────────────────────

function ForgotPasswordForm({ onBack }) {
  const [email,   setEmail]   = useAuthState('');
  const [error,   setError]   = useAuthState('');
  const [loading, setLoading] = useAuthState(false);
  const [sent,    setSent]    = useAuthState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const { error: resetErr } = await window.supabaseClient.auth.resetPasswordForEmail(email, {
        redirectTo: window.location.origin + '/app.html',
      });
      if (resetErr) throw resetErr;
      setSent(true);
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="pc-land-root">
      <div className="pc-land-bg" />
      <div className="pc-land-grid-lines" />
      <div className="pc-land-inner">
        <div className="pc-auth-card">
          <button className="pc-auth-back" onClick={onBack}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 2L4 7l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            Back to sign in
          </button>

          {sent ? (
            <div style={{ textAlign: 'center', padding: '16px 0' }}>
              <div style={{ fontSize: 32, marginBottom: 16 }}>✉️</div>
              <div className="pc-auth-title">Check your inbox</div>
              <div className="pc-auth-sub" style={{ marginBottom: 24 }}>
                We sent a password reset link to <strong style={{ color: 'var(--text)' }}>{email}</strong>.
                Check your spam folder if it doesn't arrive within a minute.
              </div>
              <button className="pc-auth-submit" style={{ marginTop: 0 }} onClick={onBack}>
                Back to sign in
              </button>
            </div>
          ) : (
            <>
              <div className="pc-auth-title">Reset your password</div>
              <div className="pc-auth-sub">Enter your email and we'll send you a reset link.</div>

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

              <form onSubmit={handleSubmit}>
                <div className="pc-auth-field">
                  <label className="pc-auth-label">Email</label>
                  <input className="pc-auth-input" type="email" required placeholder="you@company.com"
                    value={email} onChange={e => setEmail(e.target.value)} />
                </div>
                <button className="pc-auth-submit" type="submit" disabled={loading}>
                  {loading ? 'Sending…' : 'Send reset link'}
                </button>
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
