/* ============================================================
   P&L App (Lite) · the screens before the app: login, forgot password,
   set a password (from the invite or reset email), agree to the terms,
   and "not linked to a company yet". The demo's login look (green).

   The login is the app's gate: the database answers only a logged-in person,
   and nothing asks for data before it succeeds (app.jsx, startSession in data.jsx).
   The same error is shown for a wrong password and an unknown email, on purpose:
   nobody can use the login to find out who has an account.
   "by Retiply" shows on these screens only (brief 65: the app should feel like theirs).
   ============================================================ */

/* The white card every one of these screens sits in. */
function AuthCard({ title, sub, children }) {
  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-4 py-10" style={{ background: 'var(--bg)' }}>
      <div className="w-full max-w-[400px] rounded-2xl shadow-card p-7 sm:p-9" style={{ background: 'var(--surface)', border: '1px solid var(--line)' }}>
        <div className="flex flex-col items-center text-center mb-7">
          <span className="inline-flex items-center justify-center w-11 h-11 rounded-[13px] mb-3" style={{ background: 'var(--lime)', color: 'var(--sidebar)' }}>
            <Icon name="chart" size={22} />
          </span>
          <h1 className="font-display font-700 text-[20px] text-ink">{title}</h1>
          {sub && <p className="text-[13px] text-muted mt-1.5 break-words">{sub}</p>}
        </div>
        {children}
      </div>
      <div className="mt-5 text-[12px] text-muted text-center">
        P&amp;L App by Retiply · <a href="privacy.html" className="hover:text-ink underline-offset-2 hover:underline">Privacy</a> · <a href="terms.html" className="hover:text-ink underline-offset-2 hover:underline">Terms</a>
      </div>
    </div>
  );
}

/* A password field with an eye button to show or hide what is typed. The dots use the system
   font, bigger and spaced out (the app's font draws them tiny). */
function PasswordInput({ value, onChange, autoComplete, autoFocus, placeholder }) {
  const [show, setShow] = useState(false);
  return (
    <div className="relative">
      <Input type={show ? 'text' : 'password'} value={value} onChange={onChange} autoComplete={autoComplete} autoFocus={autoFocus}
             placeholder={placeholder} className="pr-11"
             style={show ? undefined : { fontFamily: 'system-ui, -apple-system, sans-serif', fontSize: '18px', letterSpacing: '0.12em' }} />
      <button type="button" onClick={() => setShow(s => !s)} aria-label={show ? 'Hide the password' : 'Show the password'} title={show ? 'Hide the password' : 'Show the password'}
              className="absolute right-1.5 top-1/2 -translate-y-1/2 w-8 h-8 inline-flex items-center justify-center rounded-lg text-muted hover:text-ink hover:bg-[#F6F8F3]">
        <Icon name={show ? 'eyeOff' : 'eye'} size={18} />
      </button>
    </div>
  );
}

function FormError({ children }) {
  if (!children) return null;
  return <div className="text-[13px] leading-relaxed rounded-xl px-4 py-3" style={{ background: 'rgba(192,57,43,0.07)', color: 'var(--neg)' }}>{children}</div>;
}
function FormNote({ children }) {
  if (!children) return null;
  return <div className="text-[13px] leading-relaxed rounded-xl px-4 py-3" style={{ background: 'var(--lime-soft)', color: '#3D5A0E' }}>{children}</div>;
}

function LoginScreen() {
  const [mode, setMode] = useState('login');      // 'login' | 'forgot'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [note, setNote] = useState('');
  const [busy, setBusy] = useState(false);

  async function submitLogin(e) {
    e.preventDefault();
    setError(''); setNote('');
    if (!email.trim() || !password) { setError('Enter your email and password.'); return; }
    setBusy(true);
    const { error: err } = await signIn(email.trim(), password);
    setBusy(false);
    if (err) setError('The email or password is not right. Check for a typo.');
    // success: app.jsx sees the new session and opens the app
  }

  async function submitForgot(e) {
    e.preventDefault();
    setError(''); setNote('');
    if (!email.trim()) { setError('Enter the email you log in with.'); return; }
    setBusy(true);
    const { error: err } = await sendPasswordReset(email.trim());
    setBusy(false);
    // the same message whether or not the email has an account (see the note at the top)
    if (err && /rate|limit/i.test(err.message || '')) { setError('Too many requests. Please wait a few minutes and try again.'); return; }
    setNote('If that email has an account, a link to choose a new password is on its way. Check your spam folder too.');
  }

  if (mode === 'forgot') {
    return (
      <AuthCard title="Forgot your password?" sub="We'll email you a link to choose a new one.">
        <form onSubmit={submitForgot} className="flex flex-col gap-4">
          <Field label="Email"><Input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@company.com" autoFocus /></Field>
          <FormError>{error}</FormError>
          <FormNote>{note}</FormNote>
          <Button type="submit" variant="primary" size="lg" disabled={busy} className="w-full">{busy ? 'Sending…' : 'Send the link'}</Button>
          <button type="button" className="text-[13px] font-600 hover:underline" style={{ color: 'var(--primary)' }} onClick={() => { setMode('login'); setError(''); setNote(''); }}>Back to login</button>
        </form>
      </AuthCard>
    );
  }

  return (
    <AuthCard title="P&L App" sub="Log in to see your numbers.">
      <form onSubmit={submitLogin} className="flex flex-col gap-4">
        <Field label="Email"><Input type="email" autoComplete="username" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@company.com" autoFocus /></Field>
        <Field label="Password"><PasswordInput autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} /></Field>
        <FormError>{error}</FormError>
        <Button type="submit" variant="primary" size="lg" disabled={busy} className="w-full">{busy ? 'Logging in…' : 'Log in'}</Button>
        <button type="button" className="text-[13px] font-600 hover:underline" style={{ color: 'var(--primary)' }} onClick={() => { setMode('forgot'); setError(''); }}>Forgot password?</button>
      </form>
    </AuthCard>
  );
}

/* After clicking the invite email or a reset link: the link has logged the person in,
   now they choose a password. `isInvite` only changes the wording. */
function SetPasswordScreen({ isInvite, onDone }) {
  const [pw, setPw] = useState('');
  const [pw2, setPw2] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setError('');
    if (pw.length < 8) { setError('Use at least 8 characters.'); return; }
    if (pw !== pw2) { setError('The two passwords are different.'); return; }
    setBusy(true);
    const { error: err } = await setNewPassword(pw);
    setBusy(false);
    if (err) { setError(/same/i.test(err.message || '') ? 'That is your current password. Choose a new one.' : 'Could not save the password: ' + err.message); return; }
    onDone();
  }

  return (
    <AuthCard title={isInvite ? 'Welcome! Choose a password' : 'Choose a new password'}
              sub={isInvite ? 'You\'ll use it with your email to log in from now on.' : 'Then you\'re back in.'}>
      <form onSubmit={submit} className="flex flex-col gap-4">
        <Field label="New password" hint="At least 8 characters."><PasswordInput autoComplete="new-password" value={pw} onChange={e => setPw(e.target.value)} autoFocus /></Field>
        <Field label="Type it again"><PasswordInput autoComplete="new-password" value={pw2} onChange={e => setPw2(e.target.value)} /></Field>
        <FormError>{error}</FormError>
        <Button type="submit" variant="primary" size="lg" disabled={busy} className="w-full">{busy ? 'Saving…' : 'Save password'}</Button>
      </form>
    </AuthCard>
  );
}

/* First login: agree to the terms and privacy policy. The date is stored (company_members.terms_accepted_at). */
function TermsScreen() {
  const [ticked, setTicked] = useState(false);
  const [busy, setBusy] = useState(false);
  return (
    <AuthCard title="Welcome to your P&L" sub={DB.company ? DB.company.name : ''}>
      <div className="flex flex-col gap-4">
        <p className="text-[13.5px] text-ink leading-relaxed">Before you start, please read and agree to how we look after your data.</p>
        <label className="flex items-start gap-3 text-[13.5px] text-ink cursor-pointer">
          <input type="checkbox" className="mt-0.5 w-4 h-4 accent-[#0F3B2C]" checked={ticked} onChange={e => setTicked(e.target.checked)} />
          <span>I agree to the <a href="terms.html" target="_blank" rel="noopener" className="font-600 underline" style={{ color: 'var(--primary)' }}>Terms</a> and
            the <a href="privacy.html" target="_blank" rel="noopener" className="font-600 underline" style={{ color: 'var(--primary)' }}>Privacy Policy</a>.</span>
        </label>
        <Button variant="primary" size="lg" disabled={!ticked || busy} className="w-full" onClick={async () => { setBusy(true); await acceptTerms(); setBusy(false); }}>
          {busy ? 'Saving…' : 'Continue'}
        </Button>
        <button type="button" className="text-[13px] text-muted hover:text-ink" onClick={() => signOut()}>Log out</button>
      </div>
    </AuthCard>
  );
}

/* Logged in, but Ana has not linked this login to a company yet (admin.create_company / add_member). */
function NoCompanyScreen() {
  return (
    <AuthCard title="Almost there" sub={DB.user ? DB.user.email : ''}>
      <div className="flex flex-col gap-4 text-center">
        <p className="text-[13.5px] text-ink leading-relaxed">
          Your login works, but it isn't linked to a company yet. We'll set that up for you shortly.
          If it takes more than a day, let the person who invited you know.
        </p>
        <Button variant="outline" className="w-full" onClick={() => signOut()}>Log out</Button>
      </div>
    </AuthCard>
  );
}

Object.assign(window, { LoginScreen, SetPasswordScreen, TermsScreen, NoCompanyScreen, PasswordInput });
