// =========================================================
// admin.jsx — Build Lab admin portal
// Loaded via <script type="text/babel"> in index.html.
// Accessible at /build/#admin or /build/#admin?key=SECRET
// =========================================================

function BuildLabAdmin() {
  const [authed, setAuthed] = React.useState(false);
  const [secret, setSecret] = React.useState('');
  const [users, setUsers] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [page, setPage] = React.useState(1);
  const [settings, setSettings] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [emailTo, setEmailTo] = React.useState('');
  const [emailSubject, setEmailSubject] = React.useState('');
  const [emailBody, setEmailBody] = React.useState('');
  const secretRef = React.useRef('');

  const hdrs = () => ({
    'Content-Type': 'application/json',
    'X-Admin-Secret': secretRef.current,
  });

  // Check URL param for key shortcut
  React.useEffect(() => {
    const h = window.location.hash || '';
    const m = h.match(/[?&]key=([^&]+)/);
    if (m) {
      secretRef.current = decodeURIComponent(m[1]);
      setSecret(secretRef.current);
      tryAuth(secretRef.current);
    }
  }, []);

  async function tryAuth(s) {
    const key = s || secret;
    secretRef.current = key;
    try {
      const res = await fetch('/api/build/admin/auth', {
        method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Admin-Secret': key },
      });
      const d = await res.json();
      if (d.ok) { setAuthed(true); loadUsers(1); loadSettings(); }
      else setMsg('Invalid secret');
    } catch (e) { setMsg('Error: ' + e.message); }
  }

  async function loadUsers(p) {
    setLoading(true);
    try {
      const res = await fetch('/api/build/admin/users?page=' + (p || page), { headers: hdrs() });
      const d = await res.json();
      setUsers(d.users || []);
      setTotal(d.total || 0);
      setPage(p || page);
    } catch (e) { setMsg('Error loading users'); }
    setLoading(false);
  }

  async function loadSettings() {
    try {
      const res = await fetch('/api/build/admin/settings', { headers: hdrs() });
      const d = await res.json();
      setSettings(d.settings || {});
    } catch (e) {}
  }

  async function updateUser(id, field, value) {
    try {
      const res = await fetch('/api/build/admin/users', {
        method: 'PATCH', headers: hdrs(),
        body: JSON.stringify({ id, [field]: value }),
      });
      const d = await res.json();
      if (d.ok) {
        setUsers(prev => prev.map(u => u.id === id ? { ...u, ...d.user } : u));
        setMsg('Updated user #' + id);
      } else { setMsg('Error: ' + (d.error || 'unknown')); }
    } catch (e) { setMsg('Error: ' + e.message); }
    setTimeout(() => setMsg(''), 3000);
  }

  async function toggleSetting(key) {
    const current = settings[key];
    const next = current === 'on' ? 'off' : 'on';
    try {
      await fetch('/api/build/admin/settings', {
        method: 'PUT', headers: hdrs(),
        body: JSON.stringify({ key, value: next }),
      });
      setSettings(prev => ({ ...prev, [key]: next }));
      setMsg(key + ' = ' + next);
    } catch (e) { setMsg('Error toggling setting'); }
    setTimeout(() => setMsg(''), 3000);
  }

  async function sendEmail() {
    if (!emailTo || !emailSubject || !emailBody) { setMsg('Fill all email fields'); return; }
    try {
      const res = await fetch('/api/build/admin/email', {
        method: 'POST', headers: hdrs(),
        body: JSON.stringify({ to: emailTo, subject: emailSubject, html: emailBody }),
      });
      const d = await res.json();
      if (d.ok) { setMsg('Email sent to ' + emailTo); setEmailTo(''); setEmailSubject(''); setEmailBody(''); }
      else setMsg('Error: ' + (d.error || 'unknown'));
    } catch (e) { setMsg('Error: ' + e.message); }
    setTimeout(() => setMsg(''), 3000);
  }

  const S = {
    page: { fontFamily: 'var(--mono)', color: 'var(--ink)', padding: 32, maxWidth: 900, margin: '0 auto' },
    h1: { fontSize: 22, fontWeight: 700, marginBottom: 24, color: 'var(--accent)' },
    h2: { fontSize: 16, fontWeight: 700, marginTop: 32, marginBottom: 12, color: 'var(--ink)' },
    input: { padding: '10px 14px', fontSize: 14, fontFamily: 'var(--mono)', background: 'var(--paper)', border: '1px solid var(--line-paper-2)', borderRadius: 'var(--r-sm)', color: 'var(--ink)', width: '100%', boxSizing: 'border-box' },
    btn: { padding: '10px 20px', fontSize: 13, fontFamily: 'var(--mono)', fontWeight: 700, background: 'var(--accent)', color: 'var(--paper)', border: 'none', borderRadius: 'var(--r-sm)', cursor: 'pointer' },
    btnGhost: { padding: '10px 20px', fontSize: 13, fontFamily: 'var(--mono)', background: 'transparent', color: 'var(--ink-dim)', border: '1px solid var(--line-paper-2)', borderRadius: 'var(--r-sm)', cursor: 'pointer' },
    td: { padding: '8px 12px', fontSize: 12, borderBottom: '1px solid var(--line-paper)', verticalAlign: 'middle' },
    th: { padding: '8px 12px', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--ink-mute)', borderBottom: '2px solid var(--line-paper-2)', textAlign: 'left' },
    select: { padding: '6px 10px', fontSize: 12, fontFamily: 'var(--mono)', background: 'var(--paper)', border: '1px solid var(--line-paper-2)', borderRadius: 4, color: 'var(--ink)' },
    msg: { padding: '10px 16px', fontSize: 13, background: 'rgba(232,115,74,0.1)', border: '1px solid rgba(232,115,74,0.3)', borderRadius: 6, color: 'var(--accent-deep)', marginBottom: 16, fontFamily: 'var(--mono)' },
    textarea: { padding: '10px 14px', fontSize: 13, fontFamily: 'var(--mono)', background: 'var(--paper)', border: '1px solid var(--line-paper-2)', borderRadius: 'var(--r-sm)', color: 'var(--ink)', width: '100%', boxSizing: 'border-box', minHeight: 80, resize: 'vertical' },
  };

  // Login gate
  if (!authed) {
    return (
      <div style={{ ...S.page, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '60vh' }}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <h1 style={S.h1}>Build Lab Admin</h1>
          {msg && <div style={S.msg}>{msg}</div>}
          <input
            type="password" autoFocus placeholder="Admin secret"
            value={secret} onChange={e => setSecret(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && tryAuth()}
            style={{ ...S.input, marginBottom: 12 }}
          />
          <button onClick={() => tryAuth()} style={S.btn}>Authenticate</button>
        </div>
      </div>
    );
  }

  return (
    <div style={S.page}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1 style={S.h1}>Build Lab Admin</h1>
        <button onClick={() => { window.location.hash = ''; window.location.reload(); }} style={S.btnGhost}>Back to site</button>
      </div>

      {msg && <div style={S.msg}>{msg}</div>}

      {/* Settings */}
      <h2 style={S.h2}>Settings</h2>
      <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
          <span style={{
            display: 'inline-block', width: 40, height: 22, borderRadius: 11,
            background: settings.login_notify === 'on' ? 'var(--accent)' : 'var(--line-paper-2)',
            position: 'relative', transition: 'background .2s', cursor: 'pointer',
          }} onClick={() => toggleSetting('login_notify')}>
            <span style={{
              position: 'absolute', top: 2, left: settings.login_notify === 'on' ? 20 : 2,
              width: 18, height: 18, borderRadius: 9, background: 'var(--paper)',
              transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.2)',
            }} />
          </span>
          Login notifications {settings.login_notify === 'on' ? 'ON' : 'OFF'}
        </label>
        {settings.login_notify_email && (
          <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>
            sending to {settings.login_notify_email}
          </span>
        )}
      </div>

      {/* Users */}
      <h2 style={S.h2}>Users ({total})</h2>
      {loading ? <div style={{ color: 'var(--ink-mute)', fontSize: 13 }}>Loading...</div> : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={S.th}>ID</th>
                <th style={S.th}>Email</th>
                <th style={S.th}>Name</th>
                <th style={S.th}>Plan</th>
                <th style={S.th}>Created</th>
                <th style={S.th}>Last Login</th>
                <th style={S.th}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map(u => (
                <tr key={u.id}>
                  <td style={S.td}>{u.id}</td>
                  <td style={S.td}>{u.email}</td>
                  <td style={S.td}>{u.display_name || '-'}</td>
                  <td style={S.td}>
                    <select style={S.select} value={u.plan} onChange={e => updateUser(u.id, 'plan', e.target.value)}>
                      <option value="free">free</option>
                      <option value="pro">pro</option>
                      <option value="lifetime">lifetime</option>
                    </select>
                  </td>
                  <td style={S.td}>{u.created_at ? u.created_at.slice(0, 10) : '-'}</td>
                  <td style={S.td}>{u.last_login_at ? u.last_login_at.slice(0, 16).replace('T', ' ') : 'never'}</td>
                  <td style={S.td}>
                    <button style={{ ...S.btnGhost, padding: '4px 10px', fontSize: 11 }}
                      onClick={() => { setEmailTo(u.email); window.scrollTo(0, document.body.scrollHeight); }}>
                      Email
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {total > 50 && (
            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              {page > 1 && <button onClick={() => loadUsers(page - 1)} style={S.btnGhost}>Prev</button>}
              <span style={{ fontSize: 12, color: 'var(--ink-mute)', padding: '8px 0' }}>Page {page} of {Math.ceil(total / 50)}</span>
              {page * 50 < total && <button onClick={() => loadUsers(page + 1)} style={S.btnGhost}>Next</button>}
            </div>
          )}
        </div>
      )}

      {/* Send email */}
      <h2 style={S.h2}>Send Email</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 500 }}>
        <input placeholder="To (email)" value={emailTo} onChange={e => setEmailTo(e.target.value)} style={S.input} />
        <input placeholder="Subject" value={emailSubject} onChange={e => setEmailSubject(e.target.value)} style={S.input} />
        <textarea placeholder="HTML body" value={emailBody} onChange={e => setEmailBody(e.target.value)} style={S.textarea} />
        <button onClick={sendEmail} style={{ ...S.btn, alignSelf: 'flex-start' }}>Send</button>
      </div>
    </div>
  );
}

window.BuildLabAdmin = BuildLabAdmin;
