/* ============================================================
   SVLM — Login. Two steps, matching the supplied design: choose a provider
   first, then a form only for whoever picks name-and-phone.

   The form is name + phone posted to /api/customers/identify, not email and
   password — this codebase has no password anywhere in the customer flow, and
   no SMS provider since SMS-KUB was cancelled, so neither a password field nor
   an OTP step could work.

   Apple appears in the list but is marked and disabled: unlike the other three
   it has no server-side implementation, and /api/auth/apple/start does not
   exist. Making it live needs a paid Apple Developer account, a Services ID and
   a .p8 signing key, and a token exchange unlike the others — Apple wants a JWT
   client secret signed ES256 and returns the profile inside an id_token. Until
   that is built, saying "soon" is the honest state; a button that redirects
   into an error teaches people the app is broken.
   ============================================================ */
const Pau = window.PALETTE;

/* Each provider's own mark. Letters in coloured squares stood in for these before, and a letter
   is not recognisable as Facebook or Google at a glance — the mark is why these buttons are
   trusted at all, and each brand's guidelines require their own. */
const BRAND_MARKS = {
  line: (
    <svg width="26" height="26" viewBox="0 0 24 24" aria-hidden="true">
      <rect width="24" height="24" rx="6" fill="#06C755" />
      <path fill="#fff" d="M19.6 10.8c0-3.4-3.4-6.2-7.6-6.2s-7.6 2.8-7.6 6.2c0 3.05 2.7 5.6 6.36 6.08.25.05.59.17.68.38.08.2.05.5.03.7l-.11.66c-.04.2-.16.76.66.41s4.4-2.59 6-4.43c1.1-1.21 1.58-2.44 1.58-3.8z" />
    </svg>
  ),
  facebook: (
    <svg width="26" height="26" viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="12" cy="12" r="12" fill="#1877F2" />
      <path fill="#fff" d="M16.2 12.4h-2.5V20h-3.1v-7.6H8.8V9.8h1.8V8.3c0-2.06 1.2-3.2 3.1-3.2.9 0 1.85.16 1.85.16v2.03h-1.04c-1.02 0-1.34.63-1.34 1.28v1.23h2.28z" />
    </svg>
  ),
  google: (
    <svg width="23" height="23" viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#4285F4" d="M23.5 12.27c0-.79-.07-1.54-.2-2.27H12v4.51h6.47a5.53 5.53 0 0 1-2.4 3.63v3h3.88c2.27-2.09 3.55-5.17 3.55-8.87z" />
      <path fill="#34A853" d="M12 24c3.24 0 5.96-1.08 7.95-2.91l-3.88-3c-1.08.72-2.45 1.16-4.07 1.16-3.13 0-5.78-2.11-6.73-4.96H1.29v3.09A12 12 0 0 0 12 24z" />
      <path fill="#FBBC05" d="M5.27 14.29a7.2 7.2 0 0 1 0-4.58V6.62H1.29a12 12 0 0 0 0 10.76z" />
      <path fill="#EA4335" d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.44-3.44C17.95 1.19 15.24 0 12 0A12 12 0 0 0 1.29 6.62l3.98 3.09C6.22 6.86 8.87 4.75 12 4.75z" />
    </svg>
  ),
  apple: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="#000" aria-hidden="true">
      <path d="M17.05 12.54c-.03-2.7 2.2-4 2.3-4.06-1.25-1.83-3.2-2.08-3.9-2.11-1.66-.17-3.24.98-4.09.98-.84 0-2.14-.96-3.52-.93-1.81.03-3.48 1.05-4.41 2.67-1.88 3.26-.48 8.08 1.35 10.72.9 1.29 1.97 2.74 3.38 2.69 1.36-.06 1.87-.88 3.51-.88 1.64 0 2.1.88 3.53.85 1.46-.03 2.38-1.32 3.27-2.62 1.03-1.5 1.46-2.95 1.48-3.03-.03-.01-2.84-1.09-2.87-4.32M14.4 4.6c.75-.9 1.25-2.16 1.11-3.41-1.08.04-2.38.72-3.15 1.62-.69.8-1.29 2.07-1.13 3.3 1.2.09 2.43-.61 3.17-1.51" />
    </svg>
  ),
  phone: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill={Pau.ink} aria-hidden="true">
      <circle cx="12" cy="8" r="4.2" />
      <path d="M12 13.6c-4.3 0-7.8 2.4-7.8 5.4 0 .6.5 1 1.1 1h13.4c.6 0 1.1-.4 1.1-1 0-3-3.5-5.4-7.8-5.4z" />
    </svg>
  ),
};

function AuthScreen({ app, oauthError }) {
  /* 'choose' is the provider list; 'form' is the name-and-phone step behind the last button. The
     design puts them on separate screens rather than showing a form nobody using LINE will fill. */
  const [step, setStep] = React.useState('choose');
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(oauthError || '');

  /* Starts false on purpose. A pre-ticked consent box is not consent under Thai PDPA, so the
     sheet below is the gate: it is what someone taps through, not decoration. */
  const [agreed, setAgreed] = React.useState(false);
  const [gate, setGate] = React.useState(null); // the action waiting on consent

  const social = (provider) => { window.location.href = `/api/auth/${provider}/start`; };

  /* Every route in — a provider, the form, guest — passes through here, so consent is asked once
     and cannot be skipped by choosing a different button. */
  const guardedRun = (action) => {
    if (agreed) { action(); return; }
    setGate(() => action);
  };

  const submit = async (asGuest = false) => {
    setErr('');
    if (!asGuest && !name.trim()) { setErr(appT('name_required') || 'Please enter your name'); return; }
    if (phone.replace(/\D/g, '').length < 9) { setErr(appT('phone_required') || 'Please enter a valid phone number'); return; }
    setBusy(true);
    try {
      const result = await api('/customers/identify', {
        method: 'POST',
        body: JSON.stringify({ name: asGuest ? 'Guest' : name.trim(), phone: phone.trim() }),
      });
      localStorage.setItem('svlm_token', result.token);
      localStorage.setItem('svlm_customer', JSON.stringify(result.customer));
      app.login({ method: asGuest ? 'guest' : 'phone', name: result.customer.name, phone: result.customer.phone, customer: result.customer });
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  };

  /* Full pill, mark on the left, nothing on the right. The chevron that used to sit at the end
     said "this opens another screen of ours", which is the opposite of what these do. */
  const Pill = ({ mark, label, onClick, primary = false, soon = false }) => (
    <button
      onClick={soon ? undefined : onClick}
      disabled={soon}
      aria-disabled={soon || undefined}
      style={{
        display: 'flex', alignItems: 'center', gap: 16, width: '100%', height: 58,
        borderRadius: 999, padding: '0 26px', cursor: soon ? 'default' : 'pointer',
        fontFamily: 'inherit', fontWeight: 700, fontSize: 15.5, textAlign: 'left',
        border: primary ? 'none' : `1px solid ${Pau.line}`,
        background: primary ? Pau.primary : Pau.card,
        color: primary ? '#fff' : Pau.ink,
        boxShadow: primary ? '0 10px 24px -10px rgba(238,123,22,0.55)' : '0 2px 8px rgba(42,32,23,0.06)',
        opacity: soon ? 0.55 : 1,
      }}>
      <span style={{ width: 26, height: 26, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{mark}</span>
      <span style={{ flex: 1 }}>{label}</span>
      {/* Apple is drawn because it belongs in this list, and labelled because the endpoint behind it
          does not exist yet. A button that silently fails teaches people the app is broken; one that
          says it is not ready yet costs nothing and tells the truth. */}
      {soon && (
        <span style={{
          fontSize: 10.5, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase',
          color: Pau.muted, background: Pau.lineSoft, padding: '4px 9px', borderRadius: 999, flexShrink: 0,
        }}>{appT('coming_soon')}</span>
      )}
    </button>
  );

  const Consent = () => (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '0 4px' }}>
      <button
        onClick={() => setAgreed(!agreed)}
        aria-pressed={agreed}
        aria-label={appT('terms_agree_label') || 'I agree to the terms'}
        style={{
          width: 22, height: 22, borderRadius: 7, flexShrink: 0, marginTop: 1, cursor: 'pointer',
          border: agreed ? 'none' : `1.5px solid ${Pau.faint}`,
          background: agreed ? Pau.primary : 'transparent',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
        }}>
        {agreed && <Icon name="check" size={14} color="#fff" sw={3} />}
      </button>
      <div style={{ fontSize: 11.5, lineHeight: 1.55, color: Pau.muted }}>
        {appT('terms_prefix') || 'I have read and agree to the'}{' '}
        <a href="/terms.html" style={{ color: Pau.primary, fontWeight: 700, textDecoration: 'none' }}>{appT('terms_service') || 'Service Agreement'}</a>
        {' '}{appT('terms_and') || 'and'}{' '}
        <a href="/privacy.html" style={{ color: Pau.primary, fontWeight: 700, textDecoration: 'none' }}>{appT('terms_privacy') || 'Privacy Policy'}</a>
      </div>
    </div>
  );

  const shell = (children) => (
    <div style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      background: 'linear-gradient(180deg, #fff4e8 0%, #ffe3c8 100%)', position: 'relative',
    }}>
      {children}
      {gate && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 60, padding: 26,
          background: 'rgba(42,29,18,0.46)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ background: Pau.card, borderRadius: 26, padding: '24px 22px 18px', width: '100%', maxWidth: 360, boxShadow: '0 24px 50px -18px rgba(42,29,18,0.55)' }}>
            {/* Names what is collected. "Please read the terms" on its own is not a disclosure. */}
            <div style={{ fontSize: 13.5, lineHeight: 1.65, color: Pau.ink, marginBottom: 20 }}>
              {appT('terms_gate_body')
                || 'Please read the Service Agreement and Privacy Policy before continuing. We collect your name, phone number and service address to schedule and carry out your booking.'}
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <button onClick={() => setGate(null)} style={{
                flex: 1, height: 48, borderRadius: 999, border: 'none', cursor: 'pointer',
                fontFamily: 'inherit', fontWeight: 700, fontSize: 14.5,
                background: Pau.lineSoft, color: Pau.muted,
              }}>{appT('cancel') || 'Cancel'}</button>
              <button onClick={() => { const run = gate; setAgreed(true); setGate(null); run(); }} style={{
                flex: 1, height: 48, borderRadius: 999, border: 'none', cursor: 'pointer',
                fontFamily: 'inherit', fontWeight: 700, fontSize: 14.5,
                background: Pau.primary, color: '#fff',
              }}>{appT('agree') || 'Agree'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );

  /* ---------- step 2: name and phone ---------- */
  if (step === 'form') {
    return shell(
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '18px 26px 30px' }}>
        <button onClick={() => { setStep('choose'); setErr(''); }} aria-label={appT('back') || 'Back'} style={{
          width: 42, height: 42, borderRadius: 999, border: `1px solid ${Pau.line}`, background: Pau.card,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0,
          boxShadow: '0 2px 8px rgba(42,32,23,0.06)',
        }}>
          <Icon name="chevL" size={19} color={Pau.ink} />
        </button>

        <h1 style={{ fontSize: 30, fontWeight: 800, color: Pau.ink, letterSpacing: -0.6, lineHeight: 1.2, margin: '34px 0 30px' }}>
          {appT('signin_phone_title') || 'Sign in with your phone'}
        </h1>

        <div style={{ background: Pau.card, borderRadius: 24, padding: '4px 20px', boxShadow: '0 2px 10px rgba(42,32,23,0.06)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 0', borderBottom: `1px solid ${Pau.lineSoft}` }}>
            <Icon name="user" size={19} color={Pau.faint} />
            <input value={name} onChange={e => setName(e.target.value)} placeholder={appT('name_placeholder') || 'Your name'}
              style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'none', fontFamily: 'inherit', fontSize: 15, color: Pau.ink }} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 0' }}>
            <Icon name="phone" size={19} color={Pau.faint} />
            <input value={phone} onChange={e => setPhone(e.target.value)} placeholder={appT('phone_placeholder') || '08X-XXX-XXXX'} inputMode="tel"
              style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'none', fontFamily: 'inherit', fontSize: 15, color: Pau.ink }} />
          </div>
        </div>

        {err && <div style={{ color: '#d23a3a', fontSize: 13, fontWeight: 700, marginTop: 14 }}>{err}</div>}

        <div style={{ marginTop: 30 }}>
          <Pill primary label={busy ? (appT('please_wait') || 'Please wait…') : (appT('continue_button') || 'Continue')}
            mark={null} onClick={() => { if (!busy) submit(false); }} />
        </div>

        <button onClick={() => { if (!busy) submit(true); }} style={{
          width: '100%', marginTop: 20, background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: 'inherit', fontSize: 14, fontWeight: 700, color: Pau.muted,
        }}>{appT('continue_guest')}</button>
      </div>
    );
  }

  /* ---------- step 1: choose a provider ---------- */
  return shell(
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '0 26px 26px' }}>
      <h1 style={{ fontSize: 30, fontWeight: 800, color: Pau.ink, letterSpacing: -0.6, textAlign: 'center', margin: '78px 0 0' }}>
        {appT('welcome_title')}
      </h1>
      <p style={{ fontSize: 14, color: Pau.muted, textAlign: 'center', margin: '10px 0 0' }}>
        {appT('welcome_subtitle')}
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 15, margin: 'auto 0' }}>
        <Pill mark={BRAND_MARKS.facebook} label={appT('signin_facebook')} onClick={() => guardedRun(() => social('facebook'))} />
        <Pill mark={BRAND_MARKS.google} label={appT('signin_google')} onClick={() => guardedRun(() => social('google'))} />
        <Pill mark={BRAND_MARKS.line} label={appT('signin_line')} onClick={() => guardedRun(() => social('line'))} />
        <Pill mark={BRAND_MARKS.apple} label={appT('signin_apple')} soon />
        <Pill mark={BRAND_MARKS.phone} label={appT('signin_phone')} onClick={() => guardedRun(() => setStep('form'))} />
      </div>

      {err && <div style={{ color: '#d23a3a', fontSize: 13, fontWeight: 700, textAlign: 'center', marginBottom: 14 }}>{err}</div>}

      <button onClick={() => guardedRun(() => setStep('form'))} style={{
        width: '100%', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 26,
        fontFamily: 'inherit', fontSize: 14.5, fontWeight: 700, color: Pau.primary,
      }}>{appT('continue_guest')}</button>

      <Consent />
    </div>
  );
}

/* small badge showing which provider the member used (in profile) */
function LoginBadge({ method }) {
  const map = { line: ['L', '#06c755'], facebook: ['f', '#1877f2'], google: ['G', '#ea4335'], phone: ['☎', '#ee7b16'] };
  const m = map[method]; if (!m) return null;
  return <span style={{ width: 16, height: 16, borderRadius: 5, background: m[1], color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 800 }}>{m[0]}</span>;
}

Object.assign(window, { AuthScreen, LoginBadge });
