// Three login variants — pick one, then I'll wire it as the real login page.
// All three lead to the same outcome: collect email → 'check inbox' → 'I clicked the link' → chat.

const { useState: useLoginState } = React;

// Shared: email input + button row, used in V1/V2/V3
function EmailRow({ value, onChange, onSubmit, autoFocus, returningEmail, error }) {
  const t = window.tokens;
  const [focused, setFocused] = React.useState(false);
  const invalid = Boolean(error);
  // Ring lights up on focus OR when the user has typed (as long as there's no error).
  const accent = (focused || !!value) && !invalid;
  const borderColor = invalid ? t.color.err : (accent ? t.color.action : t.color.strong);

  return (
    <>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        padding: '8px 8px 8px 14px',
        border: `1px solid ${borderColor}`,
        borderRadius: t.radius.lg,
        background: t.color.bg,
        transition: 'border-color 120ms ease, box-shadow 120ms ease',
        boxShadow: invalid ? `0 0 0 1px ${t.color.err}`
          : (accent ? `0 0 0 1px ${t.color.action}` : 'none'),
      }}>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke={invalid ? t.color.err : t.color.muted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
          <rect x="2" y="3.5" width="12" height="9" rx="1" />
          <path d="M2 4.5l6 4 6-4" />
        </svg>
        <input
          type="email"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={(e) => { if (e.key === 'Enter') onSubmit(); }}
          placeholder="you@example.com"
          autoFocus={autoFocus}
          aria-invalid={invalid}
          style={{
            flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none',
            fontFamily: t.font.sans, fontSize: 15, color: t.color.text, padding: '6px 0',
          }}
        />
        <Button variant="primary" onClick={onSubmit}>Send link</Button>
      </div>
      {error && (
        <div role="alert" style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 8,
          padding: '0 4px', fontSize: 13, color: t.color.err, fontFamily: t.font.sans,
        }}>
          <span aria-hidden="true" style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 16, height: 16, borderRadius: 8, background: t.color.err, color: '#fff',
            fontFamily: t.font.mono, fontSize: 11, fontWeight: 600, lineHeight: 1, flexShrink: 0,
          }}>!</span>
          {error}
        </div>
      )}
    </>
  );
}

function CheckInboxState({ email, onAdvance }) {
  const t = window.tokens;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{
        width: 44, height: 44, borderRadius: 22, background: t.color.actionSoft,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        border: `1px solid ${t.color.actionEdge}`,
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={t.color.action} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="5" width="18" height="14" rx="2" />
          <path d="M3 7l9 6 9-6" />
        </svg>
      </div>
      <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: -0.4, color: t.color.text, lineHeight: 1.2 }}>
        Check your inbox
      </div>
      <div style={{ fontSize: 15, color: t.color.body, lineHeight: 1.55 }}>
        We sent a sign in link to <strong style={{ color: t.color.text, fontWeight: 600 }}>{email}</strong>. Open the email and click the link to continue.
      </div>
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '10px 12px', background: t.color.warnLight, border: `1px solid ${t.color.hair}`,
        borderRadius: t.radius.md, fontSize: 12, color: t.color.muted, fontFamily: t.font.mono,
        letterSpacing: 0.2, alignSelf: 'flex-start',
      }}>
        <span style={{ textTransform: 'uppercase', fontWeight: 600 }}>Prototype</span>
        <span style={{ textTransform: 'none', fontFamily: t.font.sans, color: t.color.body }}>
          No real email is sent.
        </span>
        <Button variant="primary" size="sm" onClick={onAdvance} style={{ marginLeft: 8 }}>I clicked the link</Button>
      </div>
      <div style={{ fontSize: 13, color: t.color.muted }}>
        Didn't get it? <a href="#" style={{ color: t.color.action, textDecoration: 'none', fontWeight: 500 }}>Resend</a> · <a href="#" style={{ color: t.color.action, textDecoration: 'none', fontWeight: 500 }}>Use a different email</a>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// V1 · Centered card (classic, dedicated page)
// ────────────────────────────────────────────────────────────
function LoginV1() {
  const t = window.tokens;
  const [email, setEmail] = useLoginState('');
  const [phase, setPhase] = useLoginState('idle'); // idle | sent
  const [error, setError] = useLoginState('');

  const submit = () => {
    const v = email.trim();
    if (!v) { setError("Enter your email so we can send the sign in link."); return; }
    if (!/^\S+@\S+\.\S+$/.test(v)) { setError("That doesn't look like a valid email address."); return; }
    setError(''); setPhase('sent');
  };

  return (
    <div style={{
      minHeight: 600, background: t.color.surfaceLo,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '64px 24px',
    }}>
      <div style={{
        width: '100%', maxWidth: 440, background: t.color.bg,
        border: `1px solid ${t.color.hair}`, borderRadius: t.radius.xl,
        padding: 36, boxShadow: t.shadow.raised,
      }}>
        {phase === 'idle' ? (
          <>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '4px 10px', background: t.color.surfaceHi, borderRadius: t.radius.pill,
              fontFamily: t.font.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase',
              color: t.color.muted, marginBottom: 24,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 3, background: t.color.action }} />
              Continuing your dog license
            </div>
            <div style={{ fontSize: 28, fontWeight: 500, letterSpacing: -0.6, color: t.color.text, lineHeight: 1.15, marginBottom: 12 }}>
              Sign in to continue
            </div>
            <div style={{ fontSize: 15, color: t.color.body, lineHeight: 1.55, marginBottom: 24 }}>
              For your application receipt and any followups from Montgomery Township.
            </div>
            <EmailRow value={email} onChange={(v) => { setEmail(v); if (error) setError(''); }} onSubmit={submit} autoFocus error={error} />
            <div style={{ marginTop: 18, fontSize: 12, color: t.color.muted, lineHeight: 1.5 }}>
              By continuing, you agree to GovPilot's <a href="#" style={{ color: t.color.body }}>terms</a> and <a href="#" style={{ color: t.color.body }}>privacy notice</a>.
            </div>
          </>
        ) : (
          <CheckInboxState email={email} onAdvance={() => alert('→ chat')} />
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// V2 · Inline conversational (matches the home composer aesthetic)
// Keeps the chat metaphor: it looks like a tiny conversation that
// just happens to ask for an email before continuing.
// ────────────────────────────────────────────────────────────
function LoginV2() {
  const t = window.tokens;
  const [email, setEmail] = useLoginState('');
  const [phase, setPhase] = useLoginState('idle');
  const [error, setError] = useLoginState('');

  const submit = () => {
    const v = email.trim();
    if (!v) { setError("Enter your email so we can send the sign in link."); return; }
    if (!/^\S+@\S+\.\S+$/.test(v)) { setError("That doesn't look like a valid email address."); return; }
    setError(''); setPhase('sent');
  };

  return (
    <div style={{
      minHeight: 600, background: t.color.bg, padding: '80px 32px',
      display: 'flex', justifyContent: 'center',
    }}>
      <div style={{ width: '100%', maxWidth: 640 }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 24,
          fontFamily: t.font.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: t.color.muted,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: t.color.action }} />
          Dog License · Montgomery Township
        </div>

        {/* Conversation bubbles */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
          <div style={{
            alignSelf: 'flex-start', maxWidth: '80%', padding: '12px 18px',
            background: t.color.paper, color: t.color.text, border: `1px solid ${t.color.hair}`,
            fontSize: 16, lineHeight: 1.5, borderRadius: 14,
          }}>
            Before we save your progress, what's your email? We'll send a sign in link and use it for your application receipt and any followups from Montgomery.
          </div>
        </div>

        {phase === 'idle' ? (
          <EmailRow value={email} onChange={(v) => { setEmail(v); if (error) setError(''); }} onSubmit={submit} autoFocus error={error} />
        ) : (
          <>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
              <div style={{
                alignSelf: 'flex-end', maxWidth: '80%', padding: '12px 18px',
                background: t.color.text, color: '#FFFFFF',
                fontSize: 16, lineHeight: 1.5, borderRadius: 14,
              }}>
                {email}
              </div>
              <div style={{
                alignSelf: 'flex-start', maxWidth: '80%', padding: '12px 18px',
                background: t.color.paper, color: t.color.text, border: `1px solid ${t.color.hair}`,
                fontSize: 16, lineHeight: 1.5, borderRadius: 14,
              }}>
                Sent. Open the email and click the sign in link to keep going.
              </div>
            </div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 10,
              padding: '10px 12px', background: t.color.warnLight, border: `1px solid ${t.color.hair}`,
              borderRadius: t.radius.md, fontSize: 12, color: t.color.muted, fontFamily: t.font.mono, letterSpacing: 0.2,
            }}>
              <span style={{ textTransform: 'uppercase', fontWeight: 600 }}>Prototype</span>
              <span style={{ fontFamily: t.font.sans, color: t.color.body }}>No real email is sent.</span>
              <Button variant="primary" size="sm" onClick={() => alert('→ chat')}>I clicked the link</Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// V3 · Recognized account (returning user shortcut + magic link fallback)
// Shows BOTH: a recognized account "continue as" pill plus the email field.
// ────────────────────────────────────────────────────────────
function LoginV3() {
  const t = window.tokens;
  const [email, setEmail] = useLoginState('');
  const [phase, setPhase] = useLoginState('idle');
  const [error, setError] = useLoginState('');
  const recognized = 'sarah.l@gmail.com';

  const submit = () => {
    const v = email.trim();
    if (!v) { setError("Enter your email so we can send the sign in link."); return; }
    if (!/^\S+@\S+\.\S+$/.test(v)) { setError("That doesn't look like a valid email address."); return; }
    setError(''); setPhase('sent');
  };

  return (
    <div style={{
      minHeight: 600, background: t.color.surfaceLo,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '64px 24px',
    }}>
      <div style={{
        width: '100%', maxWidth: 460, background: t.color.bg,
        border: `1px solid ${t.color.hair}`, borderRadius: t.radius.xl,
        padding: 36, boxShadow: t.shadow.raised,
      }}>
        {phase === 'idle' ? (
          <>
            <div style={{ fontSize: 24, fontWeight: 500, letterSpacing: -0.5, color: t.color.text, lineHeight: 1.2, marginBottom: 8 }}>
              Welcome back
            </div>
            <div style={{ fontSize: 14, color: t.color.body, lineHeight: 1.55, marginBottom: 24 }}>
              Sign in to save your dog license progress.
            </div>

            {/* Recognized account */}
            <button
              onClick={() => { setEmail(recognized); setPhase('sent'); }}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px 14px', background: t.color.bg,
                border: `1px solid ${t.color.strong}`, borderRadius: t.radius.lg,
                cursor: 'pointer', textAlign: 'left', marginBottom: 12,
                transition: 'all 120ms ease', fontFamily: t.font.sans,
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = t.color.action; e.currentTarget.style.background = t.color.actionSoft; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = t.color.strong; e.currentTarget.style.background = t.color.bg; }}
            >
              <div style={{
                width: 36, height: 36, borderRadius: 18, background: t.color.surfaceHi,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14, fontWeight: 600, color: t.color.body, flexShrink: 0,
              }}>SL</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: t.color.text, marginBottom: 2 }}>
                  Continue as Sarah
                </div>
                <div style={{ fontSize: 12, color: t.color.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {recognized}
                </div>
              </div>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke={t.color.muted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M6 4l4 4-4 4" />
              </svg>
            </button>

            {/* Divider */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0',
              fontSize: 12, color: t.color.muted, fontFamily: t.font.mono, letterSpacing: 1, textTransform: 'uppercase',
            }}>
              <div style={{ flex: 1, height: 1, background: t.color.hair }} />
              or use a different email
              <div style={{ flex: 1, height: 1, background: t.color.hair }} />
            </div>

            <EmailRow value={email} onChange={(v) => { setEmail(v); if (error) setError(''); }} onSubmit={submit} error={error} />

            <div style={{ marginTop: 18, fontSize: 12, color: t.color.muted, lineHeight: 1.5 }}>
              For your application receipt and any followups from Montgomery.
            </div>
          </>
        ) : (
          <CheckInboxState email={email} onAdvance={() => alert('→ chat')} />
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LoginV1, LoginV2, LoginV3, EmailRow, CheckInboxState });
