// rwic-auth.jsx — Setup wizard + PIN login.
// The setup wizard is shown the FIRST time the tablet boots; once admin sets
// the company config + PIN, every subsequent boot goes to PIN login.
//
// For the demo the entry point can flip between 'login' (default) and 'setup'
// via the Tweaks panel.

// ─── Common chrome — RailFlagsPro mark in the corner ───────────
function AuthShell({ children, eyebrow, title, subtitle, step, totalSteps }) {
  const { tweaks } = useTweakValues();
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background:
        'radial-gradient(1100px 700px at 20% -10%, rgba(229,91,19,0.10), transparent 60%),' +
        'radial-gradient(900px 600px at 90% 110%, rgba(29,111,184,0.08), transparent 65%),' +
        'var(--paper)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '40px 60px',
      overflow: 'hidden',
    }}>
      {/* Brand strip top-left */}
      <div style={{ position: 'absolute', top: 22, left: 28, display: 'flex', alignItems: 'center', gap: 12 }}>
        <Mark size={36} hideText />
        <div>
          <div style={{ fontWeight: 700, fontSize: 16, letterSpacing: -0.2 }}>{tweaks.companyName}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>{tweaks.tagline}</div>
        </div>
      </div>

      {/* Build / version bottom-right */}
      <div style={{
        position: 'absolute', bottom: 22, right: 28,
        fontSize: 11, color: 'var(--muted-2)', fontFamily: 'var(--font-mono)',
      }}>
        TABLET v3.2.1 · {RWIC_USER.badge}
      </div>

      {/* Card */}
      <div style={{
        background: 'var(--panel)',
        border: '1px solid var(--line)',
        borderRadius: 22,
        boxShadow: 'var(--shadow-lg)',
        width: 560, padding: '38px 44px 32px',
        position: 'relative',
      }}>
        {step != null && totalSteps != null && (
          <div style={{ display: 'flex', gap: 6, marginBottom: 22 }}>
            {Array.from({ length: totalSteps }).map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 4, borderRadius: 2,
                background: i < step ? 'var(--accent)' : 'var(--line-strong)',
                transition: 'background 200ms ease',
              }} />
            ))}
          </div>
        )}
        {eyebrow && <div className="eyebrow" style={{ marginBottom: 8 }}>{eyebrow}</div>}
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5, marginBottom: 6 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 14, color: 'var(--muted)', marginBottom: 22, lineHeight: 1.5 }}>{subtitle}</div>}
        {children}
      </div>
    </div>
  );
}

// ─── PIN Login ─────────────────────────────────────────────────
function PinLogin() {
  const { login } = useApp();
  const { tweaks } = useTweakValues();
  const [pin, setPin] = useState('');
  const [err, setErr] = useState(false);
  const [shake, setShake] = useState(false);

  const press = (d) => {
    setErr(false);
    if (d === 'DEL') { setPin(p => p.slice(0, -1)); return; }
    if (pin.length >= 6) return;
    const np = pin + d;
    setPin(np);
    if (np.length === 4) {
      // Try login at 4 digits — both employee and master PINs are 4 digits
      setTimeout(() => {
        if (!login(np)) {
          setErr(true);
          setShake(true);
          setTimeout(() => { setShake(false); setPin(''); }, 600);
        }
      }, 120);
    }
  };

  const isMasterTry = pin === '8282';

  return (
    <AuthShell
      eyebrow="EMPLOYEE SIGN-IN"
      title="Enter your PIN"
      subtitle={`Use the 4-digit PIN issued to your ${tweaks.companyName} badge.`}
    >
      <div style={{ display: 'flex', justifyContent: 'center', gap: 14, marginBottom: 24, transform: shake ? 'translateX(0)' : 'translateX(0)', animation: shake ? 'shake 0.55s ease' : 'none' }}>
        {[0, 1, 2, 3].map(i => {
          const filled = i < pin.length;
          return (
            <div key={i} style={{
              width: 56, height: 64, borderRadius: 14,
              background: filled ? (err ? 'var(--bad-soft)' : 'var(--panel-2)') : 'transparent',
              border: `1.5px solid ${err ? 'var(--bad)' : (filled ? 'var(--accent)' : 'var(--line-strong)')}`,
              display: 'grid', placeItems: 'center',
              transition: 'all 160ms ease',
            }}>
              {filled && (
                <div style={{
                  width: 14, height: 14, borderRadius: '50%',
                  background: err ? 'var(--bad)' : 'var(--accent)',
                }} />
              )}
            </div>
          );
        })}
      </div>
      {err && (
        <div style={{ textAlign: 'center', color: 'var(--bad)', fontSize: 13, fontWeight: 500, marginTop: -10, marginBottom: 10 }}>
          PIN not recognized. Try again.
        </div>
      )}

      {/* Numeric keypad — touch-friendly */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
        marginTop: 6,
      }}>
        {['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', 'DEL'].map((d, i) => {
          if (d === '') return <div key={i} />;
          return (
            <button key={i} onClick={() => press(d)} style={{
              height: 64, borderRadius: 14, border: '1px solid var(--line)',
              background: d === 'DEL' ? 'var(--panel-2)' : 'var(--panel)',
              fontSize: d === 'DEL' ? 14 : 24, fontWeight: 600,
              fontFamily: d === 'DEL' ? 'var(--font-sans)' : 'var(--font-mono)',
              color: 'var(--text)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              transition: 'all 100ms ease',
            }}
              onMouseDown={(e) => e.currentTarget.style.transform = 'translateY(1px)'}
              onMouseUp={(e) => e.currentTarget.style.transform = 'translateY(0)'}
            >
              {d === 'DEL' ? <><IconChevronLeft size={16} /> Delete</> : d}
            </button>
          );
        })}
      </div>

      <div style={{ textAlign: 'center', marginTop: 22, fontSize: 12, color: 'var(--muted)' }}>
        Forgot PIN? Contact your dispatcher · <span className="mono">1-800-555-7411</span>
      </div>
      <div style={{ textAlign: 'center', marginTop: 6, fontSize: 11, color: 'var(--muted-2)' }}>
        Demo PIN: <span className="mono" style={{ color: 'var(--accent)' }}>{RWIC_USER.pin}</span>
        {' · '}
        Master / diagnostic: <span className="mono" style={{ color: 'var(--bad)' }}>8282</span>
      </div>
    </AuthShell>
  );
}

// ─── Setup Wizard (admin first-boot) ───────────────────────────
function SetupWizard() {
  const { setAuthStage } = useApp();
  const { tweaks } = useTweakValues();
  const [step, setStep] = useState(1);
  const [f, setF] = useState({
    companyName: tweaks.companyName,
    tagline: 'RWIC Field Operations',
    accent: tweaks.accent,
    adminName: '',
    adminPin: '',
    confirmPin: '',
  });
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const [err, setErr] = useState('');

  const PRESETS = [
    { name: 'Safety Orange', v: '#E55B13' },
    { name: 'Rail Blue',     v: '#1D6FB8' },
    { name: 'Signal Green',  v: '#137C50' },
    { name: 'Boxcar',        v: '#7C2D12' },
  ];

  const finish = () => {
    if (f.adminPin.length < 4) { setErr('PIN must be at least 4 digits'); return; }
    if (f.adminPin !== f.confirmPin) { setErr('PINs do not match'); return; }
    setAuthStage('login');
  };

  if (step === 1) return (
    <AuthShell eyebrow="STEP 1 OF 3 · COMPANY" title="Set up this tablet" subtitle="A few details so the app feels like yours. You can change these later." step={1} totalSteps={3}>
      <Field label="Company name" required>
        <Input value={f.companyName} onChange={e => set('companyName', e.target.value)} placeholder="e.g. Cascade Rail Safety LLC" />
      </Field>
      <Field label="Tagline / department">
        <Input value={f.tagline} onChange={e => set('tagline', e.target.value)} />
      </Field>
      <Button variant="primary" size="lg" disabled={!f.companyName.trim()} onClick={() => setStep(2)} style={{ width: '100%', marginTop: 8 }} iconRight={<IconArrowRight size={16} />}>
        Continue
      </Button>
    </AuthShell>
  );

  if (step === 2) return (
    <AuthShell eyebrow="STEP 2 OF 3 · BRAND COLOR" title="Pick an accent color" subtitle="High-vis colors used through the app — applied immediately." step={2} totalSteps={3}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 18 }}>
        {PRESETS.map(p => (
          <button key={p.v} type="button" onClick={() => set('accent', p.v)} style={{
            background: 'var(--panel)',
            border: `2px solid ${f.accent === p.v ? p.v : 'var(--line)'}`,
            borderRadius: 12, padding: '14px 10px', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            transition: 'border-color 160ms ease',
          }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: p.v }} />
            <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)' }}>{p.name}</span>
          </button>
        ))}
      </div>

      {/* Preview */}
      <div style={{
        padding: 18, borderRadius: 12,
        background: 'var(--panel-2)', border: '1px solid var(--line)',
        marginBottom: 18, display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 10,
          background: 'var(--text)', color: '#fff',
          display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 15,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ position: 'absolute', inset: 0, background: f.accent, clipPath: 'polygon(0 100%, 100% 100%, 100% 60%, 0 92%)' }} />
          <span style={{ position: 'relative', zIndex: 1 }}>{f.companyName.split(/\s+/).map(w => w[0]).join('').slice(0, 2).toUpperCase()}</span>
        </div>
        <div>
          <div style={{ fontWeight: 700, fontSize: 16 }}>{f.companyName}</div>
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>{f.tagline}</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <Button variant="secondary" onClick={() => setStep(1)} icon={<IconChevronLeft size={16} />} style={{ flex: 1 }}>Back</Button>
        <Button variant="primary" onClick={() => setStep(3)} iconRight={<IconArrowRight size={16} />} style={{ flex: 2 }}>Continue</Button>
      </div>
    </AuthShell>
  );

  return (
    <AuthShell eyebrow="STEP 3 OF 3 · ADMIN PIN" title="Create an admin PIN" subtitle="Used to manage tablet settings. Employees get their own PIN issued separately." step={3} totalSteps={3}>
      <Field label="Admin name">
        <Input value={f.adminName} onChange={e => set('adminName', e.target.value)} placeholder="Your name" />
      </Field>
      <Field label="Admin PIN (4–6 digits)" required>
        <Input type="password" value={f.adminPin} onChange={e => set('adminPin', e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="••••" />
      </Field>
      <Field label="Confirm PIN" required error={err && err.includes('match') ? err : null}>
        <Input type="password" value={f.confirmPin} onChange={e => set('confirmPin', e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="••••" />
      </Field>
      {err && !err.includes('match') && (
        <div style={{ color: 'var(--bad)', fontSize: 13, marginTop: -8, marginBottom: 10 }}>{err}</div>
      )}

      <div style={{
        background: 'var(--accent-soft)', color: 'var(--accent-deep)',
        padding: '10px 14px', borderRadius: 10, fontSize: 13, marginBottom: 16, lineHeight: 1.55,
      }}>
        <strong>Heads up — </strong> this tablet stays at the job site. Each RWIC employee
        gets a separate 4-digit PIN. Contractor crew members do <em>not</em> sign in;
        they only sign briefings as proof of attendance.
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <Button variant="secondary" onClick={() => setStep(2)} icon={<IconChevronLeft size={16} />} style={{ flex: 1 }}>Back</Button>
        <Button variant="primary" onClick={finish} icon={<IconCheck size={16} />} style={{ flex: 2 }}>Launch app</Button>
      </div>
    </AuthShell>
  );
}

Object.assign(window, { AuthShell, PinLogin, SetupWizard });
