/* ============================================================
   Bizia — Create Website (prompt-to-website)  (/app/new)
   Prompt → Intake form → AI plan → Start build.
   ============================================================ */
(function () {
  const { useState } = React;
  const { Button, Icon, Badge, BiziaLogo, BiziaMark, Card } = window;

  function NeedDot({ need }) {
    const map = { core: ['var(--primary)', 'Core'], recommended: ['var(--secondary)', 'Suggested'], optional: ['var(--muted-2)', 'Optional'] };
    const [c, l] = map[need] || map.optional;
    return React.createElement('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 600, color: c } },
      React.createElement('span', { style: { width: 6, height: 6, borderRadius: 999, background: c } }), l);
  }

  const STYLES = ['modern', 'minimal', 'bold', 'warm', 'professional', 'playful'];
  const FEATURE_LIST = [
    ['appointment', 'Appointment Booking', 'calendar'],
    ['gallery', 'Photo Gallery', 'image'],
    ['blog', 'Blog / News', 'fileText'],
    ['payments', 'Online Payments', 'dollar'],
    ['insurance', 'Insurance Info', 'shield'],
  ];

  function emptyIntake() {
    return {
      businessName: '', businessType: '', tagline: '',
      city: '', state: '', phone: '', whatsapp: '', email: '',
      services: '', hours: 'Mon–Fri 9am–6pm',
      style: 'professional', primaryColor: '#5B5CFF',
      features: { appointment: false, gallery: false, blog: false, payments: false, insurance: false },
      insuranceProviders: '',
    };
  }

  function detectType(text) {
    const t = text.toLowerCase();
    if (t.includes('dental') || t.includes('dentist')) return 'dental';
    if (t.includes('restaurant') || t.includes('cafe') || t.includes('food') || t.includes('bistro')) return 'restaurant';
    if (t.includes('salon') || t.includes('spa') || t.includes('beauty') || t.includes('wellness')) return 'salon';
    if (t.includes('doctor') || t.includes('clinic') || t.includes('medical') || t.includes('health')) return 'medical';
    if (t.includes('school') || t.includes('coaching') || t.includes('academy') || t.includes('tutor')) return 'education';
    if (t.includes('real estate') || t.includes('property') || t.includes('realty')) return 'real estate';
    if (t.includes('shop') || t.includes('store') || t.includes('ecommerce')) return 'e-commerce';
    if (t.includes('event') || t.includes('wedding') || t.includes('venue')) return 'event';
    return 'business';
  }

  function parsePromptForIntake(text) {
    const nameMatch = text.match(/(?:called|named|for)\s+([A-Z][A-Za-z\s]{1,40}?)(?:\s+(?:in|at|is|,)|$)/);
    const cityMatch = text.match(/(?:in|at|located in)\s+([A-Z][A-Za-z\s]+?),?\s*([A-Z]{2})(?:\b|$)/);
    const styleMatch = text.match(/\b(modern|minimal|bold|warm|professional|playful|clean|luxury|elegant)\b/i);
    const type = detectType(text);
    const isMedical = type === 'dental' || type === 'medical';
    return {
      ...emptyIntake(),
      businessName: nameMatch ? nameMatch[1].trim() : '',
      businessType: type,
      city: cityMatch ? cityMatch[1].trim() : '',
      state: cityMatch ? (cityMatch[2] || '') : '',
      style: styleMatch ? styleMatch[1].toLowerCase() : 'professional',
      features: {
        appointment: isMedical || /appointment|booking/.test(text.toLowerCase()),
        gallery: /gallery|portfolio/.test(text.toLowerCase()),
        blog: /blog/.test(text.toLowerCase()),
        payments: /payment|online order/.test(text.toLowerCase()),
        insurance: isMedical || /insurance/.test(text.toLowerCase()),
      },
    };
  }

  function WizardPage() {
    if (!sessionStorage.getItem('bz_token')) {
      window.navigate('/login');
      return null;
    }
    const ex = window.DATA.createExample;
    const [phase, setPhase] = useState('prompt'); // prompt | intake | generating | plan
    const [prompt, setPrompt] = useState('');
    const [intake, setIntake] = useState(emptyIntake());
    const [genStep, setGenStep] = useState(0);
    const [generatedPlan, setGeneratedPlan] = useState(null);
    const [createdProjectId, setCreatedProjectId] = useState(null);

    const genStages = ['Reading your details', 'Designing the website', 'Writing the pages', 'Finding domain names', 'Choosing hosting & SEO', 'Preparing your plan'];

    function transformApiPlan(api, fallback) {
      if (api.name && api.structure) return api;
      const iconMap = { home: 'home', about: 'info', services: 'grid', service: 'grid', contact: 'mail', blog: 'fileText', pricing: 'dollar', portfolio: 'image', gallery: 'image', team: 'users', faq: 'helpCircle', testimonials: 'star', appointments: 'calendar', location: 'pin', insurance: 'shield', reviews: 'star' };
      const features = [];
      if (api.features?.forms) features.push('Contact form');
      if (api.features?.auth) features.push('Customer login');
      if (api.features?.payments) features.push('Online payments');
      if (!features.length) features.push(...(fallback.features || ['SEO optimized', 'Mobile responsive']));
      return {
        name: api.siteName || fallback.name,
        type: api.businessType || fallback.type,
        location: fallback.location,
        structure: (api.recommendedPages || []).slice(0, 8).map(p => ({ name: p.title, desc: p.purpose || p.metaDescription || '', icon: iconMap[p.slug?.toLowerCase()] || 'file' })),
        style: api.design?.style || fallback.style,
        colors: api.design?.colors?.length ? api.design.colors : fallback.colors,
        fonts: api.design?.fontDirection ? [api.design.fontDirection] : fallback.fonts,
        domains: fallback.domains,
        features,
        cost: fallback.cost,
      };
    }

    function setField(key, val) {
      setIntake(prev => ({ ...prev, [key]: val }));
    }

    function setFeature(key, val) {
      setIntake(prev => ({ ...prev, features: { ...prev.features, [key]: val } }));
    }

    function startIntake() {
      if (prompt.trim().length < 10) {
        window.toast({ title: 'Tell us a bit more', desc: 'Describe your business in a sentence or two.', tone: 'warning' });
        return;
      }
      setIntake(parsePromptForIntake(prompt));
      setPhase('intake');
    }

    async function generate() {
      if (!intake.businessName.trim()) {
        window.toast({ title: 'Business name required', desc: 'Please enter your business name.', tone: 'warning' });
        return;
      }
      setPhase('generating');
      setGenStep(0);

      let animDone = false;
      let apiDone = false;
      let pendingPlan = null;
      let pendingProjectId = null;

      function maybeTransition() {
        if (!animDone || !apiDone) return;
        if (pendingPlan) setGeneratedPlan(pendingPlan);
        if (pendingProjectId) setCreatedProjectId(pendingProjectId);
        setTimeout(() => setPhase('plan'), 300);
      }

      let step = 0;
      const iv = setInterval(() => {
        step++;
        setGenStep(step);
        if (step >= genStages.length) { clearInterval(iv); animDone = true; maybeTransition(); }
      }, 650);

      const servicesList = intake.services.split('\n').map(s => s.trim()).filter(Boolean);
      const insuranceList = intake.insuranceProviders.split('\n').map(s => s.trim()).filter(Boolean);
      const featuresList = Object.entries(intake.features).filter(([, v]) => v).map(([k]) => k);

      const enhanced = await window.API.generation.enhancePrompt({
        businessName: intake.businessName,
        businessType: intake.businessType,
        tagline: intake.tagline,
        city: intake.city,
        state: intake.state,
        phone: intake.phone,
        whatsapp: intake.whatsapp,
        email: intake.email,
        services: servicesList,
        hours: intake.hours,
        style: intake.style,
        primaryColor: intake.primaryColor,
        insuranceProviders: insuranceList,
        specialFeatures: featuresList,
        originalPrompt: prompt,
      }).catch(() => null);

      const enrichedPrompt = enhanced?.enhancedPrompt || prompt;

      const project = await window.API.projects.create({ name: intake.businessName || prompt.slice(0, 60), businessPrompt: enrichedPrompt });
      if (project?.id) pendingProjectId = project.id;
      const pid = project?.id || 'demo';
      const rawPlan = await window.API.plan.generate({ projectId: pid, prompt: enrichedPrompt });
      if (rawPlan) pendingPlan = transformApiPlan(rawPlan, ex.plan);
      apiDone = true;
      maybeTransition();
    }

    const plan = generatedPlan || ex.plan;

    // ---------- PROMPT PHASE ----------
    function promptPhase() {
      return React.createElement('div', { style: { maxWidth: 720, margin: '0 auto', textAlign: 'center', paddingTop: 'min(8vh,70px)' }, className: 'bz-anim-up' },
        React.createElement('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: 22 } }, React.createElement(BiziaMark, { size: 56, glow: true })),
        React.createElement('h1', { style: { fontSize: 'clamp(28px,4vw,38px)', fontWeight: 740, letterSpacing: '-0.035em', lineHeight: 1.05 } }, 'Describe the website you want'),
        React.createElement('p', { style: { fontSize: 16.5, color: 'var(--muted)', marginTop: 14, lineHeight: 1.5, maxWidth: 560, margin: '14px auto 0' } },
          'Tell Bizia about your business in plain English. We\'ll walk you through a quick setup, then design and build your site.'),
        React.createElement('div', { style: { marginTop: 28, textAlign: 'left', background: 'var(--surface)', borderRadius: 'var(--r-xl)', border: '1px solid var(--border-strong)', boxShadow: 'var(--sh-lg)', padding: 16 } },
          React.createElement('textarea', {
            value: prompt, onChange: (e) => setPrompt(e.target.value), rows: 4,
            placeholder: ex.prompt,
            style: { width: '100%', border: 'none', outline: 'none', background: 'transparent', resize: 'none', fontSize: 16, lineHeight: 1.55, color: 'var(--text)', fontFamily: 'inherit' },
          }),
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10, paddingTop: 12, borderTop: '1px solid var(--border-soft)' } },
            React.createElement('button', { onClick: () => setPrompt(ex.prompt), style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--muted)', border: 'none', background: 'none', cursor: 'pointer', fontWeight: 500 } },
              React.createElement(Icon, { name: 'sparkles', size: 14 }), 'Use example'),
            React.createElement(Button, { variant: 'primary', size: 'lg', icon: 'arrowRight', onClick: startIntake }, 'Continue'),
          ),
        ),
        React.createElement('div', { style: { marginTop: 24 } },
          React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted-2)', fontWeight: 600, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Or try one of these'),
          React.createElement('div', { style: { display: 'flex', gap: 9, flexWrap: 'wrap', justifyContent: 'center' } },
            ex.examples.map((s, i) => React.createElement('button', { key: i, onClick: () => setPrompt(s),
              style: { padding: '9px 14px', borderRadius: 'var(--r-pill)', border: '1px solid var(--border)', background: 'var(--surface)', fontSize: 13, color: 'var(--text-2)', cursor: 'pointer', textAlign: 'left' },
              onMouseEnter: (e) => e.currentTarget.style.borderColor = 'var(--primary)', onMouseLeave: (e) => e.currentTarget.style.borderColor = 'var(--border)' },
              s)),
          ),
        ),
        React.createElement('div', { style: { display: 'flex', gap: 24, justifyContent: 'center', marginTop: 36, flexWrap: 'wrap' } },
          [['layoutTemplate', 'Or start from a template', '/app/templates'], ['wand', 'Design from scratch', '/app/builder']].map((o, i) =>
            React.createElement('button', { key: i, onClick: () => window.navigate(o[2]), style: { display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: 'var(--muted)', border: 'none', background: 'none', cursor: 'pointer', fontWeight: 500 } },
              React.createElement(Icon, { name: o[0], size: 16 }), o[1], React.createElement(Icon, { name: 'arrowRight', size: 14 }))),
        ),
      );
    }

    // ---------- INTAKE PHASE ----------
    function intakePhase() {
      const isMedical = ['dental', 'medical'].includes(intake.businessType);

      function field(label, key, type, placeholder) {
        const inputId = 'wizard-field-' + key;
        return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 5 } },
          React.createElement('label', { htmlFor: inputId, style: { fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)' } }, label),
          React.createElement('input', {
            id: inputId, type: type || 'text', value: intake[key], onChange: (e) => setField(key, e.target.value),
            placeholder: placeholder || '',
            style: { padding: '9px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', fontSize: 14, color: 'var(--text)', fontFamily: 'inherit', outline: 'none' },
          }),
        );
      }

      function section(title, icon, children) {
        return React.createElement('div', { style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 20 } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 } },
            React.createElement('div', { style: { width: 28, height: 28, borderRadius: 8, background: 'var(--primary-soft)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
              React.createElement(Icon, { name: icon, size: 14 })),
            React.createElement('h3', { style: { fontSize: 14.5, fontWeight: 650 } }, title),
          ),
          children,
        );
      }

      const gridStyle = { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 };
      const spanAll = { gridColumn: '1 / -1' };

      return React.createElement('div', { style: { maxWidth: 760, margin: '0 auto', paddingTop: 'min(5vh,40px)', paddingBottom: 60 }, className: 'bz-anim-up' },
        React.createElement('button', { onClick: () => setPhase('prompt'), style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--muted)', border: 'none', background: 'none', cursor: 'pointer', marginBottom: 20 } },
          React.createElement(Icon, { name: 'arrowLeft', size: 14 }), 'Back'),
        React.createElement('h1', { style: { fontSize: 'clamp(24px,3.5vw,32px)', fontWeight: 730, letterSpacing: '-0.03em' } }, 'Tell us about your business'),
        React.createElement('p', { style: { fontSize: 15, color: 'var(--muted)', marginTop: 8, marginBottom: 24 } },
          'Fill in the details below. Bizia uses these to generate a perfectly tailored website.'),

        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },

          section('Business Details', 'briefcase',
            React.createElement('div', gridStyle,
              field('Business Name *', 'businessName', 'text', 'e.g. BrightSmile Dental'),
              field('Business Type', 'businessType', 'text', 'e.g. dental clinic, restaurant'),
              React.createElement('div', { style: spanAll }, field('Tagline / Slogan', 'tagline', 'text', 'e.g. Your smile is our mission')),
            ),
          ),

          section('Contact & Location', 'mapPin',
            React.createElement('div', gridStyle,
              field('City', 'city', 'text', 'e.g. Newark'),
              field('State / Province', 'state', 'text', 'e.g. NJ'),
              field('Phone Number', 'phone', 'tel', 'e.g. +1 973 555 0100'),
              field('WhatsApp Number', 'whatsapp', 'tel', 'e.g. +1 973 555 0100'),
              React.createElement('div', { style: spanAll }, field('Email', 'email', 'email', 'e.g. hello@yourbusiness.com')),
            ),
          ),

          section('Services & Hours', 'grid',
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } },
              React.createElement('div', null,
                React.createElement('label', { style: { fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', display: 'block', marginBottom: 5 } }, 'Services Offered (one per line)'),
                React.createElement('textarea', {
                  value: intake.services, onChange: (e) => setField('services', e.target.value), rows: 4,
                  placeholder: 'Teeth Whitening\nGeneral Check-up\nOrthodontics\nEmergency Care',
                  style: { width: '100%', padding: '9px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', fontSize: 14, color: 'var(--text)', fontFamily: 'inherit', outline: 'none', resize: 'vertical', boxSizing: 'border-box' },
                }),
              ),
              field('Business Hours', 'hours', 'text', 'e.g. Mon–Fri 9am–6pm, Sat 10am–4pm'),
            ),
          ),

          isMedical ? section('Insurance & Coverage', 'shield',
            React.createElement('div', null,
              React.createElement('label', { style: { fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', display: 'block', marginBottom: 5 } }, 'Accepted Insurance Plans (one per line)'),
              React.createElement('textarea', {
                value: intake.insuranceProviders, onChange: (e) => setField('insuranceProviders', e.target.value), rows: 4,
                placeholder: 'Aetna\nCigna\nBlue Cross Blue Shield\nDelta Dental\nMetLife',
                style: { width: '100%', padding: '9px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', fontSize: 14, color: 'var(--text)', fontFamily: 'inherit', outline: 'none', resize: 'vertical', boxSizing: 'border-box' },
              }),
            ),
          ) : null,

          section('Design Preferences', 'palette',
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } },
              React.createElement('div', null,
                React.createElement('label', { style: { fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', display: 'block', marginBottom: 10 } }, 'Visual Style'),
                React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
                  STYLES.map(s => React.createElement('button', {
                    key: s, onClick: () => setField('style', s),
                    style: { padding: '7px 14px', borderRadius: 'var(--r-pill)', border: `1.5px solid ${intake.style === s ? 'var(--primary)' : 'var(--border)'}`, background: intake.style === s ? 'var(--primary-soft)' : 'var(--surface)', fontSize: 13, fontWeight: intake.style === s ? 650 : 500, color: intake.style === s ? 'var(--primary-700)' : 'var(--text-2)', cursor: 'pointer', textTransform: 'capitalize' },
                  }, s)),
                ),
              ),
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
                React.createElement('label', { style: { fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)' } }, 'Primary Brand Color'),
                React.createElement('input', { type: 'color', value: intake.primaryColor, onChange: (e) => setField('primaryColor', e.target.value), style: { width: 40, height: 32, borderRadius: 6, border: '1px solid var(--border)', cursor: 'pointer', padding: 2 } }),
                React.createElement('span', { style: { fontSize: 13, color: 'var(--muted)', fontFamily: 'var(--font-mono)' } }, intake.primaryColor),
              ),
            ),
          ),

          section('Features to Include', 'sparkles',
            React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 10 } },
              FEATURE_LIST.map(([key, label, icon]) => React.createElement('label', {
                key,
                style: { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 'var(--r-sm)', border: `1.5px solid ${intake.features[key] ? 'var(--primary)' : 'var(--border-soft)'}`, background: intake.features[key] ? 'var(--primary-soft)' : 'var(--surface-2)', cursor: 'pointer' },
              },
                React.createElement('input', { type: 'checkbox', checked: intake.features[key], onChange: (e) => setFeature(key, e.target.checked), style: { accentColor: 'var(--primary)' } }),
                React.createElement(Icon, { name: icon, size: 14, style: { color: intake.features[key] ? 'var(--primary-700)' : 'var(--muted)' } }),
                React.createElement('span', { style: { fontSize: 13, fontWeight: 550 } }, label),
              )),
            ),
          ),
        ),

        React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 12, flexWrap: 'wrap', marginTop: 24, padding: '16px 20px', borderRadius: 'var(--r-lg)', background: 'var(--surface-2)', border: '1px solid var(--border)' } },
          React.createElement(Button, { variant: 'outline', onClick: () => setPhase('prompt') }, 'Back'),
          React.createElement(Button, { variant: 'primary', size: 'lg', icon: 'wand', onClick: generate }, 'Generate my website'),
        ),
      );
    }

    // ---------- GENERATING PHASE ----------
    function generatingPhase() {
      return React.createElement('div', { style: { maxWidth: 460, margin: '0 auto', textAlign: 'center', paddingTop: 'min(10vh,90px)' } },
        React.createElement('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: 24 } },
          React.createElement('div', { style: { position: 'relative' } },
            React.createElement('div', { style: { position: 'absolute', inset: -14, borderRadius: '30%', background: 'radial-gradient(circle, rgba(91,92,255,0.3), transparent 70%)', animation: 'bz-pulse-soft 1.4s infinite' } }),
            React.createElement(BiziaMark, { size: 72, glow: true }),
          ),
        ),
        React.createElement('h2', { style: { fontSize: 24, fontWeight: 720, letterSpacing: '-0.03em' } }, 'Building your website'),
        React.createElement('p', { style: { fontSize: 14.5, color: 'var(--muted)', marginTop: 8 } }, 'Bizia is designing pages and preparing your launch.'),
        React.createElement('div', { style: { marginTop: 28, display: 'flex', flexDirection: 'column', gap: 10, textAlign: 'left' } },
          genStages.map((g, i) => {
            const done = i < genStep, active = i === genStep;
            return React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 12, opacity: i <= genStep ? 1 : 0.4, transition: 'opacity .3s' } },
              React.createElement('div', { style: { width: 24, height: 24, borderRadius: 999, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: done ? 'var(--secondary)' : active ? 'var(--primary-soft)' : 'var(--surface-3)', color: done ? '#fff' : 'var(--primary)' } },
                done ? React.createElement(Icon, { name: 'check', size: 14 }) : active ? React.createElement('div', { style: { width: 11, height: 11, border: '2px solid var(--primary)', borderTopColor: 'transparent', borderRadius: 999, animation: 'bz-spin .7s linear infinite' } }) : React.createElement('span', { style: { width: 6, height: 6, borderRadius: 999, background: 'var(--muted-2)' } })),
              React.createElement('span', { style: { fontSize: 14, fontWeight: active ? 600 : 500 } }, g),
            );
          }),
        ),
      );
    }

    // ---------- PLAN PHASE ----------
    function PlanBlock({ icon, title, sub, children, action }) {
      return React.createElement(Card, { pad: 20 },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 } },
          React.createElement('div', { style: { width: 34, height: 34, borderRadius: 9, background: 'var(--primary-soft)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: icon, size: 17 })),
          React.createElement('div', { style: { flex: 1 } },
            React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650 } }, title),
            sub ? React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, sub) : null),
          action || null,
        ),
        children,
      );
    }

    function planPhase() {
      return React.createElement('div', { style: { maxWidth: 1000, margin: '0 auto', padding: '8px 0 40px' }, className: 'bz-anim-up' },
        React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 8 } },
          React.createElement(Badge, { tone: 'secondary', icon: 'check' }, 'Website ready to build'),
        ),
        React.createElement('h1', { style: { fontSize: 30, fontWeight: 730, letterSpacing: '-0.035em', marginTop: 8 } }, plan.name),
        React.createElement('p', { style: { fontSize: 15, color: 'var(--muted)', marginTop: 8, maxWidth: 640, lineHeight: 1.5 } },
          'Here\'s the website Bizia designed for your ', React.createElement('strong', { style: { color: 'var(--text)' } }, plan.type.toLowerCase()), ' in ' + plan.location + '. Review the plan, then start building — you can change anything later.'),

        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0,1.4fr) minmax(0,1fr)', gap: 16, marginTop: 24 }, className: 'bz-create-grid' },
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
            React.createElement(PlanBlock, { icon: 'folder', title: 'Suggested website structure', sub: plan.structure.length + ' pages' },
              React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(220px,1fr))', gap: 10 } },
                plan.structure.map((pg, i) => React.createElement('div', { key: i, style: { display: 'flex', gap: 11, padding: 12, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)' } },
                  React.createElement('div', { style: { width: 30, height: 30, borderRadius: 8, background: 'var(--surface)', border: '1px solid var(--border)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: pg.icon, size: 15 })),
                  React.createElement('div', { style: { minWidth: 0 } },
                    React.createElement('div', { style: { fontSize: 13.5, fontWeight: 600 } }, pg.name),
                    React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.35, marginTop: 2 } }, pg.desc)),
                )),
              ),
            ),
            React.createElement(PlanBlock, { icon: 'grid', title: 'Needed features' },
              React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
                plan.features.map(f => React.createElement('span', { key: f, style: { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 999, background: 'var(--surface-3)', fontSize: 13, fontWeight: 550 } },
                  React.createElement(Icon, { name: 'check', size: 13, style: { color: 'var(--secondary)' } }), f))),
            ),
          ),
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
            React.createElement(PlanBlock, { icon: 'palette', title: 'Design direction', sub: plan.style },
              React.createElement('div', { style: { display: 'flex', gap: 7, marginBottom: 12 } },
                plan.colors.map((c, i) => React.createElement('div', { key: i, style: { flex: 1, height: 36, borderRadius: 8, background: c, border: '1px solid rgba(0,0,0,0.06)' } }))),
              React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
                plan.fonts.map((f, i) => React.createElement('div', { key: i, style: { fontSize: 12.5, color: 'var(--muted)' } }, '· ' + f))),
            ),
            React.createElement(PlanBlock, { icon: 'globe', title: 'Suggested domains',
              action: React.createElement('button', { onClick: () => window.navigate('/app/domain'), style: { fontSize: 12.5, color: 'var(--primary)', fontWeight: 600, border: 'none', background: 'none', cursor: 'pointer' } }, 'More') },
              React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
                plan.domains.map(d => React.createElement('div', { key: d.name, style: { display: 'flex', alignItems: 'center', gap: 8, padding: '9px 11px', borderRadius: 'var(--r-sm)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)' } },
                  React.createElement('span', { style: { flex: 1, minWidth: 0, fontFamily: 'var(--font-mono)', fontSize: 12.5, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, d.name),
                  React.createElement(Badge, { tone: d.badgeTone, size: 'sm' }, d.badge),
                  React.createElement('span', { style: { fontSize: 12.5, fontWeight: 700 } }, '$' + d.price),
                ))),
            ),
            React.createElement(PlanBlock, { icon: 'dollar', title: 'Estimated launch cost' },
              React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 9 } },
                [['rocket', 'Hosting', plan.cost.infra], ['globe', 'Domain', plan.cost.domain], ['sparkles', 'Bizia plan', plan.cost.plan]].map((r, i) =>
                  React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 9, fontSize: 13 } },
                    React.createElement(Icon, { name: r[0], size: 15, style: { color: 'var(--muted)' } }),
                    React.createElement('span', { style: { flex: 1, color: 'var(--muted)' } }, r[1]),
                    React.createElement('span', { style: { fontWeight: 650 } }, r[2]))),
              ),
            ),
          ),
        ),

        React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginTop: 22, padding: 18, borderRadius: 'var(--r-lg)', background: 'var(--surface-2)', border: '1px solid var(--border)' } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, fontSize: 13.5, color: 'var(--muted)' } },
            React.createElement(Icon, { name: 'info', size: 16 }), 'Bizia will build these pages and open the editor. Everything is editable.'),
          React.createElement('div', { style: { display: 'flex', gap: 10, flexWrap: 'wrap' } },
            React.createElement(Button, { variant: 'outline', icon: 'wand', onClick: () => { setPhase('intake'); } }, 'Refine details'),
            React.createElement(Button, { variant: 'ghost', onClick: () => window.navigate('/app/recommendation') }, 'View full plan'),
            React.createElement(Button, { variant: 'primary', size: 'lg', icon: 'rocket', onClick: () => { window.toast({ title: 'Building ' + plan.name, desc: 'Opening the website builder.', tone: 'success' }); window.navigate('/app/builder' + (createdProjectId ? '?project=' + createdProjectId : '')); } }, 'Start build'),
          ),
        ),
      );
    }

    return React.createElement('div', { className: 'bz-app-bg', style: { minHeight: '100vh', display: 'flex', flexDirection: 'column' } },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 16, padding: '18px 28px', borderBottom: '1px solid var(--border)', background: 'var(--glass-strong)', backdropFilter: 'blur(12px)', position: 'sticky', top: 0, zIndex: 20 } },
        React.createElement(BiziaLogo, { size: 20, onClick: () => window.navigate('/app') }),
        React.createElement('div', { style: { flex: 1 } }),
        phase === 'plan' ? React.createElement(Badge, { tone: 'primary', icon: 'sparkles' }, 'AI website plan') : null,
        React.createElement(window.IconButton, { name: 'x', label: 'Exit', onClick: () => window.navigate('/app') }),
      ),
      React.createElement('div', { style: { flex: 1, padding: '0 24px' } },
        phase === 'prompt' ? promptPhase() :
        phase === 'intake' ? intakePhase() :
        phase === 'generating' ? generatingPhase() :
        planPhase(),
      ),
      React.createElement('style', null, '@media(max-width:780px){.bz-create-grid{grid-template-columns:1fr !important}}'),
    );
  }

  window.WizardPage = WizardPage;
})();
