// screen-admin.jsx — Platform admin: health dashboard, build queue, webhooks, merchants
// Exports: AdminScreen

const MERCHANTS = [
  { id: 'M-001', name: 'Nour Cairo', domain: 'nour-cairo.myshopify.com', plan: 'Growth', status: 'trialing', installs: 1240, sync: 'synced', lastActive: '2 min ago' },
  { id: 'M-002', name: 'Marcus Electronics', domain: 'marcus-electronics.myshopify.com', plan: 'Pro', status: 'active', installs: 3847, sync: 'synced', lastActive: '14 min ago' },
  { id: 'M-003', name: 'Layla Beauty', domain: 'layla-beauty.myshopify.com', plan: 'Starter', status: 'active', installs: 420, sync: 'synced', lastActive: '1h ago' },
  { id: 'M-004', name: 'Gulf Gadgets', domain: 'gulf-gadgets.myshopify.com', plan: 'Growth', status: 'past_due', installs: 890, sync: 'error', lastActive: '3h ago' },
  { id: 'M-005', name: 'Cedar Home', domain: 'cedar-home.myshopify.com', plan: 'Starter', status: 'trialing', installs: 0, sync: 'synced', lastActive: '5h ago' },
];

const BUILDS = [
  { id: '#B-0042', merchant: 'Nour Cairo', platform: 'iOS', version: '1.0.0', started: '14:22', duration: '8m 14s', status: 'in review' },
  { id: '#B-0041', merchant: 'Nour Cairo', platform: 'Android', version: '1.0.0', started: '14:20', duration: '6m 02s', status: 'building' },
  { id: '#B-0040', merchant: 'Cedar Home', platform: 'iOS', version: '1.0.0', started: '12:05', duration: '7m 48s', status: 'live' },
  { id: '#B-0039', merchant: 'Cedar Home', platform: 'Android', version: '1.0.0', started: '12:03', duration: '5m 21s', status: 'live' },
  { id: '#B-0038', merchant: 'Gulf Gadgets', platform: 'iOS', version: '2.1.0', started: '09:14', duration: '—', status: 'error' },
];

const WEBHOOKS = [
  { id: 'wh-9821', merchant: 'Marcus Electronics', event: 'products/update', received: '14:41:02', status: 'live', latency: '48ms' },
  { id: 'wh-9820', merchant: 'Nour Cairo', event: 'orders/create', received: '14:40:18', status: 'live', latency: '62ms' },
  { id: 'wh-9819', merchant: 'Gulf Gadgets', event: 'products/update', received: '14:38:44', status: 'error', latency: '—' },
  { id: 'wh-9818', merchant: 'Layla Beauty', event: 'collections/update', received: '14:36:11', status: 'live', latency: '55ms' },
  { id: 'wh-9817', merchant: 'Marcus Electronics', event: 'inventory_levels/update', received: '14:34:09', status: 'live', latency: '41ms' },
  { id: 'wh-9816', merchant: 'Gulf Gadgets', event: 'products/update', received: '14:30:22', status: 'error', latency: '—' },
];

const AdminScreen = ({ tweaks }) => {
  const [tab, setTab] = React.useState('health');
  const { dark } = tweaks;

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';
  const rowHover = dark ? 'rgba(255,255,255,0.03)' : 'var(--sand-50)';

  const thStyle = { textAlign: 'left', padding: '10px 16px', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, borderBottom: `1px solid ${cardBorder}`, background: dark ? 'rgba(0,0,0,0.15)' : 'var(--paper-bright)', whiteSpace: 'nowrap' };
  const tdStyle = { padding: '12px 16px', fontSize: 13 };

  const HealthTab = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { label: 'Active merchants', value: '5', sub: '3 trialing, 2 paid', icon: 'users', ok: true },
          { label: 'Queue depth', value: '12', sub: 'Redis jobs pending', icon: 'layers', ok: true },
          { label: 'Failed webhooks · 24h', value: '2', sub: 'Gulf Gadgets HMAC', icon: 'alert-triangle', ok: false },
          { label: 'Platform uptime', value: '99.8%', sub: 'Last 30 days', icon: 'activity', ok: true },
        ].map((m, i) => (
          <div key={i} style={{ background: cardBg, border: `1px solid ${m.ok ? cardBorder : 'var(--amber)'}`, borderRadius: 10, padding: '18px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: subColor, fontWeight: 500 }}>{m.label}</div>
              <i data-lucide={m.icon} style={{ width: 15, height: 15, color: m.ok ? subColor : 'var(--amber)' }}></i>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, lineHeight: 1, color: m.ok ? textColor : 'var(--amber)', marginBottom: 6 }}>{m.value}</div>
            <div style={{ fontSize: 11, color: m.ok ? subColor : 'var(--amber)' }}>{m.sub}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Sync health */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ padding: '14px 18px', borderBottom: `1px solid ${cardBorder}`, fontSize: 13, fontWeight: 600, color: textColor }}>Merchant sync health</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              {['Merchant', 'Sync', 'Last active'].map(h => <th key={h} style={thStyle}>{h}</th>)}
            </tr></thead>
            <tbody>
              {MERCHANTS.map((m, i) => (
                <tr key={m.id} style={{ borderBottom: i < MERCHANTS.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}
                  onMouseEnter={e => e.currentTarget.style.background = rowHover}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ ...tdStyle, fontWeight: 500, color: textColor }}>{m.name}</td>
                  <td style={tdStyle}><window.StatusPill status={m.sync === 'error' ? 'error' : 'synced'} /></td>
                  <td style={{ ...tdStyle, color: subColor, fontSize: 12 }}>{m.lastActive}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* API metrics */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 16 }}>API & performance</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { label: 'API latency p95', value: '218ms', target: '< 500ms', ok: true },
              { label: 'Webhook processing', value: '2.4s', target: '< 5s', ok: true },
              { label: 'App cold start', value: '2.1s', target: '< 3s', ok: true },
              { label: 'Crash-free sessions', value: '99.7%', target: '> 99.5%', ok: true },
              { label: 'Data sync latency', value: '3.2 min', target: '< 5 min', ok: true },
            ].map(row => (
              <div key={row.label} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, color: textColor }}>{row.label}</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: row.ok ? 'var(--mint)' : 'var(--ruby)' }}>{row.value}</span>
                  <span style={{ fontSize: 11, color: subColor }}>target {row.target}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );

  const BuildsTab = () => (
    <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
      <div style={{ padding: '16px 20px', borderBottom: `1px solid ${cardBorder}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Build queue — today</div>
        <div style={{ display: 'flex', align: 'center', gap: 6, fontSize: 12, color: subColor }}>
          <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--amber)', alignSelf: 'center' }}></div>
          1 building
        </div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>{['Build ID', 'Merchant', 'Platform', 'Version', 'Started', 'Duration', 'Status', ''].map(h => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
        <tbody>
          {BUILDS.map((b, i) => (
            <tr key={b.id} style={{ borderBottom: i < BUILDS.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}
              onMouseEnter={e => e.currentTarget.style.background = rowHover}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{b.id}</td>
              <td style={{ ...tdStyle, color: textColor, fontWeight: 500 }}>{b.merchant}</td>
              <td style={{ ...tdStyle, color: subColor }}>{b.platform}</td>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 12, color: subColor }}>v{b.version}</td>
              <td style={{ ...tdStyle, color: subColor, fontSize: 12 }}>{b.started}</td>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 12, color: subColor }}>{b.duration}</td>
              <td style={tdStyle}><window.StatusPill status={b.status} /></td>
              <td style={tdStyle}>
                {b.status === 'error' && <window.Button size="sm" variant="secondary" icon="refresh-cw">Retry</window.Button>}
                {b.status === 'building' && <window.Button size="sm" variant="ghost" icon="eye">View logs</window.Button>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const WebhooksTab = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--amber-tint)', border: '1px solid var(--amber)', borderRadius: 10, padding: '12px 16px' }}>
        <i data-lucide="alert-triangle" style={{ width: 16, height: 16, color: 'var(--amber)', flexShrink: 0 }}></i>
        <div>
          <div style={{ fontSize: 13, fontWeight: 500, color: '#5E4307' }}>2 failed webhooks from Gulf Gadgets</div>
          <div style={{ fontSize: 12, color: '#7A5A0A', marginTop: 2 }}>HMAC verification failed — webhook secret may need rotation. <span style={{ textDecoration: 'underline', cursor: 'pointer' }}>Fix now →</span></div>
        </div>
        <window.Button size="sm" style={{ marginLeft: 'auto', flexShrink: 0 }}>Rotate secret</window.Button>
      </div>

      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${cardBorder}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Webhook processing log</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <window.Button size="sm" variant="secondary" icon="refresh-cw">Refresh</window.Button>
            <window.Button size="sm" variant="ghost" icon="external-link">Full logs</window.Button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>{['ID', 'Merchant', 'Event', 'Received', 'Latency', 'Status'].map(h => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
          <tbody>
            {WEBHOOKS.map((w, i) => (
              <tr key={w.id} style={{ borderBottom: i < WEBHOOKS.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}
                onMouseEnter={e => e.currentTarget.style.background = rowHover}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 11, color: subColor }}>{w.id}</td>
                <td style={{ ...tdStyle, fontWeight: 500, color: textColor }}>{w.merchant}</td>
                <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 11, color: textColor }}>{w.event}</td>
                <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 11, color: subColor }}>{w.received}</td>
                <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 12, color: w.status === 'live' ? 'var(--mint)' : subColor }}>{w.latency}</td>
                <td style={tdStyle}><window.StatusPill status={w.status === 'live' ? 'live' : 'error'} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  const MerchantsTab = () => (
    <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
      <div style={{ padding: '16px 20px', borderBottom: `1px solid ${cardBorder}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>All merchants ({MERCHANTS.length})</div>
        <window.Button size="sm" icon="user-plus">Invite merchant</window.Button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>{['ID', 'Merchant', 'Store', 'Plan', 'Installs', 'Last active', 'Status'].map(h => <th key={h} style={thStyle}>{h}</th>)}</tr></thead>
        <tbody>
          {MERCHANTS.map((m, i) => (
            <tr key={m.id} style={{ borderBottom: i < MERCHANTS.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}
              onMouseEnter={e => e.currentTarget.style.background = rowHover}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 11, color: subColor }}>{m.id}</td>
              <td style={{ ...tdStyle, fontWeight: 500, color: textColor }}>{m.name}</td>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 11, color: subColor }}>{m.domain}</td>
              <td style={{ ...tdStyle, color: textColor }}>{m.plan}</td>
              <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: 13, color: textColor }}>{m.installs.toLocaleString()}</td>
              <td style={{ ...tdStyle, color: subColor, fontSize: 12 }}>{m.lastActive}</td>
              <td style={tdStyle}><window.StatusPill status={m.status} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const tabs = [{ id: 'health', label: 'Health' }, { id: 'builds', label: 'Build queue', badge: '2' }, { id: 'webhooks', label: 'Webhooks', badge: '2' }, { id: 'merchants', label: 'Merchants' }];
  const content = { health: <HealthTab />, builds: <BuildsTab />, webhooks: <WebhooksTab />, merchants: <MerchantsTab /> };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1100 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i data-lucide="shield" style={{ width: 18, height: 18, color: 'var(--honey)' }}></i>
        </div>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 28, color: textColor, margin: 0 }}>Platform admin</h1>
          <div style={{ fontSize: 12, color: subColor }}>Accessible only to platform operators.</div>
        </div>
      </div>
      <window.Tabs tabs={tabs} active={tab} onSelect={setTab} />
      {content[tab]}
    </div>
  );
};

window.AdminScreen = AdminScreen;
