/* ============================================================================
   PURE — LOGIN · SESSION · MFA front door + per-user welcome portal (D-113)
   Identify → verify (passwordless code / passkey · 2FA) → personalized welcome
   → hand off into the signed-in person's role-adaptive hub (home.html).
   Self-contained; reuses the brand tokens. Maps each persona to the shell's
   View-as identity so the whole site is already theirs on arrival.
   ========================================================================== */
const { useState, useRef, useEffect } = React;

/* personas mirror the shell's ROLES + named USERS; waiting[] = what's live for
   them right now, so the first screen feels personal and useful. */
const PERSONAS = [
  { rid:'agent', uid:'u_sara', name:'Sara Lin', email:'sara@acquistorealestate.com', role:'Agent', org:'Acquisto Real Estate', oinit:'AR', init:'SL',
    waiting:[['◷','4 active transactions','Oak Hollow closes May 9','var(--navy)'],['☎','9 leads in your queue','3 new from Zillow today','var(--gold-deep)'],['✎','2 forms to send','Pure Sign · ready','var(--green)']] },
  { rid:'broker', uid:'u_marcus', name:'Marcus Acquisto', email:'marcus@acquistorealestate.com', role:'Broker Admin', org:'Acquisto Real Estate', oinit:'AR', init:'MA',
    waiting:[['$','$214k GCI this month','3 CDAs awaiting approval','var(--gold-deep)'],['⚖','5 compliance items','1 license pending · Diego','var(--orange)'],['⬢','New agent onboarding','Diego Ramos · 60%','var(--navy)']] },
  { rid:'isa', uid:'', name:'Noah Brandt', email:'noah@acquistorealestate.com', role:'Inside Sales', org:'Acquisto Real Estate', oinit:'AR', init:'NB',
    waiting:[['☎','14 new leads today','avg speed-to-lead 2m 40s','var(--gold-deep)'],['◉','6 qualified','route to agents','var(--green)']] },
  { rid:'teamlead', uid:'u_renee', name:'Renee Vance', email:'renee@acquistorealestate.com', role:'Team Lead', org:'Acquisto Group', oinit:'AG', init:'RV',
    waiting:[['◫','Team production','Tara is top producer','var(--navy)'],['⬢','2 onboarding','review automations','var(--gold-deep)']] },
  { rid:'client', uid:'u_jordan', name:'Jordan Huff', email:'jordan.huff@gmail.com', role:'Buyer', org:'Acquisto Real Estate', oinit:'AR', init:'JH',
    waiting:[['⌂','1209 Oak Hollow Dr','Under contract · closes May 9','var(--navy)'],['✎','1 document to sign','Closing Disclosure','var(--green)'],['◷','Next: final walkthrough','May 8 · 5:00p','var(--gold-deep)']] },
  { rid:'mls', uid:'u_dana', name:'Dana Pruitt', email:'dana@ntreis.net', role:'MLS Staff', org:'NTREIS', oinit:'NT', init:'DP',
    waiting:[['◈','8,410 active listings','data quality 97%','var(--navy)'],['⤴','Syndication healthy','6 feeds live','var(--green)'],['⬗','New subscriber','Diego Ramos onboarding','var(--gold-deep)']] },
  { rid:'assocadmin', uid:'u_gabriela', name:'Gabriela Soto', email:'gsoto@collinaor.org', role:'Association Admin', org:'Collin County AoR', oinit:'CC', init:'GS',
    waiting:[['◈','1,240 members','dues 92% collected','var(--navy)'],['◇','Education committee','meets Friday','var(--gold-deep)'],['▦','Spring Mixer','92 tickets sold','var(--green)']] },
  { rid:'vendor', uid:'u_devon', name:'Devon Carter', email:'devon@lonestarmedia.co', role:'Vendor', org:'Lone Star Media', oinit:'LS', init:'DC',
    waiting:[['◉','3 open orders','88 Crestview due today','var(--gold-deep)'],['$','$450 pending payout','from Pure Books','var(--green)']] },
  { rid:'pure', uid:'u_mike', name:'Mike Acquisto', email:'mike@puretech.io', role:'Pure Admin', org:'Pure Technologies', oinit:'PT', init:'MA', navy:true,
    waiting:[['✦','42 organizations','$312k MRR','var(--navy)'],['⊕','Platform health','99.98% uptime','var(--green)'],['▦','Admin Hub','run the close-out sweep','var(--gold-deep)']] },
];
const personaByEmail = e => PERSONAS.find(p => p.email.toLowerCase() === e.toLowerCase().trim());

function Brand() {
  return (
    <div className="lg-brand">
      <div className="lg-brand-top">
        <img className="lg-logo" src="/assets/pure-logo-white.png" alt="Pure MLS Technologies" />
        <div className="lg-wm"><span className="a">Pure MLS Technologies</span><span className="b">Sign in</span></div>
      </div>
      <div className="lg-hero">
        <h1>One platform. <em>Your</em> whole business.</h1>
        <p>From the first lead to the closing table — every role, brokerage, association and MLS, on one secure spine.</p>
      </div>
      <div className="lg-feats">
        {[['⊕','Single sign-on, passwordless & passkeys'],['◉','2FA on every account · sessions & devices'],['⬢','You land in a hub built for your role']].map(([i,t]) => (
          <div className="lg-feat" key={t}><span className="fi">{i}</span>{t}</div>
        ))}
      </div>
      <div className="lg-foot">© 2026 Pure MLS Technologies · v4.0 · SOC 2 · TREC-compliant retention</div>
    </div>
  );
}

function MobileLogo() {
  return <div className="lg-mlogo"><img src="/assets/pure-logo.png" alt="Pure" onError={e => { e.target.style.display='none'; }} /><div className="lg-wm" style={{ borderColor:'var(--color-neutral-300)' }}><span className="a" style={{ color:'var(--gold-ink)' }}>Pure MLS Technologies</span><span className="b" style={{ color:'var(--navy)' }}>Sign in</span></div></div>;
}

function App() {
  const [step, setStep] = useState('identify');
  const [email, setEmail] = useState('');
  const [persona, setPersona] = useState(null);
  const [code, setCode] = useState(['', '', '', '', '', '']);
  const codeRefs = [useRef(), useRef(), useRef(), useRef(), useRef(), useRef()];

  const choose = p => { setPersona(p); setEmail(p.email); setStep('verify'); };
  const continueEmail = () => { const p = personaByEmail(email) || PERSONAS[0]; setPersona(p); if (!personaByEmail(email)) setEmail(p.email); setStep('verify'); };

  useEffect(() => { if (step === 'verify' && codeRefs[0].current) codeRefs[0].current.focus(); }, [step]);
  const setDigit = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    setCode(c => { const n = [...c]; n[i] = v; return n; });
    if (v && i < 5) codeRefs[i + 1].current && codeRefs[i + 1].current.focus();
  };
  const onCodeKey = (i, e) => { if (e.key === 'Backspace' && !code[i] && i > 0) codeRefs[i - 1].current && codeRefs[i - 1].current.focus(); };
  const codeComplete = code.every(d => d !== '');
  const verify = () => setStep('welcome');

  const enter = () => {
    try { localStorage.setItem('pure.shell.v1', JSON.stringify({ roleId: persona.rid, userId: persona.uid || '', active: null })); } catch (e) {}
    try { localStorage.setItem('pure.session.v1', JSON.stringify({ email: persona.email, name: persona.name, at: Date.now(), device: 'This device', mfa: true })); } catch (e) {}
    window.location.href = '/home';
  };

  return (
    <div className="lg">
      <Brand />
      <div className="lg-form">
        {step === 'identify' && (
          <div className="lg-card lg-fadein">
            <MobileLogo />
            <div className="lg-eyebrow">Welcome</div>
            <div className="lg-h2">Sign in to Pure</div>
            <div className="lg-sub">Enter your work email — we'll send a one-time code (no password). Single sign-on & passkeys supported.</div>
            <label className="lg-label">Email address</label>
            <input className="lg-input" type="email" value={email} placeholder="you@brokerage.com" autoFocus
              onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === 'Enter' && email && continueEmail()} />
            <button className="lg-btn" disabled={!email} onClick={continueEmail} style={{ opacity: email ? 1 : .5 }}>Continue →</button>
            <div className="lg-or">or choose a demo account</div>
            <div className="lg-accounts">
              {PERSONAS.map(p => (
                <button className="lg-acct" key={p.email} onClick={() => choose(p)}>
                  <span className={'lg-av' + (p.navy ? ' navy' : '')}>{p.init}</span>
                  <span className="lg-acct-tx"><b>{p.name}</b><small>{p.role} · {p.org}</small></span>
                  <span className="lg-acct-go">→</span>
                </button>
              ))}
            </div>
            <div className="lg-secnote"><span className="lock">🔒</span> Acting-as &amp; every sign-in is audit-logged. Sessions and devices are managed in your profile.</div>
          </div>
        )}

        {step === 'verify' && persona && (
          <div className="lg-card lg-fadein">
            <MobileLogo />
            <button className="lg-back" onClick={() => { setStep('identify'); setCode(['','','','','','']); }}>← Use a different account</button>
            <div className="lg-eyebrow">Two-factor authentication</div>
            <div className="lg-h2">Verify it's you</div>
            <div className="lg-sub">We sent a 6-digit code to <b style={{ color:'var(--navy)' }}>{email}</b>. Enter it below, or use a passkey.</div>
            <div className="lg-code">
              {code.map((d, i) => (
                <input key={i} ref={codeRefs[i]} value={d} inputMode="numeric" maxLength={1}
                  onChange={e => setDigit(i, e.target.value)} onKeyDown={e => onCodeKey(i, e)} />
              ))}
            </div>
            <button className="lg-btn gold" onClick={verify} style={{ opacity: codeComplete ? 1 : .55 }} disabled={!codeComplete}>Verify &amp; continue</button>
            <button className="lg-passkey" onClick={verify}><span>⊕</span> Use a passkey instead</button>
            <div className="lg-hint">Didn't get it? <button className="lg-link" onClick={() => {}}>Resend code</button> · <button className="lg-link" onClick={() => setCode(['1','2','3','4','5','6'])}>demo: fill code</button></div>
            <div className="lg-secnote"><span className="lock">🔒</span> This device can be remembered for 30 days. Manage trusted devices &amp; active sessions anytime in Settings.</div>
          </div>
        )}

        {step === 'welcome' && persona && (
          <div className="lg-welcome lg-fadein">
            <div className="lg-worg"><span className="ol">{persona.oinit}</span><span className="ot"><span className="k">{persona.role.includes('Admin') || persona.rid === 'pure' ? 'Organization' : persona.role}</span><span className="n">{persona.org}</span></span></div>
            <div className="lg-wave">👋</div>
            <h2>Welcome back, <em>{persona.name.split(' ')[0]}</em>.</h2>
            <div className="lg-wrole">You're signed in as <b>{persona.role}</b> · {persona.org}. Here's what's waiting for you.</div>
            <div className="lg-waiting">
              {persona.waiting.map((w, i) => (
                <div className="lg-wi" key={i}>
                  <span className="wic" style={{ background: w[3] }}>{w[0]}</span>
                  <span className="lg-wi-tx"><b>{w[1]}</b><small>{w[2]}</small></span>
                  <span className="wgo">→</span>
                </div>
              ))}
            </div>
            <button className="lg-btn" onClick={enter}>Enter Pure →</button>
            <div className="lg-secnote" style={{ justifyContent:'center' }}><span className="lock">🔒</span> Signed in securely · 2FA verified · session started on this device</div>
          </div>
        )}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
