/* ============================================================
   Bizia — Smart Website Onboarding Wizard  (/app/new-website)
   Gathers requirements progressively, infers stack needs,
   and recommends which accounts to connect (if any).
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const { Card, Badge, Button, Icon, EmptyState } = window;

  const API = window.__BIZIA_API_URL || (/^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname) ? 'http://localhost:4000' : '');
  function getToken() { return sessionStorage.getItem('bz_token') || ''; }

  const STEP = { PROMPT: 'prompt', QUESTIONS: 'questions', REVIEW: 'review', DONE: 'done' };

  function ProgressBar({ current, total }) {
    const pct = Math.round((current / Math.max(total, 1)) * 100);
    return React.createElement('div', { style: { marginBottom: 24 } },
      React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--muted)', marginBottom: 6 } },
        React.createElement('span', null, `Question ${current} of ${total}`),
        React.createElement('span', null, `${pct}%`),
      ),
      React.createElement('div', { style: { height: 4, background: 'var(--surface-3)', borderRadius: 99 } },
        React.createElement('div', { style: { height: 4, background: 'var(--primary)', borderRadius: 99, width: `${pct}%`, transition: 'width .3s' } }),
      ),
    );
  }

  function QuestionWidget({ question, value, onChange }) {
    const inp = { width: '100%', padding: '10px 14px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', fontSize: 14, boxSizing: 'border-box' };

    if (question.type === 'text') {
      return React.createElement('textarea', {
        style: { ...inp, minHeight: 80, resize: 'vertical' },
        value: value || '', onChange: (e) => onChange(e.target.value), placeholder: 'Type your answer…',
      });
    }
    if (question.type === 'yesno') {
      return React.createElement('div', { style: { display: 'flex', gap: 10 } },
        ['yes', 'no'].map(opt =>
          React.createElement('button', {
            key: opt, onClick: () => onChange(opt === 'yes'),
            style: {
              padding: '10px 28px', borderRadius: 'var(--r-sm)', border: '2px solid',
              borderColor: value === (opt === 'yes') ? 'var(--primary)' : 'var(--border)',
              background: value === (opt === 'yes') ? 'var(--primary-soft)' : 'var(--surface-2)',
              color: value === (opt === 'yes') ? 'var(--primary-700)' : 'var(--text-2)',
              cursor: 'pointer', fontWeight: 600, fontSize: 14, transition: 'all .14s',
            },
          }, opt === 'yes' ? 'Yes' : 'No')
        )
      );
    }
    // choice or multiChoice
    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
      (question.options || []).map(opt =>
        React.createElement('button', {
          key: opt, onClick: () => onChange(opt),
          style: {
            padding: '10px 16px', borderRadius: 'var(--r-sm)', border: '2px solid', textAlign: 'left',
            borderColor: value === opt ? 'var(--primary)' : 'var(--border)',
            background: value === opt ? 'var(--primary-soft)' : 'var(--surface-2)',
            color: value === opt ? 'var(--primary-700)' : 'var(--text)', cursor: 'pointer',
            fontSize: 14, fontWeight: value === opt ? 600 : 400, transition: 'all .14s',
          },
        }, opt)
      )
    );
  }

  function StackReview({ stack, onContinue, onBack }) {
    const PROVIDER_LABELS = { google: 'Google', github: 'GitHub', stripe: 'Stripe', sendgrid: 'SendGrid', digitalplat: 'DigitalPlat' };
    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 24 } },
      React.createElement('div', { style: { fontWeight: 700, fontSize: 20 } }, 'Your recommended setup'),
      React.createElement(Card, { pad: 20, style: { display: 'flex', flexDirection: 'column', gap: 14 } },
        React.createElement('div', { style: { display: 'flex', gap: 12, alignItems: 'center' } },
          React.createElement(Icon, { name: 'cloud', size: 18, style: { color: 'var(--primary)' } }),
          React.createElement('div', null,
            React.createElement('div', { style: { fontWeight: 650, fontSize: 14 } }, 'Hosting'),
            React.createElement('div', { style: { fontSize: 13, color: 'var(--text-2)', marginTop: 2 } },
              stack.hosting === 'github-pages' ? 'GitHub Pages' :
              stack.hosting === 'self-hosted' ? 'Your own server' : 'Bizia-managed hosting (no extra setup)',
            ),
          ),
        ),
        React.createElement('div', { style: { display: 'flex', gap: 12, alignItems: 'center' } },
          React.createElement(Icon, { name: 'globe', size: 18, style: { color: 'var(--primary)' } }),
          React.createElement('div', null,
            React.createElement('div', { style: { fontWeight: 650, fontSize: 14 } }, 'Domain'),
            React.createElement('div', { style: { fontSize: 13, color: 'var(--text-2)', marginTop: 2 } },
              stack.domain === 'existing' ? 'Your existing domain' :
              stack.domain === 'free-digitalplat' ? 'Free domain via DigitalPlat (availability not guaranteed)' :
              stack.domain === 'pending' ? 'Purchase a custom domain later' : 'No domain yet',
            ),
          ),
        ),
        stack.providers.length > 0 && React.createElement('div', null,
          React.createElement('div', { style: { fontWeight: 650, fontSize: 14, marginBottom: 8 } }, 'Accounts to connect (when ready)'),
          React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
            stack.providers.map(p => React.createElement(Badge, { key: p, tone: 'primary', size: 'sm' }, PROVIDER_LABELS[p] || p)),
          ),
        ),
        stack.warnings.length > 0 && React.createElement('div', { style: { background: 'var(--warning-soft, #fef9c3)', borderRadius: 8, padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 6 } },
          stack.warnings.map((w, i) => React.createElement('div', { key: i, style: { fontSize: 12, color: 'var(--warning-800, #854d0e)', display: 'flex', gap: 6, alignItems: 'flex-start' } },
            React.createElement(Icon, { name: 'alertTriangle', size: 13, style: { marginTop: 1, flexShrink: 0 } }), w,
          )),
        ),
      ),
      React.createElement('div', { style: { display: 'flex', gap: 10 } },
        React.createElement(Button, { variant: 'outline', icon: 'arrowLeft', onClick: onBack }, 'Back'),
        React.createElement(Button, { variant: 'primary', icon: 'creditCard', onClick: onContinue }, 'Proceed to payment'),
      ),
    );
  }

  function NewWebsitePage() {
    if (!sessionStorage.getItem('bz_token')) {
      window.navigate('/login');
      return null;
    }
    const [step, setStep] = useState(STEP.PROMPT);
    const [prompt, setPrompt] = useState('');
    const [session, setSession] = useState(null);
    const [questions, setQuestions] = useState([]);
    const [qIdx, setQIdx] = useState(0);
    const [answers, setAnswers] = useState({});
    const [currentAnswer, setCurrentAnswer] = useState(undefined);
    const [stack, setStack] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    async function startSession() {
      if (!prompt.trim()) { setError('Describe your website to get started'); return; }
      setLoading(true); setError('');
      try {
        const res = await fetch(`${API}/api/onboarding/sessions`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
          body: JSON.stringify({ initialPrompt: prompt }),
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.error);
        setSession(data.data);
        setQuestions(data.data.questions || []);
        setQIdx(0);
        setStep(STEP.QUESTIONS);
      } catch (e) {
        setError(e.message || 'Failed to start');
      } finally {
        setLoading(false);
      }
    }

    async function submitAnswer() {
      if (currentAnswer === undefined || currentAnswer === '') { setError('Please answer before continuing'); return; }
      setError('');
      const q = questions[qIdx];
      const newAnswers = { ...answers, [q.id]: currentAnswer };
      setAnswers(newAnswers);

      setLoading(true);
      try {
        await fetch(`${API}/api/onboarding/sessions/${session.sessionId}/answers`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
          body: JSON.stringify({ questionId: q.id, answer: currentAnswer }),
        });
      } catch (_) { /* best-effort */ }
      setLoading(false);

      if (qIdx + 1 < questions.length) {
        setQIdx(qIdx + 1);
        setCurrentAnswer(answers[questions[qIdx + 1]?.id]);
      } else {
        await fetchStack();
      }
    }

    async function fetchStack() {
      setLoading(true);
      try {
        const res = await fetch(`${API}/api/onboarding/sessions/${session.sessionId}/stack`, {
          method: 'POST',
          headers: { Authorization: `Bearer ${getToken()}` },
        });
        const data = await res.json();
        setStack(data.data);
        setStep(STEP.REVIEW);
      } catch (e) {
        setError('Failed to compute stack');
      } finally {
        setLoading(false);
      }
    }

    async function goToPayment() {
      setLoading(true); setError('');
      try {
        const name = session?.businessType || prompt.trim().slice(0, 60) || 'My Website';
        const res = await fetch(`${API}/api/projects`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
          body: JSON.stringify({ name, businessPrompt: prompt }),
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.error || 'Failed to create project');
        window.navigate(`/app/payment?projectId=${data.data.id}`);
      } catch (e) {
        setError(e.message || 'Failed to create project');
      } finally {
        setLoading(false);
      }
    }

    const containerStyle = { minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'var(--bg)' };
    const boxStyle = { width: '100%', maxWidth: 560, display: 'flex', flexDirection: 'column', gap: 24 };

    if (step === STEP.PROMPT) {
      return React.createElement('div', { style: containerStyle },
        React.createElement('div', { style: boxStyle },
          React.createElement('div', { style: { textAlign: 'center' } },
            React.createElement('div', { style: { fontWeight: 800, fontSize: 28, letterSpacing: '-0.02em', marginBottom: 8 } }, 'Create your website'),
            React.createElement('div', { style: { fontSize: 15, color: 'var(--text-2)', lineHeight: 1.6 } }, 'Tell us what you want to build. We\'ll ask a few quick questions to plan the right setup.'),
          ),
          React.createElement(Card, { pad: 24, style: { display: 'flex', flexDirection: 'column', gap: 16 } },
            React.createElement('textarea', {
              style: { width: '100%', padding: '12px 14px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', fontSize: 15, boxSizing: 'border-box', minHeight: 120, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.6 },
              value: prompt, onChange: (e) => setPrompt(e.target.value),
              placeholder: 'e.g. A portfolio website for my design agency with a blog and contact form',
              onKeyDown: (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) startSession(); },
            }),
            error && React.createElement('div', { style: { color: 'var(--danger)', fontSize: 13 } }, error),
            React.createElement(Button, { variant: 'primary', full: true, icon: 'arrowRight', loading, onClick: startSession }, 'Plan my website'),
          ),
          React.createElement('div', { style: { textAlign: 'center', fontSize: 13, color: 'var(--muted)' } }, 'No accounts are created automatically. You choose what to connect.'),
        ),
      );
    }

    if (step === STEP.QUESTIONS) {
      const q = questions[qIdx];
      if (!q) return null;
      return React.createElement('div', { style: containerStyle },
        React.createElement('div', { style: boxStyle },
          React.createElement('button', {
            onClick: () => window.navigate('/app'),
            style: { background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', fontSize: 13, display: 'flex', alignItems: 'center', gap: 6, padding: 0, alignSelf: 'flex-start' },
          }, React.createElement(Icon, { name: 'arrowLeft', size: 14 }), 'Back to dashboard'),
          React.createElement(ProgressBar, { current: qIdx + 1, total: questions.length }),
          React.createElement(Card, { pad: 28, style: { display: 'flex', flexDirection: 'column', gap: 20 } },
            React.createElement('div', null,
              !q.required && React.createElement(Badge, { tone: 'neutral', size: 'sm', style: { marginBottom: 8, display: 'inline-block' } }, 'Optional'),
              React.createElement('div', { style: { fontWeight: 700, fontSize: 18, lineHeight: 1.4 } }, q.text),
            ),
            React.createElement(QuestionWidget, { question: q, value: currentAnswer, onChange: setCurrentAnswer }),
            error && React.createElement('div', { style: { color: 'var(--danger)', fontSize: 13 } }, error),
            React.createElement('div', { style: { display: 'flex', gap: 10 } },
              qIdx > 0 && React.createElement(Button, { variant: 'outline', icon: 'arrowLeft', onClick: () => { setQIdx(qIdx - 1); setCurrentAnswer(answers[questions[qIdx - 1]?.id]); setError(''); } }, 'Back'),
              !q.required && React.createElement(Button, { variant: 'ghost', onClick: () => { setQIdx(qIdx + 1 < questions.length ? qIdx + 1 : qIdx); setCurrentAnswer(undefined); setError(''); if (qIdx + 1 >= questions.length) fetchStack(); } }, 'Skip'),
              React.createElement(Button, { variant: 'primary', icon: 'arrowRight', loading, onClick: submitAnswer },
                qIdx + 1 < questions.length ? 'Next' : 'See my setup'),
            ),
          ),
        ),
      );
    }

    if (step === STEP.REVIEW && stack) {
      return React.createElement('div', { style: containerStyle },
        React.createElement('div', { style: boxStyle },
          React.createElement(StackReview, { stack, onContinue: goToPayment, onBack: () => setStep(STEP.QUESTIONS) }),
        ),
      );
    }

    return React.createElement('div', { style: containerStyle }, React.createElement('div', null, 'Loading…'));
  }

  window.NewWebsitePage = NewWebsitePage;
})();
