function passwordStrengthAdmin(pw) {
  if (!pw) return { score: 0, label: '', color: 'var(--gray-200)' };
  let score = 0;
  if (pw.length >= 8) score++;
  if (/[a-z]/.test(pw) && /[A-Z]/.test(pw)) score++;
  if (/[0-9]/.test(pw)) score++;
  if (/[^A-Za-z0-9]/.test(pw)) score++;
  const labels = ['Weak', 'Weak', 'Fair', 'Good', 'Strong'];
  const colors = ['var(--status-error)', 'var(--status-error)', 'var(--status-warning)', 'var(--brand-primary)', 'var(--status-success)'];
  return { score, label: labels[score], color: colors[score] };
}
const EYE_ICON_ADMIN = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>;
const EYE_OFF_ICON_ADMIN = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /><line x1="3" y1="21" x2="21" y2="3" /></svg>;

function AdminPasswordField({ label, value, onChange, showStrength }) {
  const [show, setShow] = React.useState(false);
  const strength = showStrength ? passwordStrengthAdmin(value) : null;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{ fontSize: 'var(--text-sm)', fontWeight: 600 }}>{label}</label>
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
        <input type={show ? 'text' : 'password'} value={value} onChange={(e) => onChange(e.target.value)} style={{ width: '100%', boxSizing: 'border-box', padding: '11px 44px 11px 14px', fontSize: 'var(--text-base)', fontFamily: 'var(--font-body)', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', outline: 'none' }} />
        <button type="button" onClick={() => setShow((s) => !s)} aria-label={show ? 'Hide password' : 'Show password'} style={{ position: 'absolute', right: 10, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', padding: 4 }}>{show ? EYE_OFF_ICON_ADMIN : EYE_ICON_ADMIN}</button>
      </div>
      {showStrength && value && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <div style={{ display: 'flex', gap: 4 }}>{[0, 1, 2, 3].map((i) => <div key={i} style={{ height: 4, flex: 1, borderRadius: 2, background: i < strength.score ? strength.color : 'var(--gray-100)' }} />)}</div>
          <span style={{ fontSize: 'var(--text-xs)', color: strength.color }}>{strength.label} \u2014 use 8+ characters with upper &amp; lowercase, a number, and a symbol.</span>
        </div>
      )}
    </div>
  );
}

function AdminAvatar({ size, initials }) {
  return <div style={{ width: size, height: size, borderRadius: '50%', background: 'var(--navy-800)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size / 2.6, border: '3px solid white', boxShadow: 'var(--shadow-md)' }}>{initials}</div>;
}

function AdminProfileTab({ adminUser, onUpdated }) {
  const { Input, Button } = window.TheUpperDeckDesignSystem_4d3294;
  const [editing, setEditing] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [form, setForm] = React.useState({ firstName: adminUser.first_name || '', lastName: adminUser.last_name || '', email: adminUser.email || '', phone: adminUser.phone || '', city: adminUser.city || '' });
  const set = (k) => (v) => setForm((f) => ({ ...f, [k]: v }));
  async function save() {
    setSaving(true);
    await window.sb.from('profiles').update({ first_name: form.firstName, last_name: form.lastName, phone: form.phone || null, city: form.city || null }).eq('id', adminUser.id);
    setSaving(false); setEditing(false);
    onUpdated({ ...adminUser, first_name: form.firstName, last_name: form.lastName, phone: form.phone, city: form.city });
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontWeight: 600, fontSize: 'var(--text-sm)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>Personal info</div>
          {!editing && <Button size="sm" variant="secondary" onClick={() => setEditing(true)}>Edit profile</Button>}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Input label="First name" value={form.firstName} onChange={set('firstName')} disabled={!editing} />
          <Input label="Last name" value={form.lastName} onChange={set('lastName')} disabled={!editing} />
          <Input label="Email address" type="email" value={form.email} disabled />
          <Input label="Phone number" type="tel" value={form.phone} onChange={set('phone')} disabled={!editing} />
          <Input label="Role" value="Admin" disabled />
          <Input label="City" value={form.city} onChange={set('city')} disabled={!editing} />
        </div>
      </div>
      {editing && (
        <div style={{ display: 'flex', gap: 12 }}>
          <Button onClick={save} disabled={saving}>{saving ? 'Saving…' : 'Save changes'}</Button>
          <Button variant="ghost" onClick={() => setEditing(false)}>Cancel</Button>
        </div>
      )}
    </div>
  );
}

function AdminSettingsTab({ onSignOut }) {
  const { Button, Dialog, Input } = window.TheUpperDeckDesignSystem_4d3294;
  const [confirmOpen, setConfirmOpen] = React.useState(false);
  const [pw, setPw] = React.useState({ newPw: '', confirmPw: '' });
  const [pwSaving, setPwSaving] = React.useState(false);
  const [pwMsg, setPwMsg] = React.useState('');
  async function changePassword() {
    setPwMsg('');
    if (pw.newPw.length < 8) { setPwMsg('Password must be at least 8 characters.'); return; }
    if (pw.newPw !== pw.confirmPw) { setPwMsg('Passwords do not match.'); return; }
    setPwSaving(true);
    const { error } = await window.sb.auth.updateUser({ password: pw.newPw });
    setPwSaving(false);
    setPwMsg(error ? error.message : 'Password updated.');
    if (!error) setPw({ newPw: '', confirmPw: '' });
  }
  return (
    <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ fontWeight: 600, fontSize: 'var(--text-sm)' }}>Change password</div>
        {pwMsg && <div style={{ fontSize: 'var(--text-sm)', color: pwMsg === 'Password updated.' ? 'var(--status-success)' : 'var(--status-error)' }}>{pwMsg}</div>}
        <AdminPasswordField label="New password" value={pw.newPw} onChange={(v) => setPw((s) => ({ ...s, newPw: v }))} showStrength />
        <AdminPasswordField label="Confirm new password" value={pw.confirmPw} onChange={(v) => setPw((s) => ({ ...s, confirmPw: v }))} />
        <Button variant="secondary" onClick={changePassword} disabled={pwSaving} style={{ alignSelf: 'flex-start' }}>{pwSaving ? 'Saving\u2026' : 'Update password'}</Button>
      </div>
      <div style={{ borderTop: '1px solid var(--border-default)', paddingTop: 20 }}>
        <Button variant="danger" onClick={() => setConfirmOpen(true)}>Log out</Button>
      </div>
      <Dialog open={confirmOpen} title="Log out?" onClose={() => setConfirmOpen(false)} footer={<>
        <Button variant="ghost" onClick={() => setConfirmOpen(false)}>Stay signed in</Button>
        <Button variant="danger" onClick={onSignOut}>Log out</Button>
      </>}>You'll need to sign in again to access the admin dashboard.</Dialog>
    </div>
  );
}

function AccountScreen({ initialTab, adminUser, onSignOut, onUpdateAdminUser }) {
  const { Tabs } = window.TheUpperDeckDesignSystem_4d3294;
  const [tab, setTab] = React.useState(initialTab || 'profile');
  const [stats, setStats] = React.useState({ events: 0, orders: 0 });
  React.useEffect(() => { setTab(initialTab || 'profile'); }, [initialTab]);
  React.useEffect(() => {
    Promise.all([window.fetchMainEventsLive(), window.fetchOrdersLive()]).then(([events, orders]) => {
      setStats({ events: events.length, orders: orders.filter((o) => o.status !== 'pending').length });
    });
  }, []);
  const initials = ((adminUser.first_name || 'A')[0] + (adminUser.last_name || '')[0]).toUpperCase();
  return (
    <div>
      <div style={{ background: 'var(--gradient-navy)', borderRadius: 'var(--radius-lg)', padding: '40px 36px', color: 'white', display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap', marginBottom: -40, boxShadow: 'var(--shadow-md)' }}>
        <AdminAvatar size={88} initials={initials} />
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', margin: '0 0 4px' }}>{adminUser.first_name} {adminUser.last_name}</h1>
          <div style={{ color: 'var(--text-on-dark-muted)', fontSize: 'var(--text-sm)' }}>{adminUser.email} · Admin</div>
        </div>
        <div style={{ display: 'flex', gap: 28, marginLeft: 'auto' }}>
          <div style={{ textAlign: 'center' }}><div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-2xl)' }}>{stats.events}</div><div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-on-dark-muted)' }}>Events managed</div></div>
          <div style={{ textAlign: 'center' }}><div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-2xl)' }}>{stats.orders}</div><div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-on-dark-muted)' }}>Orders handled</div></div>
        </div>
      </div>
      <div style={{ paddingTop: 56 }}>
        <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-md)', padding: '8px 24px 0', marginBottom: 24 }}>
          <Tabs tabs={[{ value: 'profile', label: 'Profile' }, { value: 'settings', label: 'Settings' }]} active={tab} onChange={setTab} />
        </div>
        {tab === 'profile' ? <AdminProfileTab adminUser={adminUser} onUpdated={onUpdateAdminUser} /> : <AdminSettingsTab onSignOut={onSignOut} />}
      </div>
    </div>
  );
}

window.AccountScreen = AccountScreen;
