/* ============================================================
   Bizia — Go Live: checklist, publish, handoff
   Route: /app/go-live/:projectId
   ============================================================ */
(function () {
  const { useState, useEffect, useCallback } = React;
  const API = window.__BIZIA_API_URL || (/^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname) ? 'http://localhost:4000' : '');

  const STATUS_ICON = { pass: 'check', fail: 'x', warn: 'alertTriangle', skip: 'minus' };
  const STATUS_COLOR = { pass: 'var(--success)', fail: 'var(--danger)', warn: 'var(--warning)', skip: 'var(--muted-2)' };

  function CheckRow({ check }) {
    return React.createElement('div', {
      style: {
        display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 0',
        borderBottom: '1px solid var(--border-soft)',
      },
    },
      React.createElement(window.Icon, { name: STATUS_ICON[check.status] || 'circle', size: 16, style: { color: STATUS_COLOR[check.status], flexShrink: 0, marginTop: 2 } }),
      React.createElement('div', { style: { flex: 1 } },
        React.createElement('div', { style: { fontSize: 13, fontWeight: 600, color: 'var(--text-1)' } }, check.label),
        React.createElement('div', { style: { fontSize: 12, color: 'var(--text-2)', marginTop: 2 } }, check.message),
      ),
      React.createElement('span', {
        style: {
          fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 999,
          background: check.status === 'pass' ? 'var(--success-soft, #e8faf0)' :
            check.status === 'fail' ? 'var(--danger-soft, #fdecea)' :
            check.status === 'warn' ? 'var(--warning-soft, #fff8e1)' : 'var(--surface-3)',
          color: STATUS_COLOR[check.status],
        },
      }, check.status.toUpperCase()),
    );
  }

  function GoLivePage({ path }) {
    // Prefer the /app/go-live/:projectId path segment; fall back to
    // ?project= (the convention every other nav-linked page uses, since
    // the sidebar itself has no per-project context) so the plain sidebar
    // link doesn't silently 404 against an empty project id.
    const pathProjectId = (path || '').split('/')[3] || '';
    const projectId = pathProjectId
      || new URLSearchParams(window.location.hash.split('?')[1] || '').get('project')
      || window.DATA?.projects?.[0]?.id
      || '';
    const [state, setState] = useState(null);
    const [project, setProject] = useState(null);
    const [handoff, setHandoff] = useState(null);
    const [loading, setLoading] = useState(true);
    const [running, setRunning] = useState(false);
    const [publishing, setPublishing] = useState(false);
    const [sendingHandoff, setSendingHandoff] = useState(false);
    const [handoffNotes, setHandoffNotes] = useState('');
    const [error, setError] = useState(null);

    const token = sessionStorage.getItem('bz_token') || '';
    const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

    const load = useCallback(async () => {
      if (!projectId) return;
      setLoading(true);
      setError(null);
      try {
        const [stateRes, projRes, handoffRes] = await Promise.all([
          fetch(`${API}/api/go-live/${projectId}/checklist`, { headers }),
          fetch(`${API}/api/go-live/${projectId}/status`, { headers }),
          fetch(`${API}/api/handoff/${projectId}`, { headers }),
        ]);
        const stateData = await stateRes.json();
        const projData = await projRes.json();
        const handoffData = await handoffRes.json();
        setState(stateData.success ? stateData.data : null);
        setProject(projData.success ? projData.data : null);
        setHandoff(handoffData.success ? handoffData.data : null);
      } catch (e) {
        setError('Failed to load status.');
      } finally {
        setLoading(false);
      }
    }, [projectId]);

    useEffect(() => { load(); }, [load]);

    async function runChecklist() {
      setRunning(true);
      setError(null);
      try {
        const r = await fetch(`${API}/api/go-live/${projectId}/checklist/run`, { method: 'POST', headers });
        const d = await r.json();
        if (d.success) setState(d.data);
        else setError(d.error || 'Run failed');
      } catch { setError('Run failed'); }
      setRunning(false);
    }

    async function publish() {
      setPublishing(true);
      setError(null);
      try {
        const r = await fetch(`${API}/api/go-live/${projectId}/publish`, { method: 'POST', headers });
        const d = await r.json();
        if (d.success) {
          window.toast && window.toast({ title: `Live at ${d.data.liveUrl}${d.data.demo ? ' (demo)' : ''}`, tone: 'success' });
          await load();
        } else setError(d.error || 'Publish failed');
      } catch { setError('Publish failed'); }
      setPublishing(false);
    }

    async function sendHandoff() {
      setSendingHandoff(true);
      setError(null);
      try {
        const r = await fetch(`${API}/api/go-live/${projectId}/handoff`, {
          method: 'POST', headers,
          body: JSON.stringify({ notes: handoffNotes }),
        });
        const d = await r.json();
        if (d.success) {
          window.toast && window.toast({ title: 'Handoff sent to client', tone: 'success' });
          await load();
        } else setError(d.error || 'Handoff failed');
      } catch { setError('Handoff failed'); }
      setSendingHandoff(false);
    }

    if (!projectId) return React.createElement('div', { style: { padding: 32 } }, 'No project selected.');
    if (loading) return React.createElement('div', { style: { padding: 32, color: 'var(--text-2)' } }, 'Loading…');

    const checks = state?.checks || [];
    const failCount = checks.filter(c => c.status === 'fail').length;
    const warnCount = checks.filter(c => c.status === 'warn').length;
    const passed = state?.status === 'passed';
    const isLive = project?.clientFlowStatus === 'live';

    return React.createElement('div', { style: { maxWidth: 760, margin: '0 auto', padding: '24px 16px' } },
      React.createElement(window.PageHeader, {
        title: 'Go Live',
        sub: 'Run pre-launch checks, publish to Cloudflare Pages, and send client handoff.',
        action: React.createElement('div', { style: { display: 'flex', gap: 8 } },
          React.createElement(window.Button, {
            variant: 'outline', icon: 'refreshCw', loading: running, onClick: runChecklist,
          }, running ? 'Running…' : 'Run checklist'),
          React.createElement(window.Button, {
            variant: passed && !isLive ? 'primary' : 'outline',
            icon: 'rocket',
            loading: publishing,
            disabled: !passed || isLive,
            onClick: publish,
          }, isLive ? 'Already live' : 'Publish'),
        ),
      }),

      error && React.createElement(window.Banner, { type: 'error', style: { marginBottom: 16 } }, error),

      // Status bar
      project && React.createElement('div', {
        style: {
          display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 20,
          padding: '12px 16px', borderRadius: 'var(--r)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)',
        },
      },
        React.createElement('div', null,
          React.createElement('div', { style: { fontSize: 11, color: 'var(--muted-2)', fontWeight: 600, textTransform: 'uppercase' } }, 'Status'),
          React.createElement('div', { style: { fontSize: 13, fontWeight: 700, marginTop: 2, color: isLive ? 'var(--success)' : 'var(--text-1)' } }, project.clientFlowStatus || '—'),
        ),
        project.productionUrl && React.createElement('div', null,
          React.createElement('div', { style: { fontSize: 11, color: 'var(--muted-2)', fontWeight: 600, textTransform: 'uppercase' } }, 'Live URL'),
          React.createElement('a', {
            href: project.productionUrl, target: '_blank', rel: 'noopener noreferrer',
            style: { fontSize: 13, fontWeight: 600, color: 'var(--primary)', textDecoration: 'none', marginTop: 2, display: 'block' },
          }, project.productionUrl),
        ),
      ),

      // Checklist
      React.createElement('div', { style: { background: 'var(--surface)', border: '1px solid var(--border-soft)', borderRadius: 'var(--r)', padding: '0 16px', marginBottom: 24 } },
        React.createElement('div', {
          style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0', borderBottom: '1px solid var(--border-soft)' },
        },
          React.createElement('div', { style: { fontWeight: 700, fontSize: 15 } }, 'Pre-launch checklist'),
          state && React.createElement('div', { style: { display: 'flex', gap: 8, fontSize: 12 } },
            React.createElement('span', { style: { color: 'var(--danger)', fontWeight: 600 } }, `${failCount} fail`),
            React.createElement('span', { style: { color: 'var(--warning)', fontWeight: 600 } }, `${warnCount} warn`),
            passed && React.createElement('span', { style: { color: 'var(--success)', fontWeight: 700 } }, '✓ Passed'),
          ),
        ),
        checks.length === 0
          ? React.createElement('div', { style: { padding: '24px 0', color: 'var(--text-2)', fontSize: 13, textAlign: 'center' } }, 'Run the checklist to see results.')
          : checks.map(c => React.createElement(CheckRow, { key: c.id, check: c })),
      ),

      // Handoff section (only when live)
      isLive && React.createElement('div', { style: { background: 'var(--surface)', border: '1px solid var(--border-soft)', borderRadius: 'var(--r)', padding: 20, marginBottom: 24 } },
        React.createElement('div', { style: { fontWeight: 700, fontSize: 15, marginBottom: 12 } }, 'Client handoff'),
        handoff
          ? React.createElement('div', null,
              React.createElement('div', { style: { fontSize: 13, color: 'var(--text-2)', marginBottom: 8 } },
                `Handoff status: `, React.createElement('strong', null, handoff.status),
                handoff.acknowledgedAt ? ` · Acknowledged ${new Date(handoff.acknowledgedAt).toLocaleDateString()}` : '',
              ),
              handoff.liveUrl && React.createElement('div', { style: { fontSize: 13, marginBottom: 8 } },
                'Live URL: ', React.createElement('a', { href: handoff.liveUrl, target: '_blank', rel: 'noopener noreferrer', style: { color: 'var(--primary)' } }, handoff.liveUrl),
              ),
            )
          : React.createElement('div', null,
              React.createElement('textarea', {
                value: handoffNotes,
                onChange: e => setHandoffNotes(e.target.value),
                placeholder: 'Optional notes for the client (login info, next steps, etc.)',
                rows: 3,
                style: {
                  width: '100%', padding: '10px 12px', fontSize: 13, borderRadius: 'var(--r-sm)',
                  border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text-1)',
                  marginBottom: 12, resize: 'vertical', boxSizing: 'border-box',
                },
              }),
              React.createElement(window.Button, {
                variant: 'primary', icon: 'send', loading: sendingHandoff, onClick: sendHandoff,
              }, 'Send handoff to client'),
            ),
      ),
    );
  }

  window.GoLivePage = GoLivePage;
})();
