/* Login + Sign up — toggleable on the same page */
const { useState: aUseState } = React;

function AuthPage() {
  const isSignup = (window.location.hash.replace(/^#\/?/, '').split('?')[0]) === 'signup';
  const [mode, setMode] = aUseState(isSignup ? 'signup' : 'login');
  const [step, setStep] = aUseState(0);
  const [form, setForm] = aUseState({ email: '', dealer: '', cars: '', state: 'CA', name: '' });
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  return (
    <div className="m-auth" style={{ minHeight: 'calc(100vh - 56px)', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
      {/* Marketing column */}
      <div className="m-auth-marketing" style={{
        background: 'var(--ink)',
        color: 'var(--paper)',
        padding: '64px 56px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.06,
          backgroundImage: 'linear-gradient(0deg, transparent 49%, var(--paper) 49%, var(--paper) 51%, transparent 51%)',
          backgroundSize: '100% 80px' }}/>
        <div style={{ position: 'relative' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', opacity: 0.6 }}>FILE NO. 2026-LC</div>
          <div className="display" style={{ fontSize: 28, marginTop: 16 }}>Lot Copilot</div>
        </div>
        <div style={{ position: 'relative' }}>
          <h1 className="display" style={{ fontSize: 'clamp(40px, 4.5vw, 72px)', lineHeight: 0.98, letterSpacing: '-0.03em' }}>
            Five minutes today.<br/>
            <span className="serif" style={{ fontStyle: 'italic', fontWeight: 400 }}>Sleep tonight.</span>
          </h1>
          <ul style={{ listStyle: 'none', padding: 0, margin: '32px 0 0', display: 'grid', gap: 10 }}>
            {[
              'WISP generated in 25 questions',
              '4-year communication vault',
              'Nightly listing scanner · 5 channels',
              'Insurance-ready PDF on the 1st',
            ].map((b, i) => (
              <li key={i} style={{ display: 'flex', gap: 12, fontSize: 14, opacity: 0.9 }}>
                <span style={{ color: 'var(--signal)' }}>→</span>{b}
              </li>
            ))}
          </ul>
        </div>
        <div style={{ position: 'relative' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.06em', opacity: 0.5, display: 'flex', justifyContent: 'space-between' }}>
            <span>SOC 2 TYPE II · IN PROGRESS</span>
            <span>ENCRYPTED AT REST</span>
          </div>
        </div>
      </div>

      {/* Form column */}
      <div style={{ padding: '64px 56px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{ maxWidth: 440, width: '100%' }}>
          {/* Toggle */}
          <div style={{ display: 'flex', borderBottom: '1px solid var(--rule)', marginBottom: 32 }}>
            {[['login', 'Sign in'], ['signup', 'Start trial']].map(([k, l]) => (
              <button key={k} onClick={() => { setMode(k); setStep(0); }} style={{
                padding: '10px 0', marginRight: 24,
                fontSize: 13,
                color: mode === k ? 'var(--ink)' : 'var(--ink-3)',
                borderBottom: mode === k ? '2px solid var(--ink)' : '2px solid transparent',
                marginBottom: -1,
              }}>{l}</button>
            ))}
          </div>

          {mode === 'login' ? (
            <LoginForm/>
          ) : (
            <SignupForm step={step} setStep={setStep} form={form} update={update}/>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 16 }}>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 6 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{hint}</div>}
    </label>
  );
}

function inputStyle() {
  return {
    width: '100%', background: 'var(--paper-2)', border: '1px solid var(--rule-strong)',
    padding: '11px 12px', fontSize: 14, color: 'var(--ink)', outline: 'none', borderRadius: 0,
  };
}

function LoginForm() {
  return (
    <div>
      <h2 className="display" style={{ fontSize: 36, lineHeight: 1 }}>Welcome back.</h2>
      <p style={{ color: 'var(--ink-2)', marginTop: 8 }}>Sign in to your dealership.</p>
      <div style={{ marginTop: 28 }}>
        <Field label="EMAIL"><input type="email" placeholder="janelle@sunrisemotors.com" style={inputStyle()}/></Field>
        <Field label="PASSWORD"><input type="password" placeholder="••••••••••" style={inputStyle()}/></Field>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
          <label style={{ fontSize: 12, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="checkbox" defaultChecked/> Remember this device
          </label>
          <a href="#/" className="mono" style={{ fontSize: 11, letterSpacing: '0.06em', color: 'var(--ink-3)' }}>FORGOT PASSWORD?</a>
        </div>
        <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 24 }} onClick={() => go('dashboard')}>
          Sign in &nbsp;→
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '24px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'var(--rule)' }}/>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.08em' }}>OR</span>
          <div style={{ flex: 1, height: 1, background: 'var(--rule)' }}/>
        </div>
        <button className="btn btn--ghost" style={{ width: '100%', justifyContent: 'center' }}>Sign in with Google</button>
        <p style={{ textAlign: 'center', color: 'var(--ink-3)', fontSize: 12, marginTop: 24 }}>
          New here? <a href="#/signup" onClick={(e) => { e.preventDefault(); go('signup'); }} style={{ textDecoration: 'underline' }}>Start a 14-day trial</a>.
        </p>
      </div>
    </div>
  );
}

function SignupForm({ step, setStep, form, update }) {
  const steps = [
    {
      title: 'Start your trial.',
      sub: 'Fourteen days. No credit card. Cancel in two clicks.',
      content: (
        <div>
          <Field label="DEALERSHIP NAME"><input value={form.dealer} onChange={e => update('dealer', e.target.value)} placeholder="Sunrise Motors" style={inputStyle()}/></Field>
          <div className="m-signup-row" style={{ display: 'grid', gridTemplateColumns: '1fr 120px', gap: 12 }}>
            <Field label="CARS ON LOT"><input value={form.cars} onChange={e => update('cars', e.target.value)} placeholder="22" style={inputStyle()}/></Field>
            <Field label="STATE">
              <select value={form.state} onChange={e => update('state', e.target.value)} style={inputStyle()}>
                {['CA', 'TX', 'FL', 'AZ', 'NV', 'OR', 'WA', 'OTHER'].map(s => <option key={s}>{s}</option>)}
              </select>
            </Field>
          </div>
          <Field label="YOUR NAME"><input value={form.name} onChange={e => update('name', e.target.value)} placeholder="Janelle Kim" style={inputStyle()}/></Field>
          <Field label="WORK EMAIL"><input type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="janelle@sunrisemotors.com" style={inputStyle()}/></Field>
        </div>
      ),
    },
    {
      title: 'A few quick yes-or-no\'s.',
      sub: 'These set up your WISP intake. You can change anything later.',
      content: (
        <div style={{ display: 'grid', gap: 14 }}>
          {[
            ['Do you finance any of your cars (BHPH or third-party)?', 'q1'],
            ['Do you advertise inventory on Google Vehicle Listing Ads?', 'q2'],
            ['Do you collect customer SSNs or driver-license numbers?', 'q3'],
            ['Do you have employees other than yourself on the lot?', 'q4'],
          ].map(([q, k]) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, alignItems: 'center', padding: '14px 16px', border: '1px solid var(--rule)', background: 'var(--paper-2)' }}>
              <span style={{ fontSize: 13 }}>{q}</span>
              <div style={{ display: 'flex', gap: 6 }}>
                {['Yes', 'No'].map(opt => (
                  <button key={opt} onClick={() => update(k, opt)} className="btn btn--sm btn--ghost" style={{ borderColor: form[k] === opt ? 'var(--ink)' : 'var(--rule-strong)', background: form[k] === opt ? 'var(--ink)' : 'transparent', color: form[k] === opt ? 'var(--paper)' : 'var(--ink)' }}>
                    {opt}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      ),
    },
    {
      title: 'You\'re in.',
      sub: 'We\'re generating your dashboard now. This usually takes about ten seconds.',
      content: (
        <div style={{ padding: '24px 0' }}>
          {['Pulling listings from your website + ad channels…', 'Drafting your WISP from intake answers…', 'Setting retention windows on email + SMS archives…'].map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderBottom: i < 2 ? '1px solid var(--rule)' : 0 }}>
              <span className="dot dot--ok" style={{ animation: `pulse 1.4s ${i * 0.4}s infinite` }}/>
              <span style={{ fontSize: 13 }}>{t}</span>
            </div>
          ))}
          <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 28 }} onClick={() => go('dashboard')}>
            Open dashboard &nbsp;→
          </button>
          <style>{`@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.4 } }`}</style>
        </div>
      ),
    },
  ];

  const cur = steps[step];

  return (
    <div>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 12 }}>
        STEP {String(step + 1).padStart(2, '0')} / {String(steps.length).padStart(2, '0')}
      </div>
      <h2 className="display" style={{ fontSize: 36, lineHeight: 1 }}>{cur.title}</h2>
      <p style={{ color: 'var(--ink-2)', marginTop: 8 }}>{cur.sub}</p>
      {/* Progress */}
      <div style={{ display: 'flex', gap: 4, marginTop: 18, marginBottom: 24 }}>
        {steps.map((_, i) => (
          <div key={i} style={{ flex: 1, height: 3, background: i <= step ? 'var(--ink)' : 'var(--rule)' }}/>
        ))}
      </div>
      {cur.content}
      {step < steps.length - 1 && (
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24 }}>
          <button className="btn btn--ghost" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0} style={{ opacity: step === 0 ? 0.4 : 1 }}>
            Back
          </button>
          <button className="btn" onClick={() => setStep(step + 1)}>
            Continue &nbsp;→
          </button>
        </div>
      )}
    </div>
  );
}

window.AuthPage = AuthPage;
