// screens-user.jsx — user-facing screens, exported to window
const { useState: uState, useMemo, useEffect: uEffect } = React;

/* ============ PROPERTY CARD ============ */
function PropertyCard({ p, saved, onSave, onOpen, compact }) {
  return (
    <Card pad={false} hover onClick={onOpen} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <PropImage hue={p.hue} label={p.label} height={compact ? 150 : 184} radius="0" tag={p.tag} saved={saved} onSave={onSave} />
      <div style={{ padding: 'var(--pad)', display: 'flex', flexDirection: 'column', gap: 9, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: 'var(--ink-3)', fontSize: 12.5 }}>
          <Icon name="pin" size={13} /> <span>{p.city} · {p.country}</span>
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17.5, lineHeight: 1.2 }}>{p.title}</div>
        <div style={{ display: 'flex', gap: 14, color: 'var(--ink-2)', fontSize: 13, marginTop: 'auto', paddingTop: 6, flexWrap: 'wrap' }}>
          {p.beds > 0 && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="bed" size={15} /> {p.beds}</span>}
          {p.baths > 0 && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="bath" size={15} /> {p.baths}</span>}
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="ruler" size={15} /> {p.area.toLocaleString()} {p.areaUnit}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderTop: '1px solid var(--line)', paddingTop: 11, marginTop: 2 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18 }}>
            <Money cur={p.cur} value={p.price} unit={p.unit} />
          </div>
          <Tag>{p.type}</Tag>
        </div>
      </div>
    </Card>
  );
}

/* ============ STATUS TIMELINE (hero flow) ============ */
function StatusTimeline({ status, vertical }) {
  const flow = window.CREDO.STATUS_FLOW;
  const declined = status === 'Declined';
  const idx = declined ? -1 : flow.indexOf(status);
  return (
    <div style={{ display: 'flex', flexDirection: vertical ? 'column' : 'row', gap: vertical ? 0 : 4, alignItems: vertical ? 'stretch' : 'center' }}>
      {flow.map((s, i) => {
        const done = i < idx, current = i === idx, future = i > idx;
        const color = done ? 'var(--brand)' : current ? 'var(--brand)' : 'var(--line-2)';
        return (
          <div key={s} style={{ display: 'flex', flexDirection: vertical ? 'row' : 'column', alignItems: 'center', gap: vertical ? 12 : 7, flex: vertical ? 'none' : 1 }}>
            {!vertical && i > 0 && null}
            <div style={{ display: 'flex', flexDirection: vertical ? 'column' : 'row', alignItems: 'center', width: vertical ? 'auto' : '100%' }}>
              {!vertical && <div style={{ flex: 1, height: 2, background: i === 0 ? 'transparent' : (i <= idx ? 'var(--brand)' : 'var(--line)') }} />}
              <div style={{
                width: current ? 26 : 22, height: current ? 26 : 22, borderRadius: '50%', flexShrink: 0,
                display: 'grid', placeItems: 'center', transition: 'all .2s',
                background: (done || current) ? 'var(--brand)' : 'var(--surface)',
                border: future ? '2px solid var(--line-2)' : '2px solid var(--brand)',
                color: '#fff', boxShadow: current ? '0 0 0 4px var(--brand-soft)' : 'none',
              }}>
                {done ? <Icon name="check" size={12} stroke={3} /> : current ? <span style={{ width: 7, height: 7, borderRadius: 99, background: '#fff' }} /> : null}
              </div>
              {!vertical && <div style={{ flex: 1, height: 2, background: i >= flow.length - 1 ? 'transparent' : (i < idx ? 'var(--brand)' : 'var(--line)') }} />}
              {vertical && i < flow.length - 1 && <div style={{ width: 2, height: 22, background: i < idx ? 'var(--brand)' : 'var(--line)', margin: '2px 0' }} />}
            </div>
            <div style={{ fontSize: vertical ? 13.5 : 11.5, fontWeight: current ? 700 : 500, color: (done || current) ? 'var(--ink)' : 'var(--ink-3)', textAlign: vertical ? 'left' : 'center', paddingBottom: vertical ? (i < flow.length - 1 ? 14 : 0) : 0 }}>
              {s}
            </div>
          </div>
        );
      })}
      {declined && <div style={{ marginLeft: 12 }}><StatusPill status="Declined" /></div>}
    </div>
  );
}

/* ============ AUTH FLOW: sign in / create account ============ */
const DEMO_CRED = { email: 'demo@credeo.com', password: 'credeo@1234' };
const ADMIN_CRED = { email: 'admin@credeo.com', password: 'credeo@admin', name: 'Credeo Admin' };
const ACCOUNTS_KEY = 'credeo_accounts';
function loadAccounts() {
  try { return JSON.parse(localStorage.getItem(ACCOUNTS_KEY)) || []; } catch (e) { return []; }
}
function saveAccount(acc) {
  const all = loadAccounts().filter(a => a.email.toLowerCase() !== acc.email.toLowerCase());
  all.push(acc);
  try { localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(all)); } catch (e) {}
}
const DEMO_IDENTITIES = [
  { name: 'Ada Rutherford', email: 'ada.rutherford@gmail.com' },
  { name: 'Marcus Bellamy', email: 'm.bellamy@outlook.com' },
  { name: 'Sofia Lindqvist', email: 'sofia.lindqvist@gmail.com' },
  { name: 'James Okafor', email: 'j.okafor@icloud.com' },
  { name: 'Helena Marsh', email: 'helena.marsh@gmail.com' },
  { name: 'Daniel Roux', email: 'd.roux@proton.me' },
  { name: 'Priya Nair', email: 'priya.nair@gmail.com' },
  { name: 'Thomas Weller', email: 't.weller@outlook.com' },
];

function AuthFlow({ onComplete, isMobile }) {
  const [step, setStep] = uState('signin');
  const [email, setEmail] = uState('');
  const [password, setPassword] = uState('');
  const [name, setName] = uState('');
  const [err, setErr] = uState('');

  const go = (s) => { setStep(s); setErr(''); setEmail(''); setPassword(''); setName(''); };

  const submitSignin = (e) => {
    e.preventDefault();
    const em = email.trim().toLowerCase();
    // Dedicated admin account → admin console
    if (em === ADMIN_CRED.email && password === ADMIN_CRED.password) {
      setErr(''); onComplete({ name: ADMIN_CRED.name, email: ADMIN_CRED.email, role: 'admin', fresh: false });
      return;
    }
    // Quick demo member login
    if (em === DEMO_CRED.email && password === DEMO_CRED.password) {
      setErr('');
      const who = DEMO_IDENTITIES[Math.floor(Math.random() * DEMO_IDENTITIES.length)];
      onComplete({ ...who, role: 'user', fresh: false });
      return;
    }
    // Accounts created via sign-up (persisted to this browser)
    const acc = loadAccounts().find(a => a.email.toLowerCase() === em && a.password === password);
    if (acc) {
      setErr(''); onComplete({ name: acc.name, email: acc.email, role: 'user', fresh: true });
      return;
    }
    setErr('Invalid credentials — ensure your credentials are correct.');
  };

  const submitReg = (e) => {
    e.preventDefault();
    const em = email.trim().toLowerCase();
    if (!name.trim() || !email.includes('@') || !password) { setErr('Please enter your name, a valid email and a password.'); return; }
    if (em === ADMIN_CRED.email || em === DEMO_CRED.email || loadAccounts().some(a => a.email.toLowerCase() === em)) {
      setErr('An account with this email already exists — try signing in instead.'); return;
    }
    saveAccount({ name: name.trim(), email: email.trim(), password });
    setErr(''); setStep('done');
    setTimeout(() => onComplete({ name: name.trim(), email: email.trim(), role: 'user', fresh: true }), 1400);
  };

  return (
    <div style={{ minHeight: '100%', display: 'flex', background: 'var(--bg)' }}>
      {/* left brand panel (desktop) */}
      {!isMobile && (
      <div className="auth-aside" style={{ flex: '1 1 44%', position: 'relative', overflow: 'hidden', background: 'linear-gradient(150deg, var(--brand-ink) 0%, var(--brand) 70%, var(--accent) 130%)', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 48, color: '#fff' }}>
        <div style={{ color: '#fff' }}><Logo size={26} mono /></div>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,.05) 0 2px, transparent 2px 13px)' }} />
        <div style={{ position: 'relative', maxWidth: 430, display: 'flex', flexDirection: 'column', gap: 18 }}>
          <h1 style={{ fontSize: 38, lineHeight: 1.1, color: '#fff', fontWeight: 600 }}>Property &amp; asset management, considered.</h1>
          <p style={{ fontSize: 16, lineHeight: 1.55, color: 'rgba(255,255,255,.85)' }}>
            Save residences, request inspections and lease with a dedicated concierge across the UK and Europe.
          </p>
        </div>
        <div style={{ position: 'relative', display: 'flex', gap: 26, color: 'rgba(255,255,255,.78)', fontSize: 13 }}>
          <span style={{ display: 'inline-flex', gap: 7, alignItems: 'center' }}><Icon name="shield" size={16} /> Verified listings</span>
          <span style={{ display: 'inline-flex', gap: 7, alignItems: 'center' }}><Icon name="key" size={16} /> Managed lettings</span>
        </div>
      </div>
      )}

      {/* right form panel */}
      <div style={{ flex: '1 1 56%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 28 }}>
        <div style={{ width: '100%', maxWidth: 392, animation: 'credo-fade-up .3s ease' }}>
          <div className="auth-mobile-logo" style={{ display: isMobile ? 'block' : 'none', marginBottom: 28 }}><Logo size={24} /></div>

          {step === 'signin' && (
            <form onSubmit={submitSignin} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <h2 style={{ fontSize: 27 }}>Welcome back</h2>
                <p style={{ color: 'var(--ink-2)', fontSize: 14.5, marginTop: 7 }}>Sign in to your Credeo account.</p>
              </div>
              <Field label="Email address" required><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" /></Field>
              <Field label="Password" required><Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Your password" /></Field>
              {err && <div style={{ color: 'var(--danger)', fontSize: 13 }}>{err}</div>}
              <Button type="submit" size="lg" full iconRight="arrowRight">Sign in</Button>
              <Divider label="or" />
              <p style={{ fontSize: 13.5, color: 'var(--ink-2)', textAlign: 'center' }}>New to Credeo? <span onClick={() => go('register')} style={{ color: 'var(--brand)', fontWeight: 600, cursor: 'pointer' }}>Create an account</span></p>
            </form>
          )}

          {step === 'register' && (
            <form onSubmit={submitReg} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <h2 style={{ fontSize: 27 }}>Create your account</h2>
                <p style={{ color: 'var(--ink-2)', fontSize: 14.5, marginTop: 7 }}>Join Credeo to save properties and manage requests.</p>
              </div>
              <Field label="Full name" required><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your full name" /></Field>
              <Field label="Email address" required><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" /></Field>
              <Field label="Password" required><Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Choose a password" /></Field>
              {err && <div style={{ color: 'var(--danger)', fontSize: 13 }}>{err}</div>}
              <Button type="submit" size="lg" full iconRight="arrowRight">Create account</Button>
              <p style={{ fontSize: 12.5, color: 'var(--ink-3)', textAlign: 'center', lineHeight: 1.5 }}>By continuing you agree to Credeo's Terms &amp; Privacy Policy.</p>
              <Divider label="or" />
              <p style={{ fontSize: 13.5, color: 'var(--ink-2)', textAlign: 'center' }}>Already have an account? <span onClick={() => go('signin')} style={{ color: 'var(--brand)', fontWeight: 600, cursor: 'pointer' }}>Sign in</span></p>
            </form>
          )}

          {step === 'done' && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, textAlign: 'center', animation: 'credo-pop .3s ease' }}>
              <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'var(--brand)', color: '#fff', display: 'grid', placeItems: 'center', boxShadow: '0 0 0 8px var(--brand-soft)' }}>
                <Icon name="check" size={38} stroke={2.6} />
              </div>
              <h2 style={{ fontSize: 27 }}>Account created</h2>
              <p style={{ color: 'var(--ink-2)', fontSize: 14.5, maxWidth: 280, lineHeight: 1.5 }}>Welcome to Credeo, {name.split(' ')[0]}. Taking you to your dashboard…</p>
              <div style={{ width: 22, height: 22, border: '2.5px solid var(--line-2)', borderTopColor: 'var(--brand)', borderRadius: '50%', animation: 'credo-spin .7s linear infinite' }} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.UserScreens = { PropertyCard, StatusTimeline, AuthFlow };
