// Pocket Marshal — username + password login / first-run account setup

async function pmHashPw(pw, salt) {
  const data = new TextEncoder().encode(salt + ':' + pw);
  const buf = await crypto.subtle.digest('SHA-256', data);
  return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

function PMField({ theme, label, value, onChange, type, placeholder, autoFocus, onEnter, autoComplete, name }) {
  const [show, setShow] = React.useState(false);
  const isPw = type === 'password';
  return (
    <div style={{ textAlign: 'left', marginBottom: 12 }}>
      <label style={{ display: 'block', fontWeight: 700, fontSize: '0.8em', letterSpacing: '0.04em', textTransform: 'uppercase', color: theme.muted, marginBottom: 6 }}>
        {label}
      </label>
      <div style={{ position: 'relative' }}>
        <input
          value={value}
          type={isPw && !show ? 'password' : 'text'}
          name={name}
          autoComplete={autoComplete}
          autoFocus={autoFocus}
          placeholder={placeholder}
          onChange={(e) => onChange(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter' && onEnter) onEnter(); }}
          style={{
            width: '100%', boxSizing: 'border-box', border: `2px solid ${theme.line}`, borderRadius: 14,
            padding: isPw ? '14px 76px 14px 16px' : '14px 16px', font: 'inherit', fontSize: '1.05em', fontWeight: 600,
            color: theme.ink, background: theme.paper, outline: 'none', minHeight: 56,
          }}
          onFocus={(e) => { e.target.style.borderColor = theme.focusRing; }}
          onBlur={(e) => { e.target.style.borderColor = theme.line; }} />
        {isPw && (
          <button type="button" onClick={() => setShow(!show)} style={{
            position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
            minHeight: 40, padding: '0 12px', borderRadius: 10, border: 'none',
            background: 'transparent', color: theme.muted, font: 'inherit', fontWeight: 700, fontSize: '0.82em', cursor: 'pointer',
          }}>{show ? 'Hide' : 'Show'}</button>
        )}
      </div>
    </div>
  );
}

// First-run: create account. After that: sign in.
function PMLock({ theme, t, savedAuth, onComplete, onReset }) {
  const isSetup = !savedAuth;
  const [name, setName] = React.useState('');
  const [username, setUsername] = React.useState(savedAuth ? savedAuth.username || '' : '');
  const [pw, setPw] = React.useState('');
  const [access, setAccess] = React.useState(() => { try { return localStorage.getItem('pm_access') || ''; } catch (e) { return ''; } });
  const [pw2, setPw2] = React.useState('');
  const [stay, setStay] = React.useState(true);
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const fail = (msg) => { setError(msg); setBusy(false); };

  const submit = async () => {
    if (busy) return;
    setError('');
    if (isSetup) {
      if (!name.trim()) return fail('Add your name so Marshal knows who you are.');
      if (!access.trim()) return fail("Enter your department's access code — your Fire Marshal has it.");
      if (username.trim().length < 3 || (username.includes('@') && !/^\S+@\S+\.\S+$/.test(username.trim()))) return fail('Enter a valid email (or username).');
      if (pw.length < 6) return fail('Password needs at least 6 characters.');
      if (pw !== pw2) return fail("Those passwords don't match.");
      setBusy(true);
      try { localStorage.setItem('pm_access', access.trim()); } catch (e) { /* noop */ }
      try {
        const salt = Math.random().toString(36).slice(2, 12);
        const hash = await pmHashPw(pw, salt);
        onComplete({ name: name.trim(), username: username.trim(), salt, hash, stay });
      } catch (e) { fail('Something went wrong — try again.'); }
      return;
    }
    // sign in
    if (!username.trim() || !pw) return fail('Enter your username and password.');
    setBusy(true);
    try {
      if (username.trim().toLowerCase() !== String(savedAuth.username || '').toLowerCase()) {
        return fail("That email or username doesn't match this device.");
      }
      const hash = await pmHashPw(pw, savedAuth.salt);
      if (hash !== savedAuth.hash) return fail('Wrong password — give it another shot.');
      onComplete({ stay });
    } catch (e) { fail('Something went wrong — try again.'); }
  };

  return (
    <div data-screen-label="Login screen" style={{
      flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '32px 24px', boxSizing: 'border-box', textAlign: 'center', overflowY: 'auto',
    }}>
      <MarshalAvatar styleKind={t.avatar === 'none' ? 'badge' : t.avatar} size={84} float={t.avatar === 'mascot'} />
      <h1 style={{ margin: '20px 0 4px', fontSize: '1.7em', fontWeight: 700, color: theme.ink, letterSpacing: '-0.02em' }}>Pocket Marshal</h1>
      <p style={{ margin: '0 0 6px', color: theme.muted, fontWeight: 600, fontSize: '0.92em' }}>City of Winter Haven · Fire Prevention</p>
      <p style={{ margin: '10px 0 18px', color: error ? theme.dangerInk : theme.ink, fontWeight: 650, fontSize: '0.98em', minHeight: 24, maxWidth: 340, lineHeight: 1.4, animation: error ? 'pm-shake 0.4s' : 'none' }}>
        {error || (isSetup ? 'Set up this device for the field.' : `Welcome back${savedAuth.name ? ', ' + savedAuth.name.split(' ')[0] : ''}. Sign in to pick up where you left off.`)}
      </p>

      <div style={{ width: '100%', maxWidth: 340 }}>
        {isSetup && (
          <PMField theme={theme} label="Your name" value={name} onChange={setName}
            placeholder="e.g. Jeremias Alvarez" autoFocus autoComplete="name" name="name" />
        )}
        <PMField theme={theme} label="Email or username" value={username} onChange={setUsername}
          placeholder="e.g. jalvarez@mywinterhaven.com" autoFocus={!isSetup && !username} autoComplete="username" name="username" />
        <PMField theme={theme} label="Password" value={pw} onChange={setPw} type="password"
          placeholder={isSetup ? 'At least 6 characters' : 'Your password'}
          autoComplete={isSetup ? 'new-password' : 'current-password'} name="password"
          onEnter={isSetup ? undefined : submit} />
        {isSetup && (
          <PMField theme={theme} label="Confirm password" value={pw2} onChange={setPw2} type="password"
            placeholder="Same password again" autoComplete="new-password" name="password2" />
        )}
        {isSetup && (
          <PMField theme={theme} label="Department access code" value={access} onChange={setAccess}
            placeholder="From your Fire Marshal" autoComplete="off" name="access" onEnter={submit} />
        )}

        <button onClick={submit} disabled={busy} style={{
          width: '100%', marginTop: 4, minHeight: 58, borderRadius: 14, border: 'none',
          background: theme.cta, color: theme.ctaInk, opacity: busy ? 0.7 : 1,
          font: 'inherit', fontWeight: 700, fontSize: '1.08em', cursor: busy ? 'default' : 'pointer',
        }}>{busy ? 'One sec…' : isSetup ? 'Create account' : 'Sign in'}</button>

        <label style={{
          display: 'inline-flex', alignItems: 'center', gap: 9, marginTop: 16, cursor: 'pointer',
          color: theme.muted, fontWeight: 600, fontSize: '0.9em', minHeight: 44,
        }}>
          <input type="checkbox" checked={stay} onChange={(e) => setStay(e.target.checked)}
            style={{ width: 20, height: 20, accentColor: theme.heroAccent, cursor: 'pointer' }} />
          Stay signed in on this device
        </label>

        {!isSetup && onReset && (
          <div style={{ marginTop: 6 }}>
            <button onClick={() => {
              if (window.confirm('Create a new account on this device? The current account will be removed. Saved conversations stay on the device.')) onReset();
            }} style={{
              background: 'none', border: 'none', font: 'inherit', cursor: 'pointer',
              color: theme.heroAccent, fontWeight: 700, fontSize: '0.88em', minHeight: 44, padding: '0 10px',
              textDecoration: 'underline', textUnderlineOffset: '3px',
            }}>Not {savedAuth.name ? savedAuth.name.split(' ')[0] : 'you'}? Create a new account</button>
          </div>
        )}
      </div>

      <p style={{ margin: '18px 0 0', color: theme.muted, fontSize: '0.76em', fontWeight: 500, opacity: 0.8, maxWidth: 340, lineHeight: 1.45 }}>
        Your account, conversations, and settings are stored only on this device.
      </p>
    </div>
  );
}

// One-time acknowledgment after account setup — “Marshal advises; the inspector decides.”
function PMAck({ theme, t, inspectorName, onAgree }) {
  const points = [
    {
      title: 'Marshal is guidance — not the code.',
      body: 'Answers come with chapter-and-section citations so you can verify them against your department’s adopted code. The code itself is always the authority.',
    },
    {
      title: 'You make the call.',
      body: 'Marshal suggests and explains, but every inspection decision — pass, conditions, fail — belongs to you and your department.',
    },
    {
      title: 'Big calls go up the chain.',
      body: 'When something is ambiguous or precedent-setting, Marshal will point you to your Fire Marshal — that’s by design.',
    },
  ];
  return (
    <div data-screen-label="Acknowledgment screen" style={{
      flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '32px 24px', boxSizing: 'border-box', overflowY: 'auto',
    }}>
      <MarshalAvatar styleKind={t.avatar === 'none' ? 'badge' : t.avatar} size={72} />
      <h1 style={{ margin: '18px 0 4px', fontSize: '1.45em', fontWeight: 700, color: theme.ink, letterSpacing: '-0.02em', textAlign: 'center' }}>
        Before your first inspection{inspectorName ? ', ' + inspectorName.split(' ')[0] : ''}
      </h1>
      <p style={{ margin: '0 0 22px', color: theme.muted, fontWeight: 600, fontSize: '0.92em', textAlign: 'center' }}>
        Three things to agree on — then we ride.
      </p>
      <div style={{ width: '100%', maxWidth: 400, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {points.map((p, i) => (
          <div key={i} style={{
            display: 'flex', gap: 14, alignItems: 'flex-start', textAlign: 'left',
            background: theme.paper, border: `1.5px solid ${theme.line}`, borderRadius: 16, padding: '16px 18px',
          }}>
            <div aria-hidden="true" style={{
              flexShrink: 0, width: 28, height: 28, borderRadius: '50%', marginTop: 2,
              background: theme.heroAccent, color: theme.ctaInk,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 800, fontSize: '0.85em',
            }}>{i + 1}</div>
            <div>
              <div style={{ fontWeight: 750, color: theme.ink, fontSize: '0.98em', marginBottom: 3 }}>{p.title}</div>
              <div style={{ color: theme.muted, fontWeight: 500, fontSize: '0.88em', lineHeight: 1.45 }}>{p.body}</div>
            </div>
          </div>
        ))}
        <button onClick={onAgree} style={{
          width: '100%', marginTop: 8, minHeight: 58, borderRadius: 14, border: 'none',
          background: theme.cta, color: theme.ctaInk,
          font: 'inherit', fontWeight: 700, fontSize: '1.05em', cursor: 'pointer',
        }}>I understand — Marshal advises, I decide</button>
      </div>
    </div>
  );
}

Object.assign(window, { PMLock, PMAck, pmHashPw });
