/* ============================================================
 * Login screen — one uniform sign-in for every role.
 *
 * Production pattern (this prototype mirrors it):
 *   User types email + password → backend looks up the account
 *   → routes them to their role's portal. Role is determined
 *   by the account, not chosen by the user. There is NO
 *   "I am a developer / I am a VVB" toggle on the way in.
 *
 * Demo affordance:
 *   A small "Quick demo accounts" panel below the form
 *   auto-fills credentials so the prototype viewer can step
 *   into either persona without leaving the realistic sign-in
 *   surface. The 6 other Pamoja roles are listed but greyed —
 *   they're out of scope for this design pass.
 * ============================================================ */

const DEMO_ACCOUNTS = [
  {
    id: 'developer',
    name: 'Grace Kimani',
    role: 'Project Developer',
    org:  'Pamoja EcoGreen Co-operative',
    email:'grace@ecogreen.co.ke',
    password: 'BambooKenya2026',
    accent: '#F4C300',
  },
  {
    id: 'vvb',
    name: 'Sarah Chen',
    role: 'VVB Auditor',
    org:  'SCS Global Services',
    email:'sarah.chen@scsglobalservices.com',
    password: 'VVB007secure!',
    accent: '#2BC48A',
  },
];

const OTHER_ROLES = [
  { name:'Credit Buyer',     org:'Microsoft Climate Innovation Fund' },
  { name:'Field Agent',      org:'Pamoja field operations · Kenya'   },
  { name:'Farmer / Mkulima', org:'Smallholder participant'           },
  { name:'Biochar Operator', org:'Wamunyu Biochar Co-op'             },
  { name:'National Regulator', org:'Kenya Climate Change Directorate' },
  { name:'Administrator',    org:'Pamoja platform team'              },
];

function LoginScreen({ onSignIn }) {
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [autoFill, setAutoFill] = React.useState(null); // demo persona that just auto-filled
  const [submitting, setSubmitting] = React.useState(false);
  const [showPwd, setShowPwd] = React.useState(false);
  const [error, setError] = React.useState(null);

  const pickDemo = (acct) => {
    setEmail(acct.email);
    setPassword(acct.password);
    setAutoFill(acct);
    setError(null);
  };

  const submit = (e) => {
    e && e.preventDefault();
    setError(null);
    // Look up the account by email — this is what the production
    // backend does. The matched account's role determines routing.
    const account = DEMO_ACCOUNTS.find(a => a.email.toLowerCase() === email.trim().toLowerCase() && a.password === password);
    if (!account) {
      setError(email && password ? 'No account matches those credentials.' : 'Enter email and password.');
      return;
    }
    setSubmitting(true);
    // Brief auth animation, then route by role
    setTimeout(() => onSignIn(account.id, account), 700);
  };

  return (
    <div style={{minHeight:'100vh', display:'flex', background:'#022C28', color:'#fff'}}>
      {/* === Left: brand + value prop =========================== */}
      <div style={{
        flex:1, padding:'48px 56px', display:'flex', flexDirection:'column',
        background:'linear-gradient(160deg, #022C28 0%, #0A3D38 50%, #022C28 100%)',
        position:'relative', overflow:'hidden',
      }}>
        {/* Faint radial accents */}
        <div style={{
          position:'absolute', top:-160, right:-160, width:520, height:520,
          background:'radial-gradient(circle, rgba(244,195,0,0.10) 0%, transparent 60%)',
          pointerEvents:'none',
        }}/>
        <div style={{
          position:'absolute', bottom:-200, left:-100, width:520, height:520,
          background:'radial-gradient(circle, rgba(43,196,138,0.06) 0%, transparent 60%)',
          pointerEvents:'none',
        }}/>

        <a href="https://pamojadmrv.earth" style={{display:'flex', alignItems:'center', gap:12, marginBottom:48, position:'relative', textDecoration:'none', color:'inherit'}}>
          <img src="brand/logo-mark.svg" alt="Pamoja" style={{height:30}}/>
          <span style={{fontSize:16, fontWeight:900, letterSpacing:'-0.01em'}}>Pamoja DMRV</span>
          <span style={{fontSize:11, fontFamily:'JetBrains Mono, monospace', color:'rgba(255,255,255,0.4)', marginLeft:8}}>pamojadmrv.earth</span>
        </a>

        <div style={{maxWidth:520, position:'relative'}}>
          <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.14em', textTransform:'uppercase', color:'#F4C300', marginBottom:10}}>Digital MRV platform</div>
          <h1 style={{fontSize:'clamp(2.4rem, 4.4vw, 3.4rem)', fontWeight:900, letterSpacing:'-0.025em', margin:0, lineHeight:1.05}}>
            Carbon projects, <br/>verified independently.
          </h1>
          <p style={{fontSize:15, color:'rgba(255,255,255,0.65)', lineHeight:1.6, marginTop:18, maxWidth:480}}>
            Pamoja routes Project Developers, VVB Auditors, Buyers, Regulators, and Field Agents into role-scoped portals. One sign-in, one identity — the platform never lets a developer sign off their own project.
          </p>

          <div style={{display:'flex', flexDirection:'column', gap:14, marginTop:36}}>
            {[
              { ic:'shield',    t:'Independent verification',    s:'VVB Auditors operate in a separate portal, with cryptographic separation enforced by role gates.' },
              { ic:'hedera',    t:'Anchored to Hedera',           s:'Every confirm, commit, and sign-off becomes a hash on Hedera testnet topic 0.0.8321350.' },
              { ic:'globe',     t:'6 languages, mobile-first',    s:'EN · SW · FR · ES · PT · IT. Built for field tablets and household phones.' },
            ].map((row, i) => (
              <div key={i} style={{display:'flex', alignItems:'flex-start', gap:14}}>
                <div style={{
                  width:36, height:36, borderRadius:10,
                  background:'rgba(244,195,0,0.10)',
                  display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                }}>
                  <PamojaIcon name={row.ic} size={16} color="#F4C300" stroke={1.7}/>
                </div>
                <div>
                  <div style={{fontSize:13, fontWeight:800, color:'#fff', letterSpacing:'-0.01em'}}>{row.t}</div>
                  <div style={{fontSize:12, color:'rgba(255,255,255,0.55)', marginTop:2, lineHeight:1.5}}>{row.s}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{marginTop:'auto', paddingTop:32, fontSize:11, color:'rgba(255,255,255,0.4)', fontFamily:'JetBrains Mono, monospace', letterSpacing:'0.04em', position:'relative'}}>
          © 2026 Consuming Carbon Corp · 254 Chapman Rd, Ste 208, Newark DE 19702<br/>
          GDPR · POPIA · Kenya DPA 2019
        </div>
      </div>

      {/* === Right: sign-in form ================================ */}
      <div style={{
        width:'min(48%, 560px)', minWidth:420,
        background:'#fff', color:'#022C28',
        padding:'48px 48px 32px',
        display:'flex', flexDirection:'column',
        boxShadow:'-24px 0 80px rgba(0,0,0,0.25)',
      }}>
        <div style={{maxWidth:380, margin:'0 auto', width:'100%', flex:1, display:'flex', flexDirection:'column', justifyContent:'center'}}>
          <div style={{fontSize:11, fontWeight:800, letterSpacing:'0.14em', textTransform:'uppercase', color:'#B8960A', marginBottom:8}}>Welcome back</div>
          <h2 style={{fontSize:28, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', margin:'0 0 8px', lineHeight:1.1}}>
            Sign in to your portal
          </h2>
          <p style={{fontSize:13, color:'#6B7280', margin:'0 0 28px', lineHeight:1.5}}>
            Pamoja routes you based on your account. Project Developers, VVB Auditors, and other roles all sign in here.
          </p>

          <form onSubmit={submit} style={{display:'flex', flexDirection:'column', gap:14}}>
            <Field label="Email">
              <input
                type="email"
                value={email}
                onChange={(e)=>{ setEmail(e.target.value); setAutoFill(null); setError(null); }}
                placeholder="you@your-org.com"
                style={loginInput}
                autoComplete="username"
              />
            </Field>

            <Field label="Password" right={
              <a href="#" onClick={(e)=>e.preventDefault()} style={{fontSize:11, color:'#B8960A', textDecoration:'none', fontWeight:700}}>Forgot?</a>
            }>
              <div style={{position:'relative'}}>
                <input
                  type={showPwd ? 'text' : 'password'}
                  value={password}
                  onChange={(e)=>{ setPassword(e.target.value); setAutoFill(null); setError(null); }}
                  placeholder="••••••••"
                  style={{...loginInput, paddingRight:48}}
                  autoComplete="current-password"
                />
                <button type="button" onClick={()=>setShowPwd(v=>!v)} style={{
                  position:'absolute', right:6, top:'50%', transform:'translateY(-50%)',
                  background:'transparent', border:'none', cursor:'pointer',
                  padding:8, display:'flex', alignItems:'center',
                }}>
                  <PamojaIcon name="eye" size={14} color={showPwd ? '#022C28' : '#9CA3AF'} stroke={1.6}/>
                </button>
              </div>
            </Field>

            {autoFill && (
              <div style={{
                background:'#FFF8E0', border:'1px solid #FDE68A', borderRadius:8,
                padding:'8px 12px', fontSize:11, color:'#7C5104', display:'flex', alignItems:'center', gap:8,
              }}>
                <PamojaIcon name="check" size={12} color="#B8960A" stroke={2.2}/>
                Credentials auto-filled — <b>{autoFill.name}</b> · {autoFill.role}
              </div>
            )}

            {error && (
              <div style={{
                background:'#FEE2E2', border:'1px solid #FCA5A5', borderRadius:8,
                padding:'8px 12px', fontSize:12, color:'#991B1B', display:'flex', alignItems:'center', gap:8,
              }}>
                <PamojaIcon name="alert" size={12} color="#991B1B" stroke={2}/>
                {error}
              </div>
            )}

            <button type="submit" disabled={submitting} style={{
              background: submitting ? '#D4A800' : '#F4C300', color:'#022C28', border:'none',
              borderRadius:10, padding:'13px 18px', minHeight:48,
              fontSize:14, fontWeight:800, cursor: submitting ? 'wait' : 'pointer',
              fontFamily:'inherit', letterSpacing:'0.01em', marginTop:6,
              display:'inline-flex', alignItems:'center', justifyContent:'center', gap:10,
              transition:'background 200ms',
            }}>
              {submitting ? (
                <>
                  <span style={{width:14, height:14, borderRadius:'50%', border:'2.5px solid #022C28', borderTopColor:'transparent', animation:'p-spin 0.7s linear infinite'}}/>
                  Signing in…
                </>
              ) : (
                <>Sign in <PamojaIcon name="arrowRight" size={14} color="#022C28" stroke={2.4}/></>
              )}
            </button>
          </form>

          <div style={{
            marginTop:32, paddingTop:24, borderTop:'1px dashed #E5E7EB',
          }}>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:12}}>
              <span style={{fontSize:10, fontWeight:800, letterSpacing:'0.12em', textTransform:'uppercase', color:'#9CA3AF'}}>Quick demo accounts</span>
              <span style={{
                fontSize:9, fontFamily:'JetBrains Mono, monospace', fontWeight:800, letterSpacing:'0.06em',
                color:'#7C5104', background:'#FFF8E0', padding:'2px 6px', borderRadius:4,
              }}>PROTOTYPE</span>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:6}}>
              {DEMO_ACCOUNTS.map(a => (
                <DemoRow key={a.id} acct={a} onClick={()=>pickDemo(a)} active={autoFill?.id === a.id}/>
              ))}
            </div>

            <details style={{marginTop:12}}>
              <summary style={{
                fontSize:11, color:'#9CA3AF', cursor:'pointer', userSelect:'none',
                listStyle:'none', display:'inline-flex', alignItems:'center', gap:6,
                fontWeight:600,
              }}>
                <PamojaIcon name="chevronDown" size={10} color="#9CA3AF" stroke={2}/>
                6 other roles in production (out of scope for this design pass)
              </summary>
              <div style={{marginTop:10, display:'flex', flexDirection:'column', gap:4, paddingLeft:14}}>
                {OTHER_ROLES.map((r,i) => (
                  <div key={i} style={{display:'flex', alignItems:'center', gap:8, fontSize:11, color:'#9CA3AF', lineHeight:1.55}}>
                    <PamojaIcon name="lock" size={10} color="#D1D5DB" stroke={1.7}/>
                    <span style={{fontWeight:600, color:'#6B7280'}}>{r.name}</span>
                    <span>· {r.org}</span>
                  </div>
                ))}
              </div>
            </details>
          </div>
        </div>

        <div style={{
          textAlign:'center', fontSize:11, color:'#9CA3AF', paddingTop:14,
          borderTop:'1px solid #F3F4F6',
        }}>
          <div style={{display:'inline-flex', alignItems:'center', gap:6, fontFamily:'JetBrains Mono, monospace'}}>
            <span style={{width:6, height:6, borderRadius:'50%', background:'#2BC48A'}}/>
            Hedera testnet · 0.0.8321350 · operational
          </div>
        </div>
      </div>
    </div>
  );
}

function DemoRow({ acct, onClick, active }) {
  const initials = acct.name.split(' ').map(s=>s[0]).join('').slice(0,2).toUpperCase();
  return (
    <button onClick={onClick} type="button" style={{
      display:'flex', alignItems:'center', gap:12, padding:'10px 12px',
      background: active ? '#FFF8E0' : '#FAFAFA',
      border: active ? '1.5px solid #F4C300' : '1px solid #E5E7EB',
      borderRadius:10, cursor:'pointer', fontFamily:'inherit', textAlign:'left',
      transition:'background 150ms, border-color 150ms',
    }}
    onMouseEnter={e=>{ if(!active) e.currentTarget.style.borderColor = '#9CA3AF'; }}
    onMouseLeave={e=>{ if(!active) e.currentTarget.style.borderColor = '#E5E7EB'; }}>
      <div style={{
        width:32, height:32, borderRadius:'50%', background: acct.accent,
        color:'#022C28', display:'flex', alignItems:'center', justifyContent:'center',
        fontSize:11, fontWeight:900, flexShrink:0,
      }}>{initials}</div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontSize:12, fontWeight:800, color:'#022C28', display:'flex', alignItems:'center', gap:6}}>
          {acct.name}
          <span style={{fontSize:10, color:'#6B7280', fontWeight:600}}>· {acct.role}</span>
        </div>
        <div style={{fontSize:10, color:'#9CA3AF', fontFamily:'JetBrains Mono, monospace', marginTop:2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>
          {acct.email}
        </div>
      </div>
      <PamojaIcon name="arrowRight" size={12} color={active ? '#B8960A' : '#9CA3AF'} stroke={2}/>
    </button>
  );
}

function Field({ label, right, children }) {
  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:6}}>
        <label style={{fontSize:11, fontWeight:800, color:'#022C28', letterSpacing:'0.02em'}}>{label}</label>
        {right}
      </div>
      {children}
    </div>
  );
}

const loginInput = {
  width:'100%', padding:'12px 14px', border:'1.5px solid #E5E7EB', borderRadius:10,
  fontSize:14, fontFamily:'inherit', outline:'none', color:'#022C28',
  background:'#fff', minHeight:46,
  transition:'border-color 200ms, box-shadow 200ms',
};

// Renamed export so App.jsx routes through LoginScreen instead of the old PortalSelector.
window.LoginScreen = LoginScreen;
// Keep the old name as an alias in case any host code still references it.
window.PortalSelector = LoginScreen;
