/* ============================================================
   Bizia — Settings  (/app/settings)
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Badge, Button, Icon, PageHeader, Input, Toggle, Avatar, Tabs } = window;

  function Row({ children, style }) { return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', borderBottom: '1px solid var(--border-soft)', ...style } }, children); }

  function SettingsPage() {
    const data = window.DATA;
    const currentUser = window.useCurrentUser();
    const [tab, setTab] = useState('Organization');
    const tabs = ['Organization', 'Team', 'Roles', 'Brand kit', 'Integrations', 'API keys', 'Security', 'Export'];
    // No backend endpoint lists org members yet — show the real current
    // user (once known) rather than fabricated teammates. Never seeded
    // from prototype sample people.
    const [team, setTeam] = useState([]);
    const [orgName, setOrgName] = useState('');
    const [integrations, setIntegrations] = useState(data.integrations || []);

    useEffect(() => {
      window.API.auth.getOrgs().then(orgs => {
        const primaryOrg = Array.isArray(orgs) && orgs[0];
        if (primaryOrg?.name) setOrgName(primaryOrg.name);
        if (currentUser) {
          setTeam([{ name: currentUser.name || currentUser.email || 'You', email: currentUser.email || '', role: primaryOrg?.role || 'Owner', tone: '#5B5CFF' }]);
        }
      }).catch(() => {});
      window.API.integrations.list().then(list => { if (list && list.length) setIntegrations(list); }).catch(() => {});
    }, [currentUser && currentUser.id]);

    async function handleSaveOrg() {
      await window.API.auth.updateMe({ orgName }).catch(() => {});
      window.toast({ title: 'Saved', tone: 'success' });
    }
    const roles = [['Owner', 'Full access, billing & deletion', 'shield'], ['Admin', 'Manage site, team & settings', 'users'], ['Editor', 'Edit pages & content', 'edit'], ['Viewer', 'View-only access', 'eye']];

    function panel() {
      switch (tab) {
        case 'Organization':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 18 } }, 'Organization'),
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 } },
              React.createElement(Avatar, { name: orgName, tone: '#FF8A5B', size: 64 }),
              React.createElement('div', null, React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'upload', onClick: () => window.toast({ title: 'Upload logo', tone: 'info' }) }, 'Upload logo'), React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 6 } }, 'PNG or SVG, at least 256×256'))),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
              React.createElement(Input, { label: 'Business name', value: orgName, onChange: (e) => setOrgName(e.target.value), icon: 'building' }),
              React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 } }, React.createElement(Input, { label: 'Industry', defaultValue: 'Restaurant / Cafe', icon: 'briefcase' }), React.createElement(Input, { label: 'Location', defaultValue: 'San Francisco, CA', icon: 'pin' }))),
            React.createElement(Button, { variant: 'primary', icon: 'check', style: { marginTop: 20 }, onClick: handleSaveOrg }, 'Save changes'));
        case 'Team':
          return React.createElement(Card, { pad: 24 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 } }, React.createElement('h3', { style: { fontSize: 16, fontWeight: 650 } }, 'Team members'), React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'plus', onClick: () => window.navigate('/invite') }, 'Invite')),
            team.map((m, i) => React.createElement(Row, { key: i },
              React.createElement(Avatar, { name: m.name, tone: m.tone, size: 38 }),
              React.createElement('div', { style: { flex: 1 } }, React.createElement('div', { style: { fontSize: 14, fontWeight: 600 } }, m.name), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, m.email)),
              React.createElement(Badge, { tone: m.role === 'Owner' ? 'primary' : 'neutral' }, m.role),
              React.createElement(window.IconButton, { name: 'moreV', label: 'Options', onClick: () => {} }))));
        case 'Roles':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 8 } }, 'Roles & permissions'),
            roles.map((r, i) => React.createElement(Row, { key: i },
              React.createElement('div', { style: { width: 36, height: 36, borderRadius: 9, background: 'var(--surface-3)', color: 'var(--text-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: r[2], size: 17 })),
              React.createElement('div', { style: { flex: 1 } }, React.createElement('div', { style: { fontSize: 14, fontWeight: 600 } }, r[0]), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, r[1])))));
        case 'Brand kit':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 6 } }, 'Brand kit'),
            React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginBottom: 16 } }, 'Reused across your website, e-cards and social kit.'),
            React.createElement('div', { style: { display: 'flex', gap: 8, marginBottom: 18 } }, (window.DATA.design.palette || []).map((c, i) => React.createElement('div', { key: i, style: { flex: 1, height: 48, borderRadius: 10, background: c.hex, border: '1px solid rgba(0,0,0,0.06)' } }))),
            React.createElement(Button, { variant: 'outline', icon: 'palette', onClick: () => window.navigate('/app/design') }, 'Edit in Design & Brand'));
        case 'Integrations':
          return React.createElement(Card, { pad: 24 },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 6 } }, 'Connected services'),
            integrations.filter(i => i.status === 'connected').map((it, i) => React.createElement(Row, { key: i },
              React.createElement('div', { style: { width: 34, height: 34, borderRadius: 8, background: window.BZ_TONES[it.tone][0], color: window.BZ_TONES[it.tone][1], display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: it.icon, size: 16 })),
              React.createElement('div', { style: { flex: 1 } }, React.createElement('div', { style: { fontSize: 14, fontWeight: 600 } }, it.name), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, 'by ' + it.provider)),
              React.createElement(Badge, { tone: 'success', icon: 'check' }, 'Connected'))),
            React.createElement(Button, { variant: 'outline', icon: 'plug', style: { marginTop: 16 }, onClick: () => window.navigate('/app/integrations') }, 'Browse integrations'));
        case 'API keys':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 6 } }, 'API keys'),
            React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginBottom: 16 } }, 'For developers connecting Bizia to other tools. Keep these secret.'),
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, padding: 14, borderRadius: 'var(--r-md)', background: 'var(--surface-3)', fontFamily: 'var(--font-mono)', fontSize: 13 } },
              React.createElement('span', { style: { flex: 1, color: 'var(--muted)' } }, 'biz_live_••••••••••••••••••••3f9a'),
              React.createElement(window.IconButton, { name: 'copy', label: 'Copy', size: 15, onClick: () => window.toast({ title: 'Copied', tone: 'success' }) }),
              React.createElement(window.IconButton, { name: 'refresh', label: 'Regenerate', size: 15, onClick: () => window.toast({ title: 'Key rotated', tone: 'warning' }) })),
            React.createElement(Button, { variant: 'outline', icon: 'plus', style: { marginTop: 14 }, onClick: () => window.toast({ title: 'New key', desc: 'Mocked.', tone: 'info' }) }, 'Create key'));
        case 'Security':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 8 } }, 'Security'),
            [['Two-factor authentication', 'Extra protection at sign-in', true], ['Login alerts', 'Email me about new sign-ins', true], ['Require SSO for team', 'Enterprise single sign-on', false]].map((s, i) =>
              React.createElement(Row, { key: i }, React.createElement('div', { style: { flex: 1 } }, React.createElement('div', { style: { fontSize: 14, fontWeight: 600 } }, s[0]), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, s[1])), React.createElement(Toggle, { on: s[2], onChange: () => {} }))));
        case 'Export':
          return React.createElement(Card, { pad: 24, style: { maxWidth: 620 } },
            React.createElement('h3', { style: { fontSize: 16, fontWeight: 650, marginBottom: 6 } }, 'Export project'),
            React.createElement('p', { style: { fontSize: 13.5, color: 'var(--muted)', marginBottom: 18, lineHeight: 1.5 } }, 'Download your website as code, or hand it off to a developer. You own everything you build with Bizia.'),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
              [['download', 'Export website code', 'A clean React + Tailwind codebase (.zip)'], ['folder', 'Export content', 'All page content as Markdown/JSON'], ['command', 'Developer handoff', 'README + integration points for Claude Code']].map((e, i) =>
                React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 'var(--r-md)', border: '1px solid var(--border)', background: 'var(--surface-2)' } },
                  React.createElement('div', { style: { width: 36, height: 36, borderRadius: 9, background: 'var(--primary-soft)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: e[0], size: 18 })),
                  React.createElement('div', { style: { flex: 1 } }, React.createElement('div', { style: { fontSize: 14, fontWeight: 600 } }, e[1]), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, e[2])),
                  React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'download', onClick: () => window.toast({ title: 'Export started', desc: e[1], tone: 'success' }) }, 'Export')))));
        default: return null;
      }
    }

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, { icon: 'settings', title: 'Settings', sub: 'Manage your organization, team, brand and account.' }),
      React.createElement('div', { style: { overflowX: 'auto', marginBottom: 22 } }, React.createElement(Tabs, { tabs, value: tab, onChange: setTab })),
      React.createElement('div', { className: 'bz-anim-in', key: tab }, panel()),
    );
  }

  window.SettingsPage = SettingsPage;
})();
