// Login — passwordless email OTP.
// Layout: logo · email field (inline 發送驗證碼) · code field · 登入 · 註冊提示.

// ── FloatingField — label lives INSIDE the box: centered as placeholder when
// empty & blurred, floats up small when focused or filled. ──
function FloatingField({ label, value, onChange, onKeyDown, type = 'text', inputMode, maxLength, trailing, wrapperStyle, inputStyle, multiline, rows = 3, autoFocus }) {
  const t = window.flutterTokens;
  const [focused, setFocused] = React.useState(false);
  const floated = focused || (value != null && String(value).length > 0);
  const sharedInputStyle = {
    width: '100%', boxSizing: 'border-box', border: 'none', outline: 'none',
    background: 'transparent', fontFamily: 'inherit', fontSize: 15, color: t.ink,
    letterSpacing: -0.2, padding: '25px 0 9px', ...inputStyle,
  };
  return (
    <div style={{
      position: 'relative', display: 'flex', alignItems: multiline ? 'stretch' : 'center', gap: 8,
      background: t.surface, border: `1px solid ${focused ? 'var(--accent)' : t.hairline}`,
      borderRadius: 13, padding: trailing ? '0 5px 0 14px' : '0 14px',
      transition: 'border-color 160ms ease', ...wrapperStyle,
    }}>
      <div style={{ position: 'relative', flex: 1, minWidth: 0 }}>
        <label style={{
          position: 'absolute', left: 0, right: 0, pointerEvents: 'none',
          color: t.ink3, fontWeight: floated ? 700 : 500, letterSpacing: -0.1,
          fontSize: floated ? 11.5 : 15,
          top: floated ? 8 : (multiline ? 25 : '50%'),
          transform: floated ? 'none' : (multiline ? 'none' : 'translateY(-50%)'),
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          transition: 'top 160ms ease, font-size 160ms ease, transform 160ms ease',
        }}>{label}</label>
        {multiline ? (
          <textarea
            rows={rows} maxLength={maxLength} autoFocus={autoFocus}
            value={value} onChange={onChange} onKeyDown={onKeyDown}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
            style={{ ...sharedInputStyle, resize: 'none', lineHeight: 1.5 }}
          />
        ) : (
          <input
            type={type} inputMode={inputMode} maxLength={maxLength} autoFocus={autoFocus}
            value={value} onChange={onChange} onKeyDown={onKeyDown}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
            style={sharedInputStyle}
          />
        )}
      </div>
      {trailing}
    </div>
  );
}

function Login({ onLogin, onGoRegister }) {
  const t = window.flutterTokens;
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [countdown, setCountdown] = React.useState(0);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const codeValid = code.trim().length === 6;

  React.useEffect(() => {
    if (countdown <= 0) return;
    const id = setTimeout(() => setCountdown(c => c - 1), 1000);
    return () => clearTimeout(id);
  }, [countdown]);

  const sendCode = () => {
    if (!emailValid || countdown > 0) return;
    setSent(true);
    setCountdown(60);
  };

  return (
    <div style={{
      height: '100%', background: t.bg, overflowY: 'auto',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
        padding: '0 28px', maxWidth: 440, width: '100%', margin: '0 auto', boxSizing: 'border-box',
      }}>
        {/* ── Logo ── */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 44 }}>
          <div style={{
            width: 88, height: 88, borderRadius: 26, background: 'var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 10px 24px -10px rgba(31,27,22,0.5)',
          }}>
            <window.Icon name="candles" size={44} color="#fff" strokeWidth={2}/>
          </div>
        </div>

        {/* ── Email ── */}
        <FloatingField
          label="信箱" type="email" inputMode="email"
          value={email} onChange={(e) => setEmail(e.target.value)}
          wrapperStyle={{ marginBottom: 14 }}
        />

        {/* ── Verification code + inline 發送驗證碼 ── */}
        <FloatingField
          label="驗證碼" type="text" inputMode="numeric" maxLength={6}
          value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
          wrapperStyle={{ marginBottom: 24 }}
          inputStyle={{ fontSize: 16, letterSpacing: code ? 4 : -0.2, fontVariantNumeric: 'tabular-nums' }}
          trailing={
            <button
              onClick={sendCode}
              disabled={!emailValid || countdown > 0}
              style={{
                flexShrink: 0, borderRadius: 9, padding: '9px 14px', border: 'none',
                background: (emailValid && countdown === 0) ? 'var(--accent-bg)' : t.surfaceAlt,
                color: (emailValid && countdown === 0) ? 'var(--accent)' : t.ink3,
                fontFamily: 'inherit', fontSize: 13, fontWeight: 700, letterSpacing: -0.1,
                cursor: (emailValid && countdown === 0) ? 'pointer' : 'default',
                whiteSpace: 'nowrap', transition: 'background 160ms ease, color 160ms ease',
              }}
            >{countdown > 0 ? `${countdown}s 後重新發送` : (sent ? '重新發送' : '發送驗證碼')}</button>
          }
        />

        {/* ── Login ── */}
        <button
          onClick={() => codeValid && onLogin && onLogin(email.trim())}
          disabled={!codeValid}
          style={{
            width: '100%', borderRadius: 13, padding: '15px', border: 'none',
            background: codeValid ? t.ink : t.surfaceAlt,
            color: codeValid ? t.bg : t.ink3,
            fontFamily: 'inherit', fontSize: 15.5, fontWeight: 700, letterSpacing: -0.2,
            cursor: codeValid ? 'pointer' : 'default', transition: 'background 160ms ease, color 160ms ease',
          }}
        >登入</button>

        {/* ── Registration hint ── */}
        <div style={{ marginTop: 20, textAlign: 'center', fontSize: 13.5, color: t.ink3, letterSpacing: -0.1 }}>
          還沒有帳號？
          <span
            onClick={() => onGoRegister && onGoRegister()}
            style={{ color: 'var(--accent)', fontWeight: 700, cursor: 'pointer', marginLeft: 2 }}
          >立即註冊</span>
        </div>
      </div>
    </div>
  );
}

// ── Register — email · 邀請碼 · 隱私權政策 checkbox · 註冊 ──
function Register({ onRegister, onGoLogin }) {
  const t = window.flutterTokens;
  const [email, setEmail] = React.useState('');
  const [invite, setInvite] = React.useState('');
  const [agree, setAgree] = React.useState(false);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const inviteValid = invite.trim().length > 0;
  const canSubmit = emailValid && inviteValid && agree;

  return (
    <div style={{ height: '100%', background: t.bg, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
        padding: '0 28px', maxWidth: 440, width: '100%', margin: '0 auto', boxSizing: 'border-box',
      }}>
        {/* Logo */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 36 }}>
          <div style={{
            width: 88, height: 88, borderRadius: 26, background: 'var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 10px 24px -10px rgba(31,27,22,0.5)',
          }}>
            <window.Icon name="candles" size={44} color="#fff" strokeWidth={2}/>
          </div>
        </div>

        {/* Email */}
        <FloatingField
          label="信箱" type="email" inputMode="email"
          value={email} onChange={(e) => setEmail(e.target.value)}
          wrapperStyle={{ marginBottom: 14 }}
        />

        {/* Invite code */}
        <FloatingField
          label="邀請碼" type="text"
          value={invite} onChange={(e) => setInvite(e.target.value)}
          wrapperStyle={{ marginBottom: 18 }}
        />

        {/* Privacy policy checkbox */}
        <div
          onClick={() => setAgree(a => !a)}
          style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', marginBottom: 24 }}
        >
          <span style={{
            flexShrink: 0, width: 20, height: 20, borderRadius: 6, marginTop: 1,
            border: `1.5px solid ${agree ? 'var(--accent)' : t.ink3}`,
            background: agree ? 'var(--accent)' : 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background 140ms ease, border-color 140ms ease',
          }}>
            {agree && <window.Icon name="check" size={13} color="#fff" strokeWidth={2.6}/>}
          </span>
          <span style={{ fontSize: 13, color: t.ink2, lineHeight: 1.5, letterSpacing: -0.1 }}>
            我已閱讀並同意
            <span style={{ color: 'var(--accent)', fontWeight: 700 }}>隱私權政策</span>
            與
            <span style={{ color: 'var(--accent)', fontWeight: 700 }}>服務條款</span>
          </span>
        </div>

        {/* Register */}
        <button
          onClick={() => canSubmit && onRegister && onRegister(email.trim())}
          disabled={!canSubmit}
          style={{
            width: '100%', borderRadius: 13, padding: '15px', border: 'none',
            background: canSubmit ? t.ink : t.surfaceAlt,
            color: canSubmit ? t.bg : t.ink3,
            fontFamily: 'inherit', fontSize: 15.5, fontWeight: 700, letterSpacing: -0.2,
            cursor: canSubmit ? 'pointer' : 'default', transition: 'background 160ms ease, color 160ms ease',
          }}
        >註冊</button>

        {/* Back to login */}
        <div style={{ marginTop: 20, textAlign: 'center', fontSize: 13.5, color: t.ink3, letterSpacing: -0.1 }}>
          已經有帳號？
          <span
            onClick={() => onGoLogin && onGoLogin()}
            style={{ color: 'var(--accent)', fontWeight: 700, cursor: 'pointer', marginLeft: 2 }}
          >返回登入</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login, Register, FloatingField });
