/* ============================================================
   Bizia — Forms & Auth  (/app/forms)
   Optional forms + (optional) login. Plain language.
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Badge, Button, Icon, PageHeader, Toggle, StatusBadge } = window;

  function FormsPage() {
    const data = window.DATA;
    const [forms, setForms] = useState(data.forms.map(f => ({ ...f })));
    const [auth, setAuth] = useState('none');

    // 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') || data.projects?.[0]?.id;

    useEffect(() => {
      if (!projectId) return;
      window.API.forms.list(projectId).then(list => { if (list && list.length) setForms(list); }).catch(() => {});
    }, [projectId]);

    async function toggleForm(id) {
      const next = forms.map(f => f.id === id ? { ...f, enabled: !f.enabled } : f);
      setForms(next);
      const f = next.find(x => x.id === id);
      await window.API.forms.update(projectId, id, { enabled: f.enabled }).catch(() => {});
    }
    const totalSubs = forms.filter(f => f.enabled).reduce((a, f) => a + f.submissions, 0);

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        icon: 'inbox', title: 'Forms & Auth',
        sub: 'Let visitors get in touch and book with you. Forms are recommended for most sites — login is optional and only needed in special cases.',
        actions: React.createElement(Button, { variant: 'outline', icon: 'inbox', onClick: () => window.navigate('/app/leads') }, 'View submissions'),
      }),

      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0,1.5fr) minmax(0,1fr)', gap: 16, alignItems: 'start' }, className: 'bz-forms-grid' },
        // forms list
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
          React.createElement(Card, { pad: 0, style: { overflow: 'hidden' } },
            React.createElement('div', { style: { padding: '16px 20px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
              React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650 } }, 'Forms on your website'),
              React.createElement('span', { style: { fontSize: 12.5, color: 'var(--muted)' } }, totalSubs + ' submissions this month')),
            forms.map((f, i) => React.createElement('div', { key: f.id, style: { padding: '16px 20px', borderBottom: i < forms.length - 1 ? '1px solid var(--border-soft)' : 'none', opacity: f.enabled ? 1 : 0.62 } },
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
                React.createElement('div', { style: { width: 38, height: 38, borderRadius: 10, background: f.enabled ? 'var(--primary-soft)' : 'var(--surface-3)', color: f.enabled ? 'var(--primary-700)' : 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: f.icon, size: 19 })),
                React.createElement('div', { style: { flex: 1, minWidth: 0 } },
                  React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                    React.createElement('span', { style: { fontSize: 14.5, fontWeight: 650 } }, f.name),
                    f.enabled ? React.createElement(Badge, { tone: 'success', size: 'sm', dot: true }, 'Live') : React.createElement(Badge, { tone: 'neutral', size: 'sm' }, 'Off')),
                  React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', marginTop: 2 } }, 'On ' + f.page + ' · goes to ' + f.dest)),
                React.createElement(Toggle, { on: f.enabled, onChange: () => toggleForm(f.id) })),
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, paddingLeft: 50, flexWrap: 'wrap' } },
                React.createElement('span', { style: { fontSize: 11.5, color: 'var(--muted-2)', fontWeight: 600 } }, 'Fields:'),
                f.fields.map(fld => React.createElement('span', { key: fld, style: { fontSize: 11.5, padding: '3px 9px', borderRadius: 999, background: 'var(--surface-3)', color: 'var(--text-2)' } }, fld)),
                React.createElement('div', { style: { flex: 1 } }),
                f.enabled ? React.createElement('span', { style: { fontSize: 12, color: 'var(--muted)' } }, React.createElement('strong', { style: { color: 'var(--text)' } }, f.submissions), ' submissions') : null,
                React.createElement('button', { onClick: () => window.toast({ title: 'Edit form', desc: f.name, tone: 'info' }), style: { fontSize: 12, color: 'var(--primary)', fontWeight: 600, border: 'none', background: 'none', cursor: 'pointer' } }, 'Edit')),
            )),
          ),
          // submission destination
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 } },
              React.createElement(Icon, { name: 'arrowUpRight', size: 17, style: { color: 'var(--secondary)' } }), React.createElement('h4', { style: { fontSize: 15, fontWeight: 650 } }, 'Where submissions go')),
            React.createElement('div', { style: { display: 'flex', gap: 12, flexWrap: 'wrap' } },
              [['inbox', 'Bizia Leads inbox', 'Track & reply in one place', true], ['mail', 'Email notification', 'sara@amazebites.cafe', true], ['plug', 'Connect more', 'Slack, Sheets, CRM…', false]].map((d, i) =>
                React.createElement('div', { key: i, style: { flex: 1, minWidth: 160, display: 'flex', alignItems: 'center', gap: 10, padding: 13, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)' } },
                  React.createElement(Icon, { name: d[0], size: 17, style: { color: d[3] ? 'var(--secondary)' : 'var(--muted)' } }),
                  React.createElement('div', { style: { minWidth: 0 } }, React.createElement('div', { style: { fontSize: 13, fontWeight: 600 } }, d[1]), React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, d[2])),
                  d[3] ? React.createElement(Icon, { name: 'check', size: 15, style: { color: 'var(--success)', marginLeft: 'auto' } }) : null)),
            ),
          ),
        ),
        // auth column
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 } },
              React.createElement(Icon, { name: 'lock', size: 17, style: { color: 'var(--primary)' } }), React.createElement('h4', { style: { fontSize: 15, fontWeight: 650 } }, 'Login (optional)')),
            React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 9, padding: 12, borderRadius: 'var(--r-md)', background: 'var(--secondary-soft)', marginBottom: 14 } },
              React.createElement(Icon, { name: 'info', size: 16, style: { color: 'var(--secondary)', flexShrink: 0, marginTop: 1 } }),
              React.createElement('p', { style: { fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.45 } }, 'Most simple websites do not need customer login. Only turn it on if people need accounts.')),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 9 } },
              data.authOptions.map(o => React.createElement('button', { key: o.id, onClick: () => setAuth(o.id),
                style: { display: 'flex', alignItems: 'flex-start', gap: 11, padding: 13, borderRadius: 'var(--r-md)', cursor: 'pointer', textAlign: 'left', background: auth === o.id ? 'var(--primary-soft)' : 'var(--surface-2)', border: '1.5px solid ' + (auth === o.id ? 'var(--primary)' : 'var(--border)') } },
                React.createElement('div', { style: { width: 18, height: 18, borderRadius: 999, border: '2px solid ' + (auth === o.id ? 'var(--primary)' : 'var(--border-strong)'), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 } }, auth === o.id ? React.createElement('div', { style: { width: 9, height: 9, borderRadius: 999, background: 'var(--primary)' } }) : null),
                React.createElement('div', { style: { flex: 1 } },
                  React.createElement('div', { style: { fontSize: 13.5, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 } }, React.createElement(Icon, { name: o.icon, size: 14, style: { color: 'var(--muted)' } }), o.label),
                  React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 2 } }, o.simple)))),
            ),
          ),
          // provider recommendation (only when login enabled)
          auth !== 'none' ? React.createElement(Card, { pad: 20, className: 'bz-anim-in' },
            React.createElement('h4', { style: { fontSize: 14.5, fontWeight: 650, marginBottom: 4 } }, 'Recommended login system'),
            React.createElement('p', { style: { fontSize: 12.5, color: 'var(--muted)', marginBottom: 14 } }, 'Bizia sets this up securely — you don’t touch any code.'),
            [['lock', 'Clerk', 'Easiest — polished sign-in, social logins, free up to 10k users', true], ['database', 'Supabase Auth', 'Best if you also store customer data in Supabase', false]].map((p, i) =>
              React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 11, padding: 12, borderRadius: 'var(--r-md)', background: p[3] ? 'var(--primary-soft)' : 'var(--surface-2)', border: '1px solid ' + (p[3] ? 'transparent' : 'var(--border-soft)'), marginBottom: 8 } },
                React.createElement('div', { style: { width: 32, height: 32, borderRadius: 8, background: 'var(--surface)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: p[0], size: 16 })),
                React.createElement('div', { style: { flex: 1, minWidth: 0 } }, React.createElement('div', { style: { fontSize: 13.5, fontWeight: 600 } }, p[1]), React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.4 } }, p[2])),
                p[3] ? React.createElement(Badge, { tone: 'primary', size: 'sm' }, 'Recommended') : null)),
            React.createElement(Button, { variant: 'primary', full: true, icon: 'check', style: { marginTop: 6 }, onClick: async () => {
              const result = await window.API.integrations.connect(projectId, 'clerk').catch(() => null);
              window.toast({ title: 'Login enabled', desc: result?.error || 'Bizia will set up Clerk for you.', tone: result?.error ? 'danger' : 'success' });
            } }, 'Enable login with Clerk'),
          ) : React.createElement(Card, { pad: 20, style: { background: 'var(--surface-2)' } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
              React.createElement('div', { style: { width: 38, height: 38, borderRadius: 10, background: 'var(--success-soft)', color: 'var(--success)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: 'check', size: 19 })),
              React.createElement('div', null, React.createElement('div', { style: { fontSize: 14, fontWeight: 650 } }, 'No login — you’re all set'), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', marginTop: 2 } }, 'Your site is open to everyone. Simplest & fastest.'))),
          ),
        ),
      ),
      React.createElement('style', null, '@media(max-width:900px){.bz-forms-grid{grid-template-columns:1fr !important}}'),
    );
  }

  window.FormsPage = FormsPage;
})();
