// ─────────────────────────────────────────────
// DEV_AppDetail_API.jsx
// API tab — External APIs + Data API sub-tabs
//
// Sub-tabs:
//   External APIs — browse catalog, enter/save keys
//   Data API      — stub (future: JSON/CSV export endpoint config)
//
// Style prefix: SAPI (avoid Babel var collision)
// ─────────────────────────────────────────────

// ── Category metadata ─────────────────────────
const API_CATEGORIES = {
  maps:          { label: 'Maps',          icon: '🗺️'  },
  weather:       { label: 'Weather',       icon: '🌤️'  },
  communication: { label: 'Communication', icon: '📱'  },
  news:          { label: 'News',          icon: '📰'  },
  sports:        { label: 'Sports',        icon: '🏆'  },
  finance:       { label: 'Finance',       icon: '💱'  },
  payments:      { label: 'Payments',      icon: '💳'  },
  media:         { label: 'Media',         icon: '▶️'  },
  geolocation:   { label: 'Geolocation',   icon: '📍'  },
  other:         { label: 'Other',         icon: '🔌'  },
};

// ── Single API card ───────────────────────────
function APIServiceCard({ service, savedKeys, appId, onSave, onDelete }) {
  const [open,     setOpen]     = React.useState(false);
  const [fields,   setFields]   = React.useState({});
  const [revealed, setRevealed] = React.useState(false);
  const [saving,   setSaving]   = React.useState(false);
  const [saved,    setSaved]    = React.useState(false);
  const [deleting, setDeleting] = React.useState(false);
  const [error,    setError]    = React.useState(null);

  // Is this service already connected?
  const isConnected = savedKeys && Object.keys(savedKeys).length > 0;

  // When opening, pre-fill fields with saved (masked) values
  React.useEffect(() => {
    if (open) {
      const initial = {};
      (service.catalog_keys || []).forEach(kDef => {
        initial[kDef.key] = savedKeys?.[kDef.key] || '';
      });
      setFields(initial);
      setRevealed(false);
      setSaved(false);
      setError(null);
    }
  }, [open]);

  async function handleReveal() {
    if (revealed) { setRevealed(false); return; }
    try {
      const res  = await apiFetch(`${API_BASE}/v6/dev/api/keys?app=${appId}&reveal=${service.catalog_slug}`);
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      const plain = data.keys?.[service.catalog_slug] || {};
      setFields(prev => ({ ...prev, ...plain }));
      setRevealed(true);
    } catch(err) {
      setError(`Could not reveal: ${err.message}`);
    }
  }

  async function handleSave() {
    setSaving(true); setSaved(false); setError(null);
    try {
      await onSave(service.catalog_slug, fields);
      setSaved(true);
      setTimeout(() => { setSaved(false); setOpen(false); }, 1200);
    } catch(err) {
      setError(err.message);
    }
    setSaving(false);
  }

  async function handleDelete() {
    if (!window.confirm(`Remove all saved keys for ${service.catalog_name}?`)) return;
    setDeleting(true);
    try {
      await onDelete(service.catalog_slug);
      setOpen(false);
    } catch(err) {
      setError(err.message);
    }
    setDeleting(false);
  }

  const catMeta = API_CATEGORIES[service.catalog_category] || API_CATEGORIES.other;

  return (
    <div style={{ ...SAPI.serviceCard, ...(isConnected ? SAPI.serviceCardConnected : {}) }}>

      {/* ── Card header row ── */}
      <div style={SAPI.serviceHeader} onClick={() => setOpen(o => !o)}>
        <div style={SAPI.serviceLeft}>
          <span style={SAPI.serviceIcon}>{service.catalog_icon}</span>
          <div>
            <div style={SAPI.serviceName}>{service.catalog_name}</div>
            <div style={SAPI.serviceCat}>
              {catMeta.icon} {catMeta.label}
            </div>
          </div>
        </div>
        <div style={SAPI.serviceRight}>
          {isConnected
            ? <span style={SAPI.badgeConnected}>✓ Connected</span>
            : <span style={SAPI.badgeEmpty}>Not configured</span>
          }
          <span style={SAPI.chevron}>{open ? '▲' : '▼'}</span>
        </div>
      </div>

      {/* ── Expanded body ── */}
      {open && (
        <div style={SAPI.serviceBody}>
          <div style={SAPI.serviceDesc}>{service.catalog_desc}</div>

          {service.catalog_url && (
            <a href={service.catalog_url} target="_blank" rel="noopener" style={SAPI.signupLink}>
              🔗 Get API keys at {new URL(service.catalog_url).hostname}
            </a>
          )}

          {/* Key fields */}
          <div style={SAPI.keyFields}>
            {(service.catalog_keys || []).map(kDef => (
              <div key={kDef.key} style={SAPI.keyRow}>
                <label style={SAPI.keyLabel}>{kDef.label}</label>
                <div style={SAPI.keyInputWrap}>
                  <input
                    style={SAPI.keyInput}
                    type={revealed ? 'text' : 'password'}
                    value={fields[kDef.key] || ''}
                    placeholder={kDef.placeholder || ''}
                    onChange={e => setFields(prev => ({ ...prev, [kDef.key]: e.target.value }))}
                    autoComplete="off"
                    spellCheck={false}
                  />
                </div>
              </div>
            ))}
          </div>

          {error && <div style={SAPI.errorMsg}>{error}</div>}

          {/* Action row */}
          <div style={SAPI.actionRow}>
            <div style={{ display:'flex', gap:8 }}>
              <button style={SAPI.saveBtn} onClick={handleSave} disabled={saving}>
                {saving ? 'Saving…' : saved ? '✓ Saved' : 'Save Keys'}
              </button>
              {isConnected && (
                <button style={SAPI.revealBtn} onClick={handleReveal}>
                  {revealed ? '🙈 Hide' : '👁 Show Keys'}
                </button>
              )}
            </div>
            {isConnected && (
              <button style={SAPI.deleteBtn} onClick={handleDelete} disabled={deleting}>
                {deleting ? 'Removing…' : '🗑 Remove'}
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// ── External APIs sub-tab ─────────────────────
function ExternalAPIsTab({ app }) {
  const [catalog,   setCatalog]   = React.useState([]);
  const [savedKeys, setSavedKeys] = React.useState({});
  const [loading,   setLoading]   = React.useState(true);
  const [filter,    setFilter]    = React.useState('all');
  const [search,    setSearch]    = React.useState('');
  const [error,     setError]     = React.useState(null);

  // Use app_id from prop (DEV context), not window.APP_ID
  const appId = app.app_id;
  // Expose for child components via module-level var
  window.__DEV_API_APP_ID__ = appId;

  React.useEffect(() => {
    setLoading(true);
    Promise.all([
      apiFetch(`${API_BASE}/v6/dev/api/catalog`).then(r => r.json()),
      apiFetch(`${API_BASE}/v6/dev/api/keys?app=${appId}`).then(r => r.json()),
    ])
      .then(([catData, keyData]) => {
        if (catData.status === 'ok') setCatalog(catData.catalog || []);
        if (keyData.status === 'ok') setSavedKeys(keyData.keys || {});
      })
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, [appId]);

  async function handleSave(slug, fields) {
    const res  = await apiFetch(`${API_BASE}/v6/dev/api/keys?app=${appId}`, {
      method: 'POST',
      body:   JSON.stringify({ slug, keys: fields }),
    });
    const data = await res.json();
    if (data.status !== 'ok') throw new Error(data.message);
    // Refresh saved keys (masked)
    const kr   = await apiFetch(`${API_BASE}/v6/dev/api/keys?app=${appId}`);
    const kd   = await kr.json();
    if (kd.status === 'ok') setSavedKeys(kd.keys || {});
  }

  async function handleDelete(slug) {
    const url  = `${API_BASE}/v6/dev/api/keys?app=${appId}&slug=${slug}`;
    const res2 = await apiFetch(url, { method: 'DELETE' });
    const data = await res2.json();
    if (data.status !== 'ok') throw new Error(data.message);
    const kr   = await apiFetch(`${API_BASE}/v6/dev/api/keys?app=${appId}`);
    const kd   = await kr.json();
    if (kd.status === 'ok') setSavedKeys(kd.keys || {});
  }

  // Connected count
  const connectedCount = Object.keys(savedKeys).filter(k => Object.keys(savedKeys[k] || {}).length > 0).length;

  // Filter + search
  const categories = ['all', ...Array.from(new Set(catalog.map(c => c.catalog_category)))];
  const visible = catalog.filter(c => {
    if (filter !== 'all' && c.catalog_category !== filter) return false;
    if (search && !c.catalog_name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  if (loading) return <div style={SAPI.loading}>Loading API catalog…</div>;
  if (error)   return <div style={SAPI.errorMsg}>{error}</div>;

  return (
    <div>
      {/* ── Summary bar ── */}
      <div style={SAPI.summaryBar}>
        <div>
          <div style={SAPI.summaryTitle}>External API Keys</div>
          <div style={SAPI.summarySubtitle}>
            {connectedCount > 0
              ? `${connectedCount} service${connectedCount > 1 ? 's' : ''} connected`
              : 'No APIs connected yet — add a key below to get started'}
          </div>
        </div>
        <input
          style={SAPI.searchBox}
          placeholder="🔍 Search APIs…"
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>

      {/* ── Category filter pills ── */}
      <div style={SAPI.pills}>
        {categories.map(cat => {
          const meta = cat === 'all' ? { label:'All', icon:'✦' } : (API_CATEGORIES[cat] || { label: cat, icon:'🔌' });
          return (
            <button
              key={cat}
              style={{ ...SAPI.pill, ...(filter === cat ? SAPI.pillActive : {}) }}
              onClick={() => setFilter(cat)}
            >
              {meta.icon} {meta.label}
            </button>
          );
        })}
      </div>

      {/* ── Service cards ── */}
      <div style={SAPI.cardList}>
        {visible.length === 0 && (
          <div style={SAPI.empty}>No APIs match your filter.</div>
        )}
        {visible.map(service => (
          <APIServiceCard
            key={service.catalog_slug}
            service={service}
            savedKeys={savedKeys[service.catalog_slug] || null}
            appId={appId}
            onSave={handleSave}
            onDelete={handleDelete}
          />
        ))}
      </div>
    </div>
  );
}

// ── Data API sub-tab (stub) ───────────────────
function DataAPITab({ app }) {
  return (
    <div style={SAPI.comingSoon}>
      <div style={{ fontSize: 40, marginBottom: 16 }}>🔌</div>
      <div style={SAPI.comingSoonTitle}>Data API</div>
      <div style={SAPI.comingSoonText}>
        Generate a read-only JSON or CSV endpoint for any table in your app.<br />
        External websites and services can pull your data directly.<br /><br />
        <strong>Coming soon.</strong>
      </div>
    </div>
  );
}

// ── Main DEVAppAPI component ──────────────────
function DEVAppAPI({ app, jwt }) {
  const [sub, setSub] = React.useState('external');

  const SUB_TABS = [
    { id: 'external', label: '🔑 External APIs' },
    { id: 'data',     label: '📡 Data API'       },
  ];

  return (
    <div>
      {/* Sub-tab bar */}
      <div style={SAPI.subTabBar}>
        {SUB_TABS.map(t => (
          <button
            key={t.id}
            style={{ ...SAPI.subTab, ...(sub === t.id ? SAPI.subTabActive : {}) }}
            onClick={() => setSub(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>

      <div style={{ marginTop: 24 }}>
        {sub === 'external' && <ExternalAPIsTab app={app} />}
        {sub === 'data'     && <DataAPITab app={app} />}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// STYLES — prefix SAPI
// ─────────────────────────────────────────────
const SAPI = {
  // ── Layout ──
  summaryBar: {
    display:'flex', justifyContent:'space-between', alignItems:'flex-start',
    marginBottom:16, gap:16, flexWrap:'wrap',
  },
  summaryTitle: {
    fontSize:16, fontWeight:700, color:'#0f1923', marginBottom:3,
  },
  summarySubtitle: {
    fontSize:13, color:'#64748b',
  },
  searchBox: {
    border:'1.5px solid #e2e8f0', borderRadius:7, padding:'7px 12px',
    fontSize:13, fontFamily:'inherit', outline:'none', minWidth:200,
  },
  pills: {
    display:'flex', gap:8, flexWrap:'wrap', marginBottom:20,
  },
  pill: {
    background:'#f1f5f9', border:'1.5px solid transparent', borderRadius:20,
    padding:'5px 14px', fontSize:12, fontWeight:500, color:'#64748b',
    cursor:'pointer', fontFamily:'inherit', transition:'all 0.15s',
  },
  pillActive: {
    background:'#0f1923', color:'#fff', borderColor:'#0f1923',
  },
  cardList: {
    display:'flex', flexDirection:'column', gap:8,
  },

  // ── Service card ──
  serviceCard: {
    background:'#fff', border:'1.5px solid #e2e8f0', borderRadius:10,
    overflow:'hidden', transition:'border-color 0.15s',
  },
  serviceCardConnected: {
    borderColor:'#22c55e',
  },
  serviceHeader: {
    display:'flex', justifyContent:'space-between', alignItems:'center',
    padding:'14px 18px', cursor:'pointer',
    ':hover': { background:'#f8fafc' },
  },
  serviceLeft: {
    display:'flex', alignItems:'center', gap:14,
  },
  serviceIcon: {
    fontSize:28, lineHeight:1, flexShrink:0,
  },
  serviceName: {
    fontSize:14, fontWeight:600, color:'#0f1923', marginBottom:2,
  },
  serviceCat: {
    fontSize:11, color:'#94a3b8',
  },
  serviceRight: {
    display:'flex', alignItems:'center', gap:12,
  },
  badgeConnected: {
    background:'#dcfce7', color:'#15803d', fontSize:11, fontWeight:600,
    padding:'3px 10px', borderRadius:20,
  },
  badgeEmpty: {
    background:'#f1f5f9', color:'#94a3b8', fontSize:11,
    padding:'3px 10px', borderRadius:20,
  },
  chevron: {
    color:'#94a3b8', fontSize:12,
  },

  // ── Expanded body ──
  serviceBody: {
    borderTop:'1px solid #f1f5f9', padding:'16px 18px', background:'#fafbfc',
  },
  serviceDesc: {
    fontSize:13, color:'#475569', marginBottom:10, lineHeight:1.6,
  },
  signupLink: {
    display:'inline-block', fontSize:12, color:'#2563eb',
    textDecoration:'none', marginBottom:14,
  },

  // ── Key fields ──
  keyFields: {
    display:'flex', flexDirection:'column', gap:10, marginBottom:14,
  },
  keyRow: {
    display:'flex', flexDirection:'column', gap:4,
  },
  keyLabel: {
    fontSize:11, fontWeight:600, color:'#64748b', textTransform:'uppercase',
    letterSpacing:'0.06em',
  },
  keyInputWrap: {
    display:'flex', gap:8,
  },
  keyInput: {
    flex:1, padding:'8px 12px', border:'1.5px solid #e2e8f0', borderRadius:7,
    fontSize:13, fontFamily:'DM Mono, monospace', outline:'none',
    background:'#fff', color:'#0f1923',
  },

  // ── Actions ──
  actionRow: {
    display:'flex', justifyContent:'space-between', alignItems:'center',
  },
  saveBtn: {
    background:'#0f1923', color:'#fff', border:'none', borderRadius:7,
    padding:'8px 18px', fontSize:13, fontWeight:600, cursor:'pointer',
    fontFamily:'DM Sans, sans-serif',
  },
  revealBtn: {
    background:'#f1f5f9', color:'#374151', border:'1.5px solid #e2e8f0',
    borderRadius:7, padding:'8px 14px', fontSize:12, cursor:'pointer',
    fontFamily:'DM Sans, sans-serif',
  },
  deleteBtn: {
    background:'none', color:'#ef4444', border:'1.5px solid #fecaca',
    borderRadius:7, padding:'8px 14px', fontSize:12, cursor:'pointer',
    fontFamily:'DM Sans, sans-serif',
  },

  // ── Sub-tabs ──
  subTabBar: {
    display:'flex', gap:4, borderBottom:'2px solid #e2e8f0', marginBottom:4,
  },
  subTab: {
    background:'none', border:'none', borderBottom:'2px solid transparent',
    padding:'8px 16px', fontSize:13, fontWeight:500, color:'#64748b',
    cursor:'pointer', fontFamily:'inherit', marginBottom:'-2px',
    transition:'color 0.15s, border-color 0.15s',
  },
  subTabActive: {
    color:'#0f1923', borderBottomColor:'#0f1923',
  },

  // ── States ──
  loading: {
    color:'#94a3b8', fontSize:13, padding:'40px 0', textAlign:'center',
  },
  empty: {
    color:'#94a3b8', fontSize:13, padding:'40px 0', textAlign:'center',
  },
  errorMsg: {
    background:'#fef2f2', color:'#dc2626', padding:'10px 12px',
    borderRadius:7, fontSize:12, marginBottom:12, border:'1px solid #fecaca',
  },
  comingSoon: {
    textAlign:'center', padding:'80px 0', color:'#94a3b8',
  },
  comingSoonTitle: {
    fontSize:18, fontWeight:700, color:'#374151', marginBottom:12,
  },
  comingSoonText: {
    fontSize:14, lineHeight:1.8, maxWidth:440, margin:'0 auto',
  },
};
