/* ============================================================
   Bizia — Integrations  (/app/integrations)
   Optional add-ons: analytics, payments, social, e-cards, leads…
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Badge, Button, Icon, PageHeader, Chip } = window;

  // Map integration card `provider` display names → internal provider names used by /api/providers
  const PROVIDER_NAME_MAP = { PostHog: 'posthog', Stripe: 'stripe', Resend: 'resend' };

  function fetchProviderStatuses(currentItems, setItems) {
    const token = window.getApiToken ? window.getApiToken() : null;
    const headers = token ? { Authorization: 'Bearer ' + token } : {};
    const targets = currentItems.filter(i => PROVIDER_NAME_MAP[i.provider]);
    if (!targets.length) return;
    Promise.all(
      targets.map(i => {
        const pName = PROVIDER_NAME_MAP[i.provider];
        return fetch('/api/providers/' + pName + '/connection', { headers })
          .then(r => r.ok ? r.json() : null)
          .then(d => ({ key: i.key, connected: d?.data?.connected ?? false }))
          .catch(() => ({ key: i.key, connected: false }));
      })
    ).then(statuses => {
      const statusByKey = {};
      statuses.forEach(s => { statusByKey[s.key] = s.connected ? 'connected' : 'not-started'; });
      setItems(prev => prev.map(item => item.key in statusByKey ? { ...item, status: statusByKey[item.key] } : item));
    });
  }

  function IntegrationsPage() {
    const [items, setItems] = useState(window.DATA.integrations || []);
    const cats = ['All', ...Array.from(new Set(items.map(i => i.category)))];
    const [cat, setCat] = useState('All');
    // Hash-routed SPA — the ?project= query string lives inside
    // window.location.hash, not window.location.search (which is always
    // empty here). Reading .search silently fell back to a mock project.
    const projectId = new URLSearchParams(window.location.hash.split('?')[1] || '').get('project') || window.DATA.projects?.[0]?.id;

    useEffect(() => {
      window.API.integrations.list(projectId).then(r => {
        const next = r?.length ? r : items;
        setItems(next);
        fetchProviderStatuses(next, setItems);
      }).catch(() => fetchProviderStatuses(items, setItems));
    }, [projectId]);
    const filtered = cat === 'All' ? items : items.filter(i => i.category === cat);
    const statusMap = { connected: ['success', 'Connected', 'check'], available: ['primary', 'Available', 'plus'], 'not-started': ['neutral', 'Not connected', 'plus'] };

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        icon: 'plug', title: 'Integrations',
        sub: 'Optional add-ons that extend your website — analytics, payments, social kit, e-cards and more. Add only what you need.',
      }),
      React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 } },
        cats.map(c => React.createElement(Chip, { key: c, active: cat === c, onClick: () => setCat(c) }, c)),
      ),
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16 } },
        filtered.map(it => {
          const [tone, lbl, ic] = statusMap[it.status] || statusMap['not-started'];
          const [bg, fg] = window.BZ_TONES[it.tone];
          const connected = it.status === 'connected';
          return React.createElement(Card, { key: it.key, hover: true, pad: 20, style: { display: 'flex', flexDirection: 'column' } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' } },
              React.createElement('div', { style: { width: 44, height: 44, borderRadius: 12, background: bg, color: fg, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: it.icon, size: 22 })),
              React.createElement(Badge, { tone, size: 'sm', icon: connected ? 'check' : null }, lbl)),
            React.createElement('h4', { style: { fontSize: 15.5, fontWeight: 650, marginTop: 14 } }, it.name),
            React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginTop: 5, lineHeight: 1.5, flex: 1 } }, it.simple),
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 } },
              React.createElement('span', { style: { fontSize: 12, color: 'var(--muted-2)' } }, 'by ' + it.provider),
              it.route ? React.createElement(Button, { variant: connected ? 'outline' : 'soft', size: 'sm', iconRight: 'arrowRight', onClick: () => window.navigate(it.route) }, 'Open')
                : connected ? React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'settings', onClick: () => window.toast({ title: it.name + ' settings', tone: 'info' }) }, 'Manage')
                  : React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'plug', onClick: () => window.toast({ title: 'Connecting ' + it.name, desc: 'Mocked in prototype.', tone: 'primary' }) }, 'Connect')),
          );
        }),
      ),
    );
  }

  window.IntegrationsPage = IntegrationsPage;
})();
