// AdminDashboard.jsx — admin role: manage staff accounts (create ID + password).
const { useState: useStateAdmin } = React;

function genPassword() {
  const words = ['care', 'ortho', 'sylhet', 'clinic', 'bone', 'heal'];
  return words[Math.floor(Math.random() * words.length)] + '-' + Math.floor(1000 + Math.random() * 9000);
}
function slugId(name) { return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '.').replace(/^\.|\.$/g, '').slice(0, 16); }

function AdminDashboard({ accounts, onCreate, onDelete, onLogout, compact, account, online, lang = 'en', onLang }) {
  const T = window.TOK, B = window.BRAND, D = window.dict(lang);
  const [name, setName] = useStateAdmin('');
  const [role, setRole] = useStateAdmin('caregiver');
  const [id, setId] = useStateAdmin('');
  const [pw, setPw] = useStateAdmin(genPassword());
  const [reveal, setReveal] = useStateAdmin({});
  const [toast, setToast] = useStateAdmin('');

  const effectiveId = (id || slugId(name));
  const idTaken = accounts.some(a => a.id.toLowerCase() === effectiveId.toLowerCase());
  const canCreate = name.trim() && effectiveId && pw.trim() && !idTaken;

  const create = () => {
    if (!canCreate) return;
    const newPw = pw.trim();
    onCreate({ id: effectiveId, password: newPw, role, name: name.trim(), created: 'Admin' });
    // online: the server never returns stored passwords, so surface it once here
    setToast(online ? `“${effectiveId}” ${D.acc_created} · ${D.l_pw}: ${newPw}` : `“${effectiveId}” ${D.acc_created}`);
    setName(''); setId(''); setPw(genPassword()); setRole('caregiver');
    setTimeout(() => setToast(''), online ? 6000 : 3200);
  };

  const inputStyle = { width: '100%', boxSizing: 'border-box', height: 46, padding: '0 13px', fontFamily: 'inherit', fontSize: 15.5, color: T.ink, background: T.surface, border: `1px solid ${T.line}`, borderRadius: 11, outline: 'none' };
  const onFocus = e => e.target.style.borderColor = T.accent;
  const onBlur = e => e.target.style.borderColor = T.line;
  const labelStyle = { display: 'block', fontSize: 12.5, fontWeight: 600, color: T.inkSoft, marginBottom: 6 };

  const caregivers = accounts.filter(a => a.role === 'caregiver').length;
  const admins = accounts.filter(a => a.role === 'admin').length;

  // ── account card ──
  const Card = (a) => (
    <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '13px 14px', background: T.surface, border: `1px solid ${T.line}`, borderRadius: 14 }}>
      <span style={{ width: 42, height: 42, borderRadius: 11, flexShrink: 0, background: a.role === 'admin' ? '#EEE6FB' : T.accentSoft, color: a.role === 'admin' ? '#7A4FD0' : T.accentDeep, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17, fontWeight: 700 }}>{a.name[0]}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 15, fontWeight: 600, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</span>
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: a.role === 'admin' ? '#7A4FD0' : T.accentDeep, background: a.role === 'admin' ? '#EEE6FB' : T.accentSoft, padding: '2px 7px', borderRadius: 6, flexShrink: 0 }}>{D['role_' + a.role]}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 3, fontFamily: 'monospace', fontSize: 12.5, color: T.muted }}>
          <span>{a.id}</span>
          {/* online: passwords are hashed server-side and never returned. offline demo: reveal/hide. */}
          {online ? (
            <span style={{ color: T.faint, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><rect x="4" y="10" width="16" height="11" rx="2.4" stroke={T.faint} strokeWidth="1.9"/><path d="M8 10V7a4 4 0 0 1 8 0v3" stroke={T.faint} strokeWidth="1.9"/></svg>
              hashed
            </span>
          ) : (
            <React.Fragment>
              <span style={{ color: T.faint }}>·</span>
              <span>{reveal[a.id] ? a.password : '••••••'}</span>
              <button onClick={() => setReveal(r => ({ ...r, [a.id]: !r[a.id] }))} style={{ border: 'none', background: 'none', cursor: 'pointer', color: T.accent, fontFamily: 'inherit', fontSize: 12, fontWeight: 600, padding: 0 }}>{reveal[a.id] ? D.reveal_hide : D.reveal_show}</button>
            </React.Fragment>
          )}
        </div>
      </div>
      {a.created === 'Owner'
        ? <span style={{ fontSize: 11, color: T.faint, fontWeight: 600, flexShrink: 0 }}>{D.owner}</span>
        : <button onClick={() => onDelete(a.id)} title="Remove" style={{ width: 32, height: 32, borderRadius: 9, border: `1px solid ${T.line}`, background: T.bone, cursor: 'pointer', color: T.faint, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M5 7h14M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>}
    </div>
  );

  // ── create panel ──
  const createPanel = (
    <div style={{ background: T.surface, border: `1px solid ${T.line}`, borderRadius: 18, padding: compact ? 18 : 22 }}>
      <div style={{ fontFamily: "'Anek Bangla', 'Hind Siliguri', sans-serif", fontWeight: 600, fontSize: 22, color: T.ink, marginBottom: 4 }}>{D.new_account}</div>
      <div style={{ fontSize: 13.5, color: T.muted, marginBottom: 18 }}>{D.new_acc_sub}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <span style={labelStyle}>{D.a_name}</span>
          <input value={name} onChange={e => setName(e.target.value)} placeholder={D.a_name_ph} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
        </div>
        <div>
          <span style={labelStyle}>{D.a_role}</span>
          <div style={{ display: 'flex', gap: 8 }}>
            {[['caregiver', D.role_caregiver], ['admin', D.role_admin]].map(([v, l]) => (
              <button key={v} onClick={() => setRole(v)} style={{ flex: 1, height: 44, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14.5, fontWeight: 600, borderRadius: 11, border: `1.5px solid ${role === v ? T.accent : T.line}`, background: role === v ? T.accentSoft : T.surface, color: role === v ? T.accentDeep : T.inkSoft }}>{l}</button>
            ))}
          </div>
        </div>
        <div>
          <span style={labelStyle}>{D.a_id}</span>
          <input value={id} onChange={e => setId(e.target.value.toLowerCase())} placeholder={slugId(name) || D.a_id_ph} style={{ ...inputStyle, fontFamily: 'monospace', borderColor: idTaken ? '#E0A094' : T.line }} onFocus={onFocus} onBlur={onBlur} />
          {idTaken && <div style={{ fontSize: 12.5, color: '#C0492B', marginTop: 5 }}>{D.id_taken}</div>}
        </div>
        <div>
          <span style={labelStyle}>{D.a_pw}</span>
          <div style={{ display: 'flex', gap: 8 }}>
            <input value={pw} onChange={e => setPw(e.target.value)} style={{ ...inputStyle, fontFamily: 'monospace', flex: 1 }} onFocus={onFocus} onBlur={onBlur} />
            <button onClick={() => setPw(genPassword())} style={{ flexShrink: 0, padding: '0 14px', height: 46, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: 600, color: T.accentDeep, background: T.accentSoft, border: 'none', borderRadius: 11 }}>{D.generate}</button>
          </div>
        </div>
        <button onClick={create} disabled={!canCreate} style={{ height: 50, marginTop: 4, cursor: canCreate ? 'pointer' : 'not-allowed', fontFamily: 'inherit', fontSize: 16, fontWeight: 600, color: canCreate ? '#fff' : T.faint, background: canCreate ? T.accent : T.boneDeep, border: 'none', borderRadius: 12 }}>{D.create_btn}</button>
      </div>
    </div>
  );

  const accountsList = (
    <div>
      <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: 1.4, color: T.faint, textTransform: 'uppercase', marginBottom: 12 }}>{D.accounts} · {accounts.length}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{accounts.map(Card)}</div>
    </div>
  );

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.bone, fontFamily: "'Hanken Grotesk', sans-serif" }}>
      <Topbar compact={compact} account={account} lang={lang} onLang={onLang} onLogout={onLogout} roleTag={D.role_admin} />
      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ maxWidth: compact ? '100%' : 1100, margin: '0 auto', padding: compact ? '18px 18px 40px' : '28px 32px 50px' }}>
          {/* stats */}
          <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr 1fr' : 'repeat(3,1fr)', gap: 12, marginBottom: 22 }}>
            <Stat label={D.accounts} value={accounts.length} />
            <Stat label={D.stat_caregivers} value={caregivers} />
            <Stat label={D.stat_admins} value={admins} />
          </div>
          {compact
            ? <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>{createPanel}{accountsList}</div>
            : <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 26, alignItems: 'start' }}>{accountsList}{createPanel}</div>}
        </div>
      </div>
      {toast && <div style={{ position: 'absolute', bottom: 22, left: '50%', transform: 'translateX(-50%)', background: '#1AA06D', color: '#fff', padding: '11px 18px', borderRadius: 12, fontSize: 14, fontWeight: 600, boxShadow: '0 10px 28px rgba(26,160,109,0.4)', whiteSpace: 'nowrap' }}>✓ {toast}</div>}
    </div>
  );
}

function Stat({ label, value }) {
  const T = window.TOK;
  return (
    <div style={{ background: T.surface, border: `1px solid ${T.line}`, borderRadius: 14, padding: '14px 16px' }}>
      <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, color: T.ink, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 12.5, color: T.muted, marginTop: 4, fontWeight: 500 }}>{label}</div>
    </div>
  );
}

// shared staff top bar
function Topbar({ compact, account, onLogout, roleTag, right, lang = 'en', onLang }) {
  const T = window.TOK, B = window.BRAND, D = window.dict(lang);
  return (
    <div style={{ flexShrink: 0, background: T.surface, borderBottom: `1px solid ${T.line}`, padding: compact ? '48px 18px 14px' : '14px 28px', display: 'flex', alignItems: 'center', gap: 14 }}>
      <span style={{ width: 34, height: 34, borderRadius: 10, background: T.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M3 12h3l2-5 3 9 2.5-6 1.5 2H21" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: compact ? 19 : 22, color: T.ink, lineHeight: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>{B.name}</span>
          <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: T.accentDeep, background: T.accentSoft, padding: '2px 7px', borderRadius: 6 }}>{roleTag}</span>
        </div>
        {!compact && <div style={{ fontSize: 12.5, color: T.muted, marginTop: 2 }}>{account ? account.name + ' · ' + D.logged_in : B.hospital}</div>}
      </div>
      {right}
      {onLang && <window.LangToggle lang={lang} onLang={onLang} />}
      <button onClick={onLogout} style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 7, padding: compact ? '8px 12px' : '9px 15px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600, color: T.inkSoft, background: T.bone, border: `1px solid ${T.line}`, borderRadius: 10 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M15 12H4m0 0l4-4m-4 4l4 4M14 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
        {!compact && D.logout}
      </button>
    </div>
  );
}

window.AdminDashboard = AdminDashboard;
window.StaffTopbar = Topbar;
