// Personal info — name & birthday locked, email/phone editable via verification

function SettingsPersonalInfoScreen({ theme, accent, onBack }) {
  const [email, setEmail] = React.useState(USER.email);
  const [phone, setPhone] = React.useState(USER.phone);
  const dob = '14 Mar 1993';

  // Inline change flow: null | 'email' | 'phone' | 'locked'
  const [flow, setFlow] = React.useState(null);

  if (flow === 'email')  return <EmailChangeFlow theme={theme} accent={accent} current={email} onClose={() => setFlow(null)} onDone={v => { setEmail(v); setFlow(null); }}/>;
  if (flow === 'phone')  return <PhoneChangeFlow theme={theme} accent={accent} current={phone} onClose={() => setFlow(null)} onDone={v => { setPhone(v); setFlow(null); }}/>;
  if (flow === 'locked') return <LockedFieldNotice theme={theme} accent={accent} onBack={() => setFlow(null)}/>;

  return (
    <Screen theme={theme} padTop={0} padBottom={120}>
      <NavBar theme={theme} title="Personal info" onBack={onBack}/>

      <div style={{ padding: '6px 16px 0' }}>
        <Card theme={theme} padded={false} style={{ padding: 4 }}>
          <ReadOnlyField theme={theme} label="Full name"     value={USER.name} onLockedTap={() => setFlow('locked')}/>
          <ReadOnlyField theme={theme} label="Date of birth" value={dob}        onLockedTap={() => setFlow('locked')}/>
          <EditableField theme={theme} accent={accent} label="Email" value={email} onEdit={() => setFlow('email')}/>
          <EditableField theme={theme} accent={accent} label="Phone" value={phone} onEdit={() => setFlow('phone')} last/>
        </Card>
      </div>

      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ fontSize: 11.5, color: theme.textMute, lineHeight: 1.55 }}>
          To change your full name or date of birth, please contact support.
        </div>
      </div>
    </Screen>
  );
}

function ReadOnlyField({ theme, label, value, onLockedTap }) {
  return (
    <button onClick={onLockedTap} style={{
      width: '100%', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 14px',
      background: 'transparent', border: 'none',
      borderBottom: `0.5px solid ${theme.line}`,
      cursor: 'pointer', color: theme.text,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute, marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 13.5, color: theme.textMute, fontWeight: 500 }}>{value}</div>
      </div>
      <Ico.lock size={14} stroke={theme.textMute}/>
    </button>
  );
}

function EditableField({ theme, accent, label, value, onEdit, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 14px',
      borderBottom: last ? 'none' : `0.5px solid ${theme.line}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute, marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
      </div>
      <button onClick={onEdit} style={{
        background: 'transparent', border: 'none',
        color: accent,
        fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600,
        cursor: 'pointer', padding: '4px 8px',
      }}>Change</button>
    </div>
  );
}

function LockedFieldNotice({ theme, accent, onBack }) {
  return (
    <Screen theme={theme} padTop={0} padBottom={40}>
      <NavBar theme={theme} title="Locked field" onBack={onBack}/>
      <div style={{ padding: '24px 16px 0', textAlign: 'center' }}>
        <div style={{
          width: 60, height: 60, borderRadius: 30, margin: '8px auto 16px',
          background: `${theme.textMute}18`, color: theme.textDim,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Ico.lock size={26}/></div>
        <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, lineHeight: 1.3, padding: '0 16px' }}>
          This field can’t be edited in-app
        </div>
        <div style={{ fontSize: 13, color: theme.textDim, marginTop: 10, padding: '0 24px', lineHeight: 1.55 }}>
          For security, full name and date of birth are tied to your verified ID. To update them, please open a support ticket and our team will help within one business day.
        </div>
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <button onClick={() => { window.location.href = 'mailto:support@himma.app?subject=Update%20personal%20info'; }} style={{
          width: '100%',
          background: theme.text, color: theme.bg,
          border: 'none', borderRadius: 16,
          padding: '14px',
          fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Ico.send size={14} stroke={theme.bg} sw={2}/> Open a support ticket
        </button>
        <button onClick={onBack} style={{
          marginTop: 10, width: '100%',
          background: 'transparent', border: 'none',
          color: theme.textDim,
          fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 500,
          cursor: 'pointer', padding: '10px 0',
        }}>Back</button>
      </div>
    </Screen>
  );
}

// ── Email change: single verification flow ──────────────────────────────────
//   enter-new → verify-new → done

function EmailChangeFlow({ theme, accent, current, onClose, onDone }) {
  const [step, setStep] = React.useState('enter-new'); // enter-new | verify-new | done
  const [code, setCode] = React.useState('');
  const [newEmail, setNewEmail] = React.useState('');
  const [error, setError] = React.useState('');

  const submitCode = () => {
    if (code.length !== 6) { setError('Enter the 6-digit code'); return; }
    setError(''); setCode('');
    setStep('done');
  };

  const submitNewEmail = () => {
    if (!newEmail.includes('@') || !newEmail.includes('.')) { setError('Enter a valid email'); return; }
    setError('');
    setStep('verify-new');
  };

  if (step === 'done') {
    return (
      <ConfirmDone theme={theme} title="Email updated"
        body={`Your account email is now ${newEmail}. We’ve sent a confirmation to your previous address.`}
        onBack={() => onDone(newEmail)}/>
    );
  }

  return (
    <Screen theme={theme} padTop={0} padBottom={40}>
      <NavBar theme={theme} title="Change email" onBack={onClose}/>

      {step === 'verify-new' && (
        <>
          <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 28, margin: '12px auto 14px',
              background: `${accent}18`, color: accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Ico.shield size={26}/></div>
            <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, lineHeight: 1.3, padding: '0 16px' }}>
              Verify your new email
            </div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 8, padding: '0 24px', lineHeight: 1.55 }}>
              We’ve sent a 6-digit code to {newEmail}.
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <Card theme={theme} padded={false} style={{ padding: 16 }}>
              <PiLabel theme={theme}>Verification code</PiLabel>
              <input
                value={code}
                inputMode="numeric"
                maxLength={6}
                onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="••••••"
                style={{
                  marginTop: 8, width: '100%',
                  background: theme.surface2, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                  padding: '12px 14px', color: theme.text,
                  fontSize: 18, fontFamily: FONTS.mono, letterSpacing: 6,
                  textAlign: 'center', outline: 'none',
                }}
              />
              {error && <div style={{ marginTop: 10, color: theme.negative, fontSize: 12 }}>{error}</div>}
              <ResendTimer theme={theme} accent={accent}/>
            </Card>
          </div>

          <div style={{ padding: '20px 16px 0' }}>
            <button onClick={submitCode} style={{
              width: '100%',
              background: theme.text, color: theme.bg,
              border: 'none', borderRadius: 16,
              padding: '14px',
              fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
              cursor: 'pointer',
            }}>Verify</button>
          </div>
        </>
      )}

      {step === 'enter-new' && (
        <>
          <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
            <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, lineHeight: 1.3, padding: '8px 16px 0' }}>
              Enter your new email
            </div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 8, padding: '0 24px', lineHeight: 1.55 }}>
              We’ll send a verification code to confirm.
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <Card theme={theme} padded={false} style={{ padding: 16 }}>
              <PiLabel theme={theme}>New email</PiLabel>
              <input
                value={newEmail}
                onChange={e => setNewEmail(e.target.value)}
                placeholder="you@example.com"
                type="email"
                style={{
                  marginTop: 8, width: '100%',
                  background: theme.surface2, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                  padding: '12px 14px', color: theme.text,
                  fontSize: 14, fontFamily: FONTS.ui, outline: 'none',
                }}
              />
              {error && <div style={{ marginTop: 10, color: theme.negative, fontSize: 12 }}>{error}</div>}
            </Card>
          </div>

          <div style={{ padding: '20px 16px 0' }}>
            <button onClick={submitNewEmail} style={{
              width: '100%',
              background: theme.text, color: theme.bg,
              border: 'none', borderRadius: 16,
              padding: '14px',
              fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
              cursor: 'pointer',
            }}>Send verification</button>
          </div>
        </>
      )}
    </Screen>
  );
}

// ── Phone change: OTP flow ───────────────────────────────────────────────────
//   enter-new → verify → done

function PhoneChangeFlow({ theme, accent, current, onClose, onDone }) {
  const [step, setStep] = React.useState('enter-new'); // enter-new | verify | done
  const [phoneRest, setPhoneRest] = React.useState('');
  const [code, setCode] = React.useState('');
  const [error, setError] = React.useState('');

  const fullPhone = `+971 ${phoneRest}`.trim();

  const submitNewPhone = () => {
    const digits = phoneRest.replace(/\D/g, '');
    if (digits.length < 7) { setError('Enter a valid phone number'); return; }
    setError('');
    setStep('verify');
  };

  const submitCode = () => {
    if (code.length !== 6) { setError('Enter the 6-digit code'); return; }
    setError(''); setCode('');
    setStep('done');
  };

  if (step === 'done') {
    return (
      <ConfirmDone theme={theme} title="Phone updated"
        body={`Your account phone is now ${fullPhone}.`}
        onBack={() => onDone(fullPhone)}/>
    );
  }

  return (
    <Screen theme={theme} padTop={0} padBottom={40}>
      <NavBar theme={theme} title="Change phone" onBack={onClose}/>

      {step === 'enter-new' && (
        <>
          <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
            <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, lineHeight: 1.3, padding: '8px 16px 0' }}>
              Enter your new phone
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <Card theme={theme} padded={false} style={{ padding: 16 }}>
              <div style={{
                display: 'flex', alignItems: 'stretch',
                background: theme.surface2, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                overflow: 'hidden',
              }}>
                <div style={{
                  padding: '12px 12px',
                  borderRight: `0.5px solid ${theme.line2}`,
                  background: theme.surface3,
                  color: theme.text,
                  fontSize: 14, fontFamily: FONTS.mono, letterSpacing: 0.5,
                  display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0,
                }}>
                  <UAEFlag/>
                  <span>+971</span>
                </div>
                <input
                  value={phoneRest}
                  onChange={e => setPhoneRest(e.target.value.replace(/[^\d ]/g, ''))}
                  placeholder="50 000 0000"
                  inputMode="tel"
                  style={{
                    flex: 1, background: 'transparent', border: 'none',
                    padding: '12px 14px', color: theme.text,
                    fontSize: 14, fontFamily: FONTS.mono, letterSpacing: 0.5, outline: 'none',
                  }}
                />
              </div>
              {error && <div style={{ marginTop: 10, color: theme.negative, fontSize: 12 }}>{error}</div>}
            </Card>
          </div>

          <div style={{ padding: '20px 16px 0' }}>
            <button onClick={submitNewPhone} style={{
              width: '100%',
              background: theme.text, color: theme.bg,
              border: 'none', borderRadius: 16,
              padding: '14px',
              fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
              cursor: 'pointer',
            }}>Send OTP</button>
          </div>
        </>
      )}

      {step === 'verify' && (
        <>
          <div style={{ padding: '8px 16px 0', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 28, margin: '12px auto 14px',
              background: `${accent}18`, color: accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Ico.shield size={26}/></div>
            <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, lineHeight: 1.3, padding: '0 16px' }}>
              Enter your OTP
            </div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 8, padding: '0 24px', lineHeight: 1.55 }}>
              We’ve sent a 6-digit code to {fullPhone}.
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <Card theme={theme} padded={false} style={{ padding: 16 }}>
              <PiLabel theme={theme}>OTP code</PiLabel>
              <input
                value={code}
                inputMode="numeric"
                maxLength={6}
                onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="••••••"
                style={{
                  marginTop: 8, width: '100%',
                  background: theme.surface2, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                  padding: '12px 14px', color: theme.text,
                  fontSize: 18, fontFamily: FONTS.mono, letterSpacing: 6,
                  textAlign: 'center', outline: 'none',
                }}
              />
              {error && <div style={{ marginTop: 10, color: theme.negative, fontSize: 12 }}>{error}</div>}
              <ResendTimer theme={theme} accent={accent}/>
            </Card>
          </div>

          <div style={{ padding: '20px 16px 0' }}>
            <button onClick={submitCode} style={{
              width: '100%',
              background: theme.text, color: theme.bg,
              border: 'none', borderRadius: 16,
              padding: '14px',
              fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
              cursor: 'pointer',
            }}>Verify</button>
          </div>
        </>
      )}
    </Screen>
  );
}

// Resend code button with 60s countdown timer
function ResendTimer({ theme, accent, seconds = 60 }) {
  const [remaining, setRemaining] = React.useState(seconds);
  React.useEffect(() => {
    if (remaining <= 0) return;
    const id = setInterval(() => setRemaining(r => Math.max(0, r - 1)), 1000);
    return () => clearInterval(id);
  }, [remaining]);

  const ready = remaining === 0;
  return (
    <button
      disabled={!ready}
      onClick={() => ready && setRemaining(seconds)}
      style={{
        marginTop: 12, background: 'transparent', border: 'none',
        color: ready ? accent : theme.textMute,
        fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600,
        cursor: ready ? 'pointer' : 'default', padding: 0,
        display: 'inline-flex', alignItems: 'center', gap: 6,
      }}>
      Resend code{!ready && (
        <span style={{ fontFamily: FONTS.mono, color: theme.textMute, fontWeight: 500, letterSpacing: 0.4 }}>
          {`in 0:${remaining.toString().padStart(2, '0')}`}
        </span>
      )}
    </button>
  );
}

function ConfirmDone({ theme, title, body, onBack }) {
  return (
    <Screen theme={theme} padTop={0} padBottom={40}>
      <NavBar theme={theme} title="Done" onBack={onBack}/>
      <div style={{ padding: '40px 16px 0', textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 32, margin: '0 auto 18px',
          background: `${theme.positive}18`, color: theme.positive,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Ico.check size={28} sw={2.4}/></div>
        <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text }}>{title}</div>
        <div style={{ fontSize: 13, color: theme.textDim, marginTop: 8, padding: '0 24px', lineHeight: 1.55 }}>{body}</div>
        <button onClick={onBack} style={{
          marginTop: 28, background: theme.text, color: theme.bg,
          border: 'none', borderRadius: 16,
          padding: '14px 28px',
          fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600,
          cursor: 'pointer',
        }}>Back to Personal info</button>
      </div>
    </Screen>
  );
}

function PiLabel({ theme, children }) {
  return <div style={{
    fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1, textTransform: 'uppercase',
    color: theme.textMute,
  }}>{children}</div>;
}

function UAEFlag() {
  return (
    <svg width="20" height="14" viewBox="0 0 20 14" style={{ borderRadius: 2, flexShrink: 0, display: 'block' }}>
      <rect x="5" y="0"  width="15" height="4.67" fill="#00843D"/>
      <rect x="5" y="4.67" width="15" height="4.66" fill="#FFFFFF"/>
      <rect x="5" y="9.33" width="15" height="4.67" fill="#000000"/>
      <rect x="0" y="0"  width="5"  height="14"   fill="#CE1126"/>
    </svg>
  );
}

function maskEmail(addr) {
  const [u, d] = addr.split('@');
  if (!u || !d) return addr;
  const head = u.slice(0, 2);
  return `${head}${'•'.repeat(Math.max(0, u.length - 2))}@${d}`;
}

Object.assign(window, { SettingsPersonalInfoScreen });
