/* Auth — Sign In / Join pages. Accounts need only email + username.
 * Usernames pass a profanity / slur filter before they're accepted. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { Card, Input, Button, Divider, Logo, Icon, FanLeaf } = D;
  const { useState } = React;

  /* -- username moderation -------------------------------------------- */
  const norm = (s) => String(s).toLowerCase()
    .replace(/[@]/g, 'a').replace(/[0]/g, 'o').replace(/[1!|]/g, 'i')
    .replace(/[3]/g, 'e').replace(/[4]/g, 'a').replace(/[5$]/g, 's')
    .replace(/[7]/g, 't').replace(/[8]/g, 'b').replace(/[^a-z]/g, '');
  // Substring-blocked: slurs & hate terms (matched anywhere, incl. leetspeak).
  const BLOCK_SUBSTR = ['nigg', 'fagg', 'kike', 'spic', 'wetback', 'chink', 'gook', 'beaner', 'raghead', 'towelhead', 'tranny', 'dyke', 'coon', 'darkie', 'gyppo', 'zipperhead', 'porchmonkey', 'junglebunny', 'heeb', 'sheeny', 'paki', 'nazi', 'hitler', 'kkk', 'whitepower', 'lynch'];
  // Whole-word-ish profanity (blocked when it dominates the name).
  const BLOCK_WORDS = ['fuck', 'shit', 'cunt', 'bitch', 'asshole', 'dickhead', 'pussy', 'whore', 'slut', 'rape', 'rapist', 'cock', 'penis', 'vagina'];
  function usernameProblem(raw) {
    const u = String(raw).replace(/^@/, '');
    if (u.length < 3) return 'Username must be at least 3 characters.';
    if (u.length > 20) return 'Username must be 20 characters or fewer.';
    if (!/^[a-zA-Z0-9._]+$/.test(u)) return 'Only letters, numbers, dots, and underscores.';
    const n = norm(u);
    if (BLOCK_SUBSTR.some((b) => n.includes(b)) || BLOCK_WORDS.some((b) => n.includes(b))) {
      return 'That username isn’t allowed — hateful or explicit terms are blocked by our community guidelines.';
    }
    return null;
  }
  const emailProblem = (e) => (/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(e).trim()) ? null : 'Enter a valid email address.');
  window.WR_USERNAME_PROBLEM = usernameProblem;

  /* -- shared shell ---------------------------------------------------- */
  function AuthShell({ children, title, sub }) {
    return (
      <div style={{ position: 'relative', minHeight: 'calc(100vh - 68px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 24px', background: 'radial-gradient(120% 140% at 85% 0%, #24503F 0%, #1B3B2F 55%, #14301F 100%)', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -60, bottom: -80, opacity: 0.08, pointerEvents: 'none' }}><FanLeaf size={380} filledColor="#EDE7D8" /></div>
        <Card padding="lg" elevation="lg" style={{ position: 'relative', width: 'min(430px, 100%)' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><Logo size="md" /></div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 600, color: 'var(--text-heading)', textAlign: 'center', letterSpacing: '-0.02em' }}>{title}</h1>
          <p style={{ color: 'var(--text-muted)', fontSize: 14, textAlign: 'center', margin: '8px 0 24px', lineHeight: 1.5 }}>{sub}</p>
          {children}
        </Card>
      </div>
    );
  }

  function JoinPage({ navigate, onAuth }) {
    const [email, setEmail] = useState('');
    const [username, setUsername] = useState('');
    const [errs, setErrs] = useState({});
    const submit = () => {
      const e1 = emailProblem(email);
      const e2 = usernameProblem(username);
      setErrs({ email: e1, username: e2 });
      if (e1 || e2) return;
      onAuth({ email: email.trim(), username: '@' + username.replace(/^@/, '') });
      navigate('home');
    };
    return (
      <AuthShell title="Join WeedReview" sub="Just an email and a username — no real names, no fluff. Start rating in under a minute.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Input label="Email" icon="mail" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} invalid={!!errs.email} hint={errs.email || undefined} />
          <Input label="Username" icon="at-sign" placeholder="terpchaser" value={username} onChange={(e) => setUsername(e.target.value)} invalid={!!errs.username} hint={errs.username || 'Letters, numbers, dots, underscores. Keep it classy — slurs and profanity are auto-blocked.'} />
          <Button size="lg" fullWidth onClick={submit}>Create account</Button>
          <p style={{ fontSize: 12, color: 'var(--text-faint)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
            By joining you confirm you’re 21+ and agree to the community guidelines.
          </p>
          <Divider label="Already a member?" />
          <Button variant="secondary" fullWidth onClick={() => navigate('signin')}>Sign in instead</Button>
        </div>
      </AuthShell>
    );
  }

  function SignInPage({ navigate, onAuth }) {
    const [email, setEmail] = useState('');
    const [err, setErr] = useState(null);
    const submit = () => {
      const e1 = emailProblem(email);
      setErr(e1);
      if (e1) return;
      const handle = email.split('@')[0].replace(/[^a-zA-Z0-9._]/g, '').slice(0, 20) || 'member';
      onAuth({ email: email.trim(), username: '@' + handle });
      navigate('home');
    };
    return (
      <AuthShell title="Welcome back" sub="Sign in with the email on your account — we’ll send a magic link (mocked here, you’re in instantly).">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Input label="Email" icon="mail" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} invalid={!!err} hint={err || undefined} />
          <Button size="lg" fullWidth iconLeft="send" onClick={submit}>Send magic link</Button>
          <Divider label="New here?" />
          <Button variant="secondary" fullWidth onClick={() => navigate('join')}>Create an account</Button>
        </div>
      </AuthShell>
    );
  }

  window.JoinPage = JoinPage;
  window.SignInPage = SignInPage;
})();
