/* screens-auth.jsx — 注册与登录全流程
 * 视觉沿用移动端 V1 设计系统（品牌紫 / Inter / 8px 圆角 / Screen 外壳）
 * 逻辑参考 iOS Raccoon FunctionModule/Login&Sigin：
 *   LoginVC                       → AuthWelcome
 *   MobileLoginVC (.code)         → AuthMobileCode
 *   MobileLoginVC (.password)     → AuthMobilePassword
 *   LoginCodeVC                   → AuthSmsCode
 *   LoginAreaCodeViewController   → AuthAreaCode
 *   LoginSetPasswordVC            → AuthSetPassword
 * 关键复用逻辑：
 *   - 未注册手机号自动注册（文案与原 iOS 一致）
 *   - 验证码 / 密码两种登录方式可互切
 *   - 区号决定手机号最大长度（+86=11；+852/+853=8；+81=10）；可选区号仅 +86 / +852 / +853 / +81 四个
 *   - 60s 倒计时重发 + 阿里云滑块验证后端调用
 *   - 首次登录后若 password_status=="unset" 进入设置密码页
 *   - 密码规则：大小写字母 + 数字 + 特殊字符，8–32 位
 */
/* global React, Screen, Raccoon, Ic, Icon */

/* ---------- 顶部条：返回 + 标题 ---------- */
function AuthTopBar({ title = '', onBack = true }) {
  return (
    <div className="appbar" style={{ borderBottom: 'none' }}>
      {onBack ? (
        <button className="iconbtn" aria-label="返回"><Ic.back size={22} /></button>
      ) : <div style={{ width: 36 }} />}
      <div className="appbar-title" style={{ fontWeight: 600 }}>{title}</div>
      <div className="spacer" />
      <div style={{ width: 36 }} />
    </div>
  );
}

/* ---------- 主按钮（紫色 / 禁用态） ---------- */
function PrimaryBtn({ children, disabled, style }) {
  return (
    <button
      disabled={disabled}
      style={{
        width: '100%', height: 50, borderRadius: 14, border: 'none',
        background: disabled ? 'rgba(33,33,33,0.18)' : 'var(--purple)',
        color: '#fff', fontSize: 16, fontWeight: 600,
        letterSpacing: 0.3, cursor: disabled ? 'not-allowed' : 'pointer',
        ...style,
      }}
    >{children}</button>
  );
}

/* ---------- 协议勾选 + 富文本 ---------- */
function AgreementRow({ checked = false, align = 'left' }) {
  return (
    <div style={{
      display: 'flex', gap: 8, alignItems: 'flex-start',
      justifyContent: align === 'center' ? 'center' : 'flex-start',
      padding: '0 4px',
    }}>
      <span style={{
        width: 16, height: 16, marginTop: 2, borderRadius: 4, flex: '0 0 auto',
        background: checked ? 'var(--purple)' : '#fff',
        border: `1.5px solid ${checked ? 'var(--purple)' : '#C8C8C0'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
      }}>
        {checked && <Ic.check size={11} sw={2.4} />}
      </span>
      <p style={{
        margin: 0, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.65,
        maxWidth: align === 'center' ? 280 : undefined,
      }}>
        未注册手机号将自动注册，勾选即代表您阅读并同意小浣熊家族{' '}
        <span style={{ color: 'var(--purple-dark)' }}>用户协议</span> 与{' '}
        <span style={{ color: 'var(--purple-dark)' }}>隐私政策</span>
      </p>
    </div>
  );
}

/* ===================================================================
 * ① 欢迎页 — 对应 iOS LoginVC
 * ================================================================ */
function AuthWelcome() {
  return (
    <Screen>
      <div className="appbar" style={{ borderBottom: 'none' }}>
        <div style={{ width: 36 }} />
        <div className="spacer" />
        <div style={{ width: 36 }} />
      </div>
      <div className="body" style={{ display: 'flex', flexDirection: 'column' }}>
        <div style={{
          flex: 1, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          padding: '0 28px', textAlign: 'center',
        }}>
          <div style={{
            width: 96, height: 96, borderRadius: 22,
            background: '#fff', border: '1px solid var(--border)',
            boxShadow: '0 12px 28px rgba(142,107,242,0.18), 0 2px 6px rgba(10,10,6,0.06)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto',
          }}>
            <img src="assets/app-icon.png" alt="办公小浣熊"
              style={{ width: 72, height: 72, display: 'block' }} />
          </div>
          <h1 style={{
            margin: '20px 0 8px', fontSize: 26, fontWeight: 700,
            color: 'var(--t1)', letterSpacing: '-0.3px',
          }}>办公小浣熊</h1>
          <p style={{ fontSize: 14, color: 'var(--t3)', margin: 0, lineHeight: 1.65 }}>
            你的随身 AI 办公调度台
          </p>
        </div>
        <div style={{ padding: '0 24px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <PrimaryBtn>手机号登录 / 注册</PrimaryBtn>
          <AgreementRow checked={false} align="center" />
        </div>
      </div>
    </Screen>
  );
}

/* ===================================================================
 * ①′ 协议二次确认弹层 — LoginVC 中 agree=false 时点击登录的拦截
 *    设计模式：底部抬升半屏弹层 + 半透明遮罩
 *    用户必须点「同意并继续」才能继续，原入口按钮变为协议复述
 * ================================================================ */
function AuthAgreeSheet() {
  return (
    <Screen>
      {/* 底层欢迎页（降亮，被遮罩压住） */}
      <div className="appbar" style={{ borderBottom: 'none' }}>
        <div style={{ width: 36 }} />
        <div className="spacer" />
        <div style={{ width: 36 }} />
      </div>
      <div className="body" style={{ display: 'flex', flexDirection: 'column', position: 'relative' }}>
        <div style={{
          flex: 1, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          padding: '0 28px', textAlign: 'center',
        }}>
          <div style={{
            width: 96, height: 96, borderRadius: 22,
            background: '#fff', border: '1px solid var(--border)',
            boxShadow: '0 12px 28px rgba(142,107,242,0.18), 0 2px 6px rgba(10,10,6,0.06)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto',
          }}>
            <img src="assets/app-icon.png" alt="办公小浣熊"
              style={{ width: 72, height: 72, display: 'block' }} />
          </div>
          <h1 style={{
            margin: '20px 0 8px', fontSize: 26, fontWeight: 700,
            color: 'var(--t1)', letterSpacing: '-0.3px',
          }}>办公小浣熊</h1>
          <p style={{ fontSize: 14, color: 'var(--t3)', margin: 0, lineHeight: 1.65 }}>
            你的随身 AI 办公调度台
          </p>
        </div>
        <div style={{ padding: '0 24px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <PrimaryBtn>手机号登录 / 注册</PrimaryBtn>
          <AgreementRow checked={false} align="center" />
        </div>

        {/* 遮罩 */}
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(10,10,6,0.45)',
        }} />

        {/* 底部弹层 */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          background: '#fff', borderRadius: '20px 20px 0 0',
          padding: '22px 22px 28px',
          boxShadow: '0 -8px 24px rgba(0,0,0,0.08)',
        }}>
          <div style={{
            width: 36, height: 4, borderRadius: 2,
            background: 'var(--border)', margin: '0 auto 18px',
          }} />
          <h3 style={{
            margin: '0 0 10px', fontSize: 17, fontWeight: 600,
            color: 'var(--t1)', textAlign: 'center',
          }}>请先阅读并同意协议</h3>
          <p style={{
            margin: '0 0 18px', fontSize: 13.5, color: 'var(--t3)',
            lineHeight: 1.7, textAlign: 'center',
          }}>
            为保障你的合法权益，使用前请先阅读并同意小浣熊家族{' '}
            <span style={{ color: 'var(--purple-dark)', fontWeight: 500 }}>《用户协议》</span> 与{' '}
            <span style={{ color: 'var(--purple-dark)', fontWeight: 500 }}>《隐私政策》</span>。
            未注册的手机号将自动创建账号。
          </p>
          <PrimaryBtn>同意并继续</PrimaryBtn>
          <button style={{
            width: '100%', marginTop: 10, height: 44, borderRadius: 12,
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontSize: 14, color: 'var(--t3)', fontFamily: 'inherit',
          }}>不同意</button>
        </div>
      </div>
    </Screen>
  );
}

/* ===================================================================
 * 共享：手机号输入行（+86 区号 + 11 位）
 * ================================================================ */
function MobileInputRow({ areaCode = '+86', value = '' }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      borderBottom: '1.5px solid var(--border)', padding: '14px 4px',
    }}>
      <button style={{
        display: 'inline-flex', alignItems: 'center', gap: 4,
        background: 'transparent', border: 'none', cursor: 'pointer',
        fontSize: 17, fontWeight: 600, color: 'var(--t1)', padding: 0,
      }}>
        {areaCode}
        <Ic.chevD size={16} />
      </button>
      <div style={{ width: 1, height: 18, background: 'var(--border)' }} />
      <input
        defaultValue={value}
        placeholder="请输入手机号"
        inputMode="numeric"
        style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          fontSize: 17, color: 'var(--t1)', fontFamily: 'inherit',
          letterSpacing: 0.5,
        }}
      />
      {value && (
        <button className="iconbtn" style={{ width: 24, height: 24, color: 'var(--subtle)' }}>
          <Ic.x size={16} />
        </button>
      )}
    </div>
  );
}

/* ===================================================================
 * ② 手机号 · 验证码登录 — MobileLoginVC method=.code
 * ================================================================ */
function AuthMobileCode() {
  return (
    <Screen>
      <AuthTopBar />
      <div className="body" style={{ padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <h1 style={{ margin: '8px 0 6px', fontSize: 26, fontWeight: 700, color: 'var(--t1)', letterSpacing: '-0.3px' }}>
          手机号登录
        </h1>
        <p style={{ margin: '0 0 22px', fontSize: 13, color: 'var(--muted)' }}>
          未注册的手机号将自动创建账号
        </p>

        <MobileInputRow areaCode="+86" value="138 8888 8888" />

        <div style={{ marginTop: 26 }}>
          <PrimaryBtn>获取验证码</PrimaryBtn>
        </div>

        <button style={{
          marginTop: 16, alignSelf: 'center',
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontSize: 13.5, color: 'var(--purple-dark)', fontWeight: 500,
        }}>使用密码登录</button>

        <div style={{ flex: 1 }} />
        <AgreementRow checked={false} />
      </div>
    </Screen>
  );
}

/* ===================================================================
 * ③ 手机号 · 密码登录 — MobileLoginVC method=.password
 * ================================================================ */
function AuthMobilePassword() {
  const [show, setShow] = React.useState(false);
  return (
    <Screen>
      <AuthTopBar />
      <div className="body" style={{ padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <h1 style={{ margin: '8px 0 6px', fontSize: 26, fontWeight: 700, color: 'var(--t1)', letterSpacing: '-0.3px' }}>
          密码登录
        </h1>
        <p style={{ margin: '0 0 22px', fontSize: 13, color: 'var(--muted)' }}>
          使用账号密码直接登录
        </p>

        <MobileInputRow areaCode="+86" value="138 8888 8888" />

        {/* 密码输入 */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: '1.5px solid var(--border)', padding: '14px 4px',
        }}>
          <input
            type={show ? 'text' : 'password'}
            defaultValue="abc12345"
            placeholder="请输入密码（8–32 位）"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 17, color: 'var(--t1)', fontFamily: 'inherit', letterSpacing: 1,
            }}
          />
          <button
            onClick={() => setShow((v) => !v)}
            className="iconbtn"
            style={{ width: 28, height: 28, color: 'var(--subtle)' }}
            aria-label="切换显示"
          >
            {show ? <Ic.check size={18} /> : <Ic.x size={18} />}
          </button>
        </div>

        <div style={{
          marginTop: 10, fontSize: 12, color: 'var(--muted)', lineHeight: 1.6,
        }}>
          密码须包含大小写字母、数字与特殊字符，8–32 位
        </div>

        <div style={{ marginTop: 22 }}>
          <PrimaryBtn>登录</PrimaryBtn>
        </div>

        <div style={{
          marginTop: 16, display: 'flex', justifyContent: 'space-between',
          fontSize: 13.5, color: 'var(--purple-dark)', fontWeight: 500,
        }}>
          <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'inherit', padding: 0 }}>
            使用验证码登录
          </button>
          <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--t3)', padding: 0 }}>
            忘记密码？
          </button>
        </div>

        <div style={{ flex: 1 }} />
        <AgreementRow checked={false} />
      </div>
    </Screen>
  );
}

/* ===================================================================
 * ④ 短信验证码 6 位 — LoginCodeVC
 * ================================================================ */
function AuthSmsCode() {
  const filled = ['8', '4', '2', '', '', ''];
  return (
    <Screen>
      <AuthTopBar />
      <div className="body" style={{ padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <h1 style={{ margin: '8px 0 8px', fontSize: 26, fontWeight: 700, color: 'var(--t1)', letterSpacing: '-0.3px' }}>
          输入验证码
        </h1>
        <p style={{ margin: '0 0 28px', fontSize: 13, color: 'var(--muted)', lineHeight: 1.65 }}>
          验证码已发送至 <span style={{ color: 'var(--t1)', fontWeight: 500 }}>+86 138****8888</span>，
          十分钟内有效。如未收到，可尝试重新获取。
        </p>

        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
          {filled.map((d, i) => {
            const active = i === filled.findIndex((x) => x === '');
            return (
              <div key={i} style={{
                width: 46, height: 60, borderRadius: 10,
                border: `2px solid ${active ? 'var(--purple)' : (d ? 'var(--purple)' : '#E1E1E0')}`,
                background: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 28, fontWeight: 600, color: 'var(--purple-dark)',
                position: 'relative',
              }}>
                {d}
                {active && (
                  <span style={{
                    position: 'absolute', width: 2, height: 28,
                    background: 'var(--purple)', animation: 'none',
                  }} />
                )}
              </div>
            );
          })}
        </div>

        <div style={{ marginTop: 28 }}>
          <PrimaryBtn disabled>重新发送 48 s</PrimaryBtn>
        </div>

        <button style={{
          marginTop: 16, alignSelf: 'center',
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontSize: 13.5, color: 'var(--purple-dark)', fontWeight: 500,
        }}>使用密码登录</button>
      </div>
    </Screen>
  );
}

/* ===================================================================
 * ⑤ 区号选择 — LoginAreaCodeViewController
 * ================================================================ */
const AREA_CODES = [
  { group: '可选区号', items: [
    { name: '中国大陆', code: '+86' },
    { name: '中国香港', code: '+852' },
    { name: '中国澳门', code: '+853' },
    { name: '日本', code: '+81' },
  ]},
];

function AuthAreaCode() {
  return (
    <Screen>
      <AuthTopBar title="选择国家或地区" />
      <div className="body" style={{ padding: '0', display: 'flex', flexDirection: 'column' }}>
        {/* 搜索框 */}
        <div style={{ padding: '4px 16px 12px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            background: 'var(--bg-subtle)', border: '1px solid var(--border)',
            borderRadius: 12, padding: '10px 14px',
          }}>
            <Ic.search size={16} style={{ color: 'var(--subtle)' }} />
            <input placeholder="搜索国家或地区" style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 14, fontFamily: 'inherit', color: 'var(--t1)',
            }} />
          </div>
        </div>

        <div className="scroll">
          {AREA_CODES.map((sec) => (
            <div key={sec.group}>
              <div style={{
                padding: '8px 20px 6px', fontSize: 12, fontWeight: 600,
                color: 'var(--subtle)', letterSpacing: 0.5, background: 'var(--bg-soft)',
              }}>{sec.group}</div>
              {sec.items.map((it, idx) => {
                const selected = it.code === '+86';
                return (
                  <div key={it.code} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    padding: '14px 20px',
                    borderBottom: idx === sec.items.length - 1 ? 'none' : '1px solid var(--border)',
                    background: selected ? 'var(--purple-bg)' : '#fff',
                  }}>
                    <span style={{ fontSize: 15, color: selected ? 'var(--purple-dark)' : 'var(--t1)', fontWeight: selected ? 600 : 400 }}>
                      {it.name}
                    </span>
                    <span style={{ fontSize: 15, color: selected ? 'var(--purple-dark)' : 'var(--t3)' }}>
                      {it.code}
                    </span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

/* ===================================================================
 * ⑥ 首次登录设置密码 — LoginSetPasswordVC
 * ================================================================ */
function AuthSetPassword() {
  const [show1, setShow1] = React.useState(false);
  const [show2, setShow2] = React.useState(true);
  return (
    <Screen>
      <div className="appbar" style={{ borderBottom: 'none' }}>
        <div style={{ width: 36 }} />
        <div className="spacer" />
        <button style={{
          background: 'transparent', border: 'none', fontSize: 14,
          color: 'var(--t3)', cursor: 'pointer',
        }}>跳过</button>
      </div>
      <div className="body" style={{ padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <h1 style={{ margin: '8px 0 8px', fontSize: 26, fontWeight: 700, color: 'var(--t1)', letterSpacing: '-0.3px' }}>
          设置登录密码
        </h1>
        <p style={{ margin: '0 0 26px', fontSize: 13, color: 'var(--muted)', lineHeight: 1.65 }}>
          首次登录的小浣熊用户，请设置一个密码以便后续使用密码登录。
        </p>

        {/* 新密码 */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: '1.5px solid var(--border)', padding: '14px 4px',
        }}>
          <input
            type={show1 ? 'text' : 'password'}
            defaultValue="Abc12345!"
            placeholder="请输入新密码"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 17, color: 'var(--t1)', fontFamily: 'inherit', letterSpacing: 1,
            }}
          />
          <button onClick={() => setShow1(v => !v)} className="iconbtn"
            style={{ width: 28, height: 28, color: 'var(--subtle)' }}>
            {show1 ? <Ic.check size={18} /> : <Ic.x size={18} />}
          </button>
        </div>

        {/* 确认密码 */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: '1.5px solid var(--border)', padding: '14px 4px',
        }}>
          <input
            type={show2 ? 'text' : 'password'}
            defaultValue="Abc12345!"
            placeholder="请再次输入密码"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 17, color: 'var(--t1)', fontFamily: 'inherit', letterSpacing: 1,
            }}
          />
          <button onClick={() => setShow2(v => !v)} className="iconbtn"
            style={{ width: 28, height: 28, color: 'var(--subtle)' }}>
            {show2 ? <Ic.check size={18} /> : <Ic.x size={18} />}
          </button>
        </div>

        <div style={{
          marginTop: 14, padding: 12, borderRadius: 10,
          background: 'var(--bg-subtle)', border: '1px solid var(--border)',
          fontSize: 12, color: 'var(--t3)', lineHeight: 1.7,
        }}>
          <div style={{ fontWeight: 600, color: 'var(--t2)', marginBottom: 4 }}>密码要求</div>
          • 包含大小写字母、数字与特殊字符<br />
          • 长度 8–32 位<br />
          • 不能与用户名相同
        </div>

        <div style={{ marginTop: 24 }}>
          <PrimaryBtn>确认设置</PrimaryBtn>
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, {
  AuthWelcome, AuthAgreeSheet, AuthMobileCode, AuthMobilePassword,
  AuthSmsCode, AuthAreaCode, AuthSetPassword,
});
