/* ============================================================
   Bizia — Domain center  (/app/domain)
   Search, buy, connect existing, mapping checklist, SSL.
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Badge, Button, Icon, PageHeader, StatusBadge, Modal, Input } = window;

  function StatusLine({ icon, label, sub, status, last }) {
    return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderBottom: last ? 'none' : '1px solid var(--border-soft)' } },
      React.createElement('div', { style: { width: 34, height: 34, borderRadius: 9, background: 'var(--surface-3)', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: icon, size: 16 })),
      React.createElement('div', { style: { flex: 1, minWidth: 0 } },
        React.createElement('div', { style: { fontSize: 13.5, fontWeight: 600 } }, label),
        sub ? React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, sub) : null),
      React.createElement(StatusBadge, { status, size: 'sm' }),
    );
  }

  function DomainPage() {
    const data = window.DATA;
    const [q, setQ] = useState('amazebites');
    const [connectOpen, setConnectOpen] = useState(false);
    const [buying, setBuying] = useState(null);
    const [searching, setSearching] = useState(false);
    const [results, setResults] = useState(data.domains.filter(d => d.available));
    const [domainInfo, setDomainInfo] = useState(null);
    const [domainMapping, setDomainMapping] = useState(data.domainMapping);
    const [connectDomain, setConnectDomain] = useState('');

    // 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.domain.get(projectId).then(info => { if (info) setDomainInfo(info); }).catch(() => {});
    }, [projectId]);

    async function handleSearch() {
      if (!q.trim()) return;
      setSearching(true);
      const res = await window.API.domain.check(q).catch(() => null);
      setSearching(false);
      if (res && res.length) setResults(res);
      else window.toast({ title: 'No results', desc: 'Try a different name.', tone: 'warning' });
    }

    async function handleBuyDomain() {
      if (!buying) return;
      const result = await window.API.domain.purchase({ domain: buying.name, projectId, price: buying.price }).catch(() => null);
      if (result?.error) { window.toast({ title: result.error, tone: 'danger' }); return; }
      window.toast({ title: 'Domain reserved', desc: buying.name + ' — connecting now.', tone: 'success' });
      setBuying(null);
    }

    async function handleConnect() {
      if (!connectDomain.trim()) return;
      const result = await window.API.domain.connect({ domain: connectDomain.trim(), projectId }).catch(() => null);
      if (result?.error) { window.toast({ title: result.error, tone: 'danger' }); return; }
      window.toast({ title: 'Connection started', desc: 'Follow the steps to verify your domain.', tone: 'primary' });
      setConnectOpen(false);
    }

    const connectedDomain = domainInfo?.domain;
    const connectedLabel = domainInfo?.siteLabel;
    const connectedRenews = domainInfo?.renewsAt;

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        icon: 'globe', title: 'Domain',
        sub: 'Your domain is the web address people type to find you. Search for a new one or connect a domain you already own.',
        actions: React.createElement(Button, { variant: 'outline', icon: 'link', onClick: () => setConnectOpen(true) }, 'Connect existing domain'),
      }),

      // No real domain connected yet — never fabricate a "Connected" panel.
      !connectedDomain ? React.createElement(Card, { pad: 24, style: { textAlign: 'center', marginBottom: 22 } },
        React.createElement(Icon, { name: 'globe', size: 26, style: { color: 'var(--muted-2)', marginBottom: 8 } }),
        React.createElement('h4', { style: { fontSize: 15, fontWeight: 650, marginBottom: 4 } }, 'No domain connected yet'),
        React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)' } }, 'Search for a new domain below, or connect one you already own.'),
      ) : null,

      // Connected domain panel
      !connectedDomain ? null : React.createElement(Card, { pad: 0, style: { overflow: 'hidden', marginBottom: 22 } },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 14, padding: '20px 22px', borderBottom: '1px solid var(--border-soft)', background: 'var(--surface-2)', flexWrap: 'wrap' } },
          React.createElement('div', { style: { width: 46, height: 46, borderRadius: 12, background: 'var(--secondary-soft)', color: 'var(--secondary)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: 'globe', size: 24 })),
          React.createElement('div', { style: { flex: 1, minWidth: 180 } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
              React.createElement('span', { style: { fontSize: 19, fontWeight: 700, fontFamily: 'var(--font-mono)' } }, connectedDomain),
              React.createElement(Badge, { tone: 'success', icon: 'check' }, 'Connected')),
            React.createElement('div', { style: { fontSize: 13, color: 'var(--muted)', marginTop: 3 } }, 'Connected to ' + connectedLabel + ' · Renews ' + connectedRenews)),
          React.createElement(Button, { variant: 'ghost', size: 'sm', icon: 'externalLink', onClick: () => window.toast({ title: 'Opening site', tone: 'info' }) }, 'Visit'),
        ),
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(280px,1fr))' } },
          React.createElement('div', { style: { padding: '8px 22px 18px', borderRight: '1px solid var(--border-soft)' } },
            React.createElement('div', { style: { fontSize: 11.5, fontWeight: 650, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: '0.05em', margin: '14px 0 4px' } }, 'Status'),
            React.createElement(StatusLine, { icon: 'link', label: 'Connected to your website', sub: 'Your domain points to this site', status: 'connected' }),
            React.createElement(StatusLine, { icon: 'lock', label: 'Secure (SSL)', sub: 'The https padlock visitors trust', status: 'ready' }),
            React.createElement(StatusLine, { icon: 'globe', label: 'www and non-www', sub: 'Both versions work correctly', status: 'ready' }),
            React.createElement(StatusLine, { icon: 'refresh', label: 'Final verification', sub: 'Checking it loads everywhere', status: 'in-progress', last: true }),
          ),
          React.createElement('div', { style: { padding: '8px 22px 18px' } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '14px 0 6px' } },
              React.createElement('span', { style: { fontSize: 11.5, fontWeight: 650, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Connect your domain to this website'),
              React.createElement('span', { style: { fontSize: 12, fontWeight: 600, color: 'var(--secondary)' } }, '4 of 5 done')),
            domainMapping.map((m, i) => {
              const done = m.status === 'done', prog = m.status === 'in-progress';
              return React.createElement('div', { key: m.id, style: { display: 'flex', gap: 11, padding: '10px 0', borderBottom: i < domainMapping.length - 1 ? '1px solid var(--border-soft)' : 'none' } },
                React.createElement('div', { style: { width: 22, height: 22, borderRadius: 999, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: done ? 'var(--secondary)' : prog ? 'var(--accent-soft)' : 'var(--surface-3)', color: done ? '#fff' : 'var(--accent)', marginTop: 1 } },
                  done ? React.createElement(Icon, { name: 'check', size: 12 }) : prog ? React.createElement('div', { style: { width: 9, height: 9, border: '2px solid var(--accent)', borderTopColor: 'transparent', borderRadius: 999, animation: 'bz-spin .8s linear infinite' } }) : null),
                React.createElement('div', { style: { flex: 1 } },
                  React.createElement('div', { style: { fontSize: 13.5, fontWeight: 550 } }, m.label),
                  React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 1 } }, m.simple)));
            }),
          ),
        ),
      ),

      // Search
      React.createElement(Card, { pad: 22 },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 } },
          React.createElement(Icon, { name: 'search', size: 18, style: { color: 'var(--primary)' } }),
          React.createElement('h3', { style: { fontSize: 16.5, fontWeight: 650 } }, 'Search for a new domain')),
        React.createElement('p', { style: { fontSize: 13.5, color: 'var(--muted)', marginBottom: 16 } }, 'Find a memorable web address. Bizia connects it automatically — no technical setup.'),
        React.createElement('div', { style: { display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' } },
          React.createElement('div', { style: { flex: 1, minWidth: 220, display: 'flex', alignItems: 'center', gap: 9, height: 48, padding: '0 16px', borderRadius: 'var(--r-md)', background: 'var(--surface)', border: '1px solid var(--border-strong)' } },
            React.createElement(Icon, { name: 'search', size: 18, style: { color: 'var(--muted)' } }),
            React.createElement('input', { value: q, onChange: (e) => setQ(e.target.value), placeholder: 'yourbusiness', style: { flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 15.5, color: 'var(--text)', fontFamily: 'var(--font-mono)' } })),
          React.createElement(Button, { variant: 'primary', size: 'lg', icon: 'search', onClick: handleSearch, disabled: searching }, searching ? 'Searching…' : 'Search'),
        ),
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(300px,1fr))', gap: 12 } },
          results.map((d, i) => React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)', background: 'var(--surface-2)' } },
            React.createElement('div', { style: { flex: 1, minWidth: 0 } },
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
                React.createElement('span', { style: { fontSize: 15, fontWeight: 650, fontFamily: 'var(--font-mono)' } }, d.name),
                d.badge ? React.createElement(Badge, { tone: d.badgeTone, size: 'sm' }, d.badge) : null),
              React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 3 } }, '$' + d.price + '/yr · renews $' + d.renew + '/yr')),
            React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'plus', onClick: () => setBuying(d) }, 'Get'),
          )),
        ),
      ),

      // Buy modal
      React.createElement(Modal, { open: !!buying, onClose: () => setBuying(null), width: 440 },
        buying ? React.createElement('div', null,
          React.createElement('div', { style: { width: 48, height: 48, borderRadius: 13, background: 'var(--primary-soft)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 } }, React.createElement(Icon, { name: 'globe', size: 24 })),
          React.createElement('h2', { style: { fontSize: 20, fontWeight: 700 } }, 'Get this domain'),
          React.createElement('div', { style: { fontSize: 17, fontWeight: 650, fontFamily: 'var(--font-mono)', margin: '8px 0 16px', color: 'var(--primary-700)' } }, buying.name),
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10, padding: 16, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', marginBottom: 18 } },
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 13.5 } }, React.createElement('span', { style: { color: 'var(--muted)' } }, 'First year'), React.createElement('span', { style: { fontWeight: 650 } }, '$' + buying.price)),
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 13.5 } }, React.createElement('span', { style: { color: 'var(--muted)' } }, 'Renews at'), React.createElement('span', { style: { fontWeight: 650 } }, '$' + buying.renew + '/yr')),
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 13.5 } }, React.createElement('span', { style: { color: 'var(--muted)' } }, 'Auto-connect & SSL'), React.createElement('span', { style: { fontWeight: 650, color: 'var(--secondary)' } }, 'Included'))),
          React.createElement('p', { style: { fontSize: 12.5, color: 'var(--muted)', marginBottom: 16 } }, 'Domains are billed separately from your Bizia plan. This is a demo — no payment is taken.'),
          React.createElement('div', { style: { display: 'flex', gap: 10 } },
            React.createElement(Button, { variant: 'ghost', onClick: () => setBuying(null), style: { flex: 1 } }, 'Cancel'),
            React.createElement(Button, { variant: 'primary', icon: 'check', style: { flex: 1 }, onClick: handleBuyDomain }, 'Get domain')),
        ) : null,
      ),

      // Connect existing modal
      React.createElement(Modal, { open: connectOpen, onClose: () => setConnectOpen(false), width: 460 },
        React.createElement('h2', { style: { fontSize: 20, fontWeight: 700 } }, 'Connect a domain you own'),
        React.createElement('p', { style: { fontSize: 13.5, color: 'var(--muted)', marginTop: 6, marginBottom: 18 } }, 'Already have a domain from another provider? Enter it and Bizia will walk you through connecting it — in plain language.'),
        React.createElement(Input, { label: 'Your domain', icon: 'globe', placeholder: 'yourbusiness.com', value: connectDomain, onChange: (e) => setConnectDomain(e.target.value) }),
        React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 10, padding: 13, borderRadius: 'var(--r-md)', background: 'var(--info-soft)', margin: '16px 0' } },
          React.createElement(Icon, { name: 'info', size: 17, style: { color: 'var(--info)', flexShrink: 0, marginTop: 1 } }),
          React.createElement('p', { style: { fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.5 } }, 'We’ll give you one simple record to add at your provider, then verify it for you. No technical knowledge needed.')),
        React.createElement('div', { style: { display: 'flex', gap: 10 } },
          React.createElement(Button, { variant: 'ghost', onClick: () => setConnectOpen(false), style: { flex: 1 } }, 'Cancel'),
          React.createElement(Button, { variant: 'primary', icon: 'arrowRight', style: { flex: 1 }, onClick: handleConnect }, 'Start connecting')),
      ),
    );
  }

  window.DomainPage = DomainPage;
})();
