// Platform admin dashboard — fetches live data via JWT auth.
// Login → /api/auth/login; authed calls → /api/admin/*

const TOKEN_KEY = 'dsc-admin-token';

const authedFetch = (path, opts = {}) => {
  const token = localStorage.getItem(TOKEN_KEY);
  return fetch((window.__API_BASE || '') + path, {
    ...opts,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts.headers || {}),
    },
  });
};

const Admin = ({ nav }) => {
  const [me, setMe] = React.useState(null);
  const [checking, setChecking] = React.useState(true);
  const [section, setSection] = React.useState('Overview');

  // On mount, try to resolve current user from stored token.
  React.useEffect(() => {
    const token = localStorage.getItem(TOKEN_KEY);
    if (!token) { setChecking(false); return; }
    authedFetch('/api/auth/me')
      .then((r) => r.ok ? r.json() : null)
      .then((user) => {
        if (user?.role === 'admin') setMe(user);
        else if (user) localStorage.removeItem(TOKEN_KEY);
      })
      .finally(() => setChecking(false));
  }, []);

  if (checking) {
    return <div style={{ padding: 80, textAlign: 'center', fontFamily: 'var(--ff-mono)', fontSize: 11, textTransform: 'uppercase', color: 'var(--ink-3)' }}>Checking session…</div>;
  }

  if (!me) return <AdminLogin onSignedIn={setMe} />;

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '240px 1fr' }}>
      {/* Sidebar */}
      <aside style={{ borderRight: '1px solid var(--line)', padding: '24px 20px', background: 'var(--bg-2)', minHeight: '100vh' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>DSC admin</div>
        <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>{me.email}</div>
        <div className="mono muted" style={{ fontSize: 11, marginBottom: 24, textTransform: 'uppercase' }}>{me.role}</div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {['Overview', 'Leads', 'Claims', 'Users'].map((s) => (
            <button key={s} onClick={() => setSection(s)}
              style={{ textAlign: 'left', padding: '8px 10px', borderRadius: 4, fontSize: 13,
                       background: section === s ? 'var(--bg)' : 'transparent',
                       color: section === s ? 'var(--ink)' : 'var(--ink-2)',
                       fontWeight: section === s ? 500 : 400 }}>
              {s}
            </button>
          ))}
        </div>

        <button onClick={() => { localStorage.removeItem(TOKEN_KEY); setMe(null); }}
          className="btn" style={{ marginTop: 24, fontSize: 12, width: '100%' }}>
          Sign out
        </button>
      </aside>

      {/* Content */}
      <main style={{ padding: 32 }}>
        {section === 'Overview' && <AdminOverview />}
        {section === 'Leads' && <AdminLeads />}
        {section === 'Claims' && <AdminClaims />}
        {section === 'Users' && <AdminUsers />}
      </main>
    </div>
  );
};

// --- Login ---------------------------------------------------------------

const AdminLogin = ({ onSignedIn }) => {
  const [email, setEmail] = React.useState('admin@droneshowcompanies.com');
  const [password, setPassword] = React.useState('');
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const res = await fetch((window.__API_BASE||'') + '/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(body.error || 'Login failed');
      if (body.user?.role !== 'admin') throw new Error('This account is not an admin.');
      localStorage.setItem(TOKEN_KEY, body.token);
      onSignedIn(body.user);
    } catch (ex) {
      setErr(ex.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="page" style={{ display: 'grid', placeItems: 'center', minHeight: '80vh' }}>
      <form onSubmit={submit} className="card" style={{ padding: 32, width: 360 }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>Admin</div>
        <h2 style={{ fontFamily: 'var(--ff-display)', fontSize: 28, margin: '0 0 20px', fontWeight: 400 }}>Sign in</h2>
        <label className="mono muted" style={{ fontSize: 11, textTransform: 'uppercase' }}>Email</label>
        <input className="input" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} style={{ marginTop: 4, marginBottom: 14 }} />
        <label className="mono muted" style={{ fontSize: 11, textTransform: 'uppercase' }}>Password</label>
        <input className="input" type="password" required value={password} onChange={(e) => setPassword(e.target.value)} style={{ marginTop: 4, marginBottom: 14 }} />
        {err && <div style={{ color: 'oklch(55% 0.2 25)', fontSize: 13, marginBottom: 12 }}>{err}</div>}
        <button type="submit" className="btn btn-primary" disabled={busy} style={{ width: '100%' }}>{busy ? 'Signing in…' : 'Sign in'}</button>
        <div className="muted" style={{ fontSize: 11, marginTop: 14, lineHeight: 1.5 }}>
          Seeded default: <code style={{ fontFamily: 'var(--ff-mono)' }}>admin@droneshowcompanies.com</code> / <code style={{ fontFamily: 'var(--ff-mono)' }}>admin123</code>
        </div>
      </form>
    </div>
  );
};

// --- Overview ------------------------------------------------------------

const AdminOverview = () => {
  const [stats, setStats] = React.useState(null);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    authedFetch('/api/admin/stats')
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then(setStats)
      .catch(setErr);
  }, []);

  if (err) return <div style={{ color: 'oklch(55% 0.2 25)' }}>Error: {String(err)}</div>;
  if (!stats) return <div className="mono muted" style={{ fontSize: 11 }}>Loading stats…</div>;

  const cards = [
    ['Operators', stats.operators, `${stats.claimedOperators} claimed`],
    ['Manufacturers and Tools', stats.manufacturers, null],
    ['Designers', stats.designers, null],
    ['Blog posts', stats.posts, null],
    ['Total leads', stats.quotes, `${stats.newQuotes} new`],
    ['Pending claims', stats.claimsPending, null],
    ['Users', stats.users, null],
  ];

  return (
    <div>
      <h1 style={{ fontFamily: 'var(--ff-display)', fontSize: 36, margin: '0 0 24px', fontWeight: 400, letterSpacing: '-0.02em' }}>Overview</h1>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 16 }}>
        {cards.map(([label, value, hint]) => (
          <div key={label} className="card" style={{ padding: 20 }}>
            <div className="mono muted" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 8 }}>{label}</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 36, lineHeight: 1 }}>{value}</div>
            {hint && <div className="mono muted" style={{ fontSize: 11, marginTop: 4 }}>{hint}</div>}
          </div>
        ))}
      </div>
    </div>
  );
};

// --- Leads (quote requests) ---------------------------------------------

const AdminLeads = () => {
  const [rows, setRows] = React.useState(null);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    authedFetch('/api/admin/quotes').then((r) => r.ok ? r.json() : Promise.reject(r.statusText)).then(setRows).catch(setErr);
  }, []);

  if (err) return <div style={{ color: 'oklch(55% 0.2 25)' }}>Error: {String(err)}</div>;
  if (!rows) return <div className="mono muted" style={{ fontSize: 11 }}>Loading leads…</div>;

  return (
    <div>
      <h1 style={{ fontFamily: 'var(--ff-display)', fontSize: 36, margin: '0 0 24px', fontWeight: 400, letterSpacing: '-0.02em' }}>Leads</h1>
      {rows.length === 0 ? (
        <div className="card" style={{ padding: 24, color: 'var(--ink-3)' }}>No quote requests yet.</div>
      ) : (
        <div className="card" style={{ overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-2)', textAlign: 'left' }}>
                {['When', 'Name', 'Email', 'Event', 'Location', 'Budget', 'Operator', 'Status'].map((h) => (
                  <th key={h} className="mono" style={{ padding: '10px 12px', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', fontWeight: 500 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((q) => (
                <tr key={q.id} style={{ borderTop: '1px solid var(--line)' }}>
                  <td className="mono" style={{ padding: '10px 12px', fontSize: 11 }}>{new Date(q.created_at).toLocaleDateString()}</td>
                  <td style={{ padding: '10px 12px' }}>{q.client_name || '—'}</td>
                  <td style={{ padding: '10px 12px' }}>{q.client_email}</td>
                  <td style={{ padding: '10px 12px' }}>{q.event_type || '—'}</td>
                  <td style={{ padding: '10px 12px' }}>{q.location || '—'}</td>
                  <td style={{ padding: '10px 12px' }}>{q.budget || '—'}</td>
                  <td style={{ padding: '10px 12px' }}>{q.operator_name || '—'}</td>
                  <td style={{ padding: '10px 12px' }}><span className="chip" style={{ fontSize: 10 }}>{q.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// --- Claims --------------------------------------------------------------

const AdminClaims = () => {
  const [rows, setRows] = React.useState(null);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    authedFetch('/api/admin/claims').then((r) => r.ok ? r.json() : Promise.reject(r.statusText)).then(setRows).catch(setErr);
  }, []);

  if (err) return <div style={{ color: 'oklch(55% 0.2 25)' }}>Error: {String(err)}</div>;
  if (!rows) return <div className="mono muted" style={{ fontSize: 11 }}>Loading claims…</div>;

  return (
    <div>
      <h1 style={{ fontFamily: 'var(--ff-display)', fontSize: 36, margin: '0 0 24px', fontWeight: 400, letterSpacing: '-0.02em' }}>Profile claims</h1>
      {rows.length === 0 ? (
        <div className="card" style={{ padding: 24, color: 'var(--ink-3)' }}>No claim requests yet.</div>
      ) : (
        <div className="card" style={{ overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-2)', textAlign: 'left' }}>
                {['Requested', 'Type', 'Profile', 'Claimant', 'Email', 'Status'].map((h) => (
                  <th key={h} className="mono" style={{ padding: '10px 12px', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', fontWeight: 500 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((c) => (
                <tr key={c.id} style={{ borderTop: '1px solid var(--line)' }}>
                  <td className="mono" style={{ padding: '10px 12px', fontSize: 11 }}>{new Date(c.requested_at).toLocaleString()}</td>
                  <td style={{ padding: '10px 12px' }}>{c.entity_type}</td>
                  <td style={{ padding: '10px 12px' }}>{c.entity_name || `#${c.entity_id}`}</td>
                  <td style={{ padding: '10px 12px' }}>{c.claimant_name || '—'}</td>
                  <td style={{ padding: '10px 12px' }}>{c.claimant_email}</td>
                  <td style={{ padding: '10px 12px' }}><span className="chip" style={{ fontSize: 10 }}>{c.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// --- Users ---------------------------------------------------------------

const AdminUsers = () => {
  const [rows, setRows] = React.useState(null);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    authedFetch('/api/admin/users').then((r) => r.ok ? r.json() : Promise.reject(r.statusText)).then(setRows).catch(setErr);
  }, []);

  if (err) return <div style={{ color: 'oklch(55% 0.2 25)' }}>Error: {String(err)}</div>;
  if (!rows) return <div className="mono muted" style={{ fontSize: 11 }}>Loading users…</div>;

  return (
    <div>
      <h1 style={{ fontFamily: 'var(--ff-display)', fontSize: 36, margin: '0 0 24px', fontWeight: 400, letterSpacing: '-0.02em' }}>Users</h1>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: 'var(--bg-2)', textAlign: 'left' }}>
              {['Created', 'Email', 'Role'].map((h) => (
                <th key={h} className="mono" style={{ padding: '10px 12px', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', fontWeight: 500 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((u) => (
              <tr key={u.id} style={{ borderTop: '1px solid var(--line)' }}>
                <td className="mono" style={{ padding: '10px 12px', fontSize: 11 }}>{new Date(u.created_at).toLocaleDateString()}</td>
                <td style={{ padding: '10px 12px' }}>{u.email}</td>
                <td style={{ padding: '10px 12px' }}><span className="chip" style={{ fontSize: 10 }}>{u.role}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

Object.assign(window, { Admin });
