/* ============================================================
   Bizia — Dashboard  (/app)
   Website launch workspace — create, edit, connect, publish.
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, StatusBadge, Button, ProgressBar, RingProgress, Icon, PageHeader, SectionTitle } = window;

  /* mini status pill for project footer */
  function MiniStat({ icon, label, tone }) {
    const colors = { ok: 'var(--success)', warn: 'var(--warning)', off: 'var(--muted-2)', info: 'var(--info)' };
    return React.createElement('div', { title: label, style: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--muted)' } },
      React.createElement('span', { style: { width: 18, height: 18, borderRadius: 6, background: 'var(--surface-3)', color: colors[tone] || 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: icon, size: 12 })),
      label,
    );
  }

  function statusTone(s) {
    if (['connected', 'deployed', 'ready', 'verified', 'published'].includes(s)) return 'ok';
    if (['pending', 'partial', 'building', 'preview', 'in-progress'].includes(s)) return 'warn';
    return 'off';
  }

  function SitePreview({ p, h = 132 }) {
    return React.createElement('div', { style: { height: h, position: 'relative', background: 'linear-gradient(150deg,' + p.color + '1f,' + p.color + '06)', borderBottom: '1px solid var(--border-soft)', overflow: 'hidden' } },
      React.createElement('div', { style: { position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg,' + p.color + '12 0 1px, transparent 1px 11px)' } }),
      // mini browser
      React.createElement('div', { style: { position: 'absolute', left: 16, right: 16, top: 14, bottom: -2, borderRadius: '10px 10px 0 0', background: 'var(--surface)', border: '1px solid var(--border)', borderBottom: 'none', boxShadow: 'var(--sh-md)', overflow: 'hidden' } },
        React.createElement('div', { style: { height: 16, background: 'var(--surface-2)', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', gap: 3, padding: '0 7px' } },
          [0, 1, 2].map(i => React.createElement('span', { key: i, style: { width: 4, height: 4, borderRadius: 999, background: 'var(--border-strong)' } }))),
        React.createElement('div', { style: { padding: 10 } },
          React.createElement('div', { style: { height: 22, borderRadius: 6, background: p.color, opacity: 0.9, marginBottom: 8, display: 'flex', alignItems: 'center', padding: '0 9px' } },
            React.createElement('div', { style: { width: '45%', height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.75)' } })),
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 } },
            [0, 1, 2].map(i => React.createElement('div', { key: i, style: { height: 20, borderRadius: 5, background: 'var(--surface-3)' } }))),
        ),
      ),
    );
  }

  function ProjectCard({ p }) {
    return React.createElement(Card, { hover: true, pad: 0, style: { overflow: 'hidden', cursor: 'pointer', display: 'flex', flexDirection: 'column' }, onClick: () => window.navigate('/app/builder') },
      React.createElement('div', { style: { position: 'relative' } },
        React.createElement(SitePreview, { p }),
        React.createElement('div', { style: { position: 'absolute', top: 12, right: 12 } }, React.createElement(StatusBadge, { status: p.status, size: 'sm' })),
      ),
      React.createElement('div', { style: { padding: 16, flex: 1, display: 'flex', flexDirection: 'column' } },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
          React.createElement('div', { style: { width: 30, height: 30, borderRadius: 8, background: p.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: p.icon, size: 16 })),
          React.createElement('div', { style: { minWidth: 0, flex: 1 } },
            React.createElement('h4', { style: { fontSize: 15, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, p.name),
            React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)' } }, p.type),
          ),
        ),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 12, fontSize: 12.5 } },
          React.createElement('span', { style: { width: 7, height: 7, borderRadius: 999, background: p.domain ? 'var(--success)' : 'var(--muted-2)' } }),
          React.createElement('span', { style: { color: p.domain ? 'var(--text-2)' : 'var(--muted-2)', fontFamily: p.domain ? 'var(--font-mono)' : 'inherit', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, p.domain || 'No domain yet'),
        ),
        React.createElement('div', { style: { marginTop: 14 } },
          React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 } },
            React.createElement('span', { style: { color: 'var(--muted)' } }, 'Website readiness'),
            React.createElement('span', { style: { fontWeight: 650 } }, (p.readiness ?? 0) + '%'),
          ),
          React.createElement(ProgressBar, { value: p.readiness ?? 0, height: 7 }),
        ),
        React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 13, paddingTop: 13, borderTop: '1px solid var(--border-soft)' } },
          React.createElement(MiniStat, { icon: 'folder', label: (p.pagesCount ?? 0) + ' pages', tone: 'info' }),
          React.createElement(MiniStat, { icon: 'rocket', label: p.hostingStatus === 'deployed' ? 'Hosted' : p.hostingStatus === 'building' ? 'Building' : p.hostingStatus === 'preview' ? 'Preview' : 'Not hosted', tone: statusTone(p.hostingStatus) }),
          React.createElement(MiniStat, { icon: 'search', label: p.seoScore != null ? 'SEO ' + p.seoScore + '%' : 'SEO not scored', tone: statusTone(p.seoStatus) }),
        ),
        React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 14 } },
          React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'edit', style: { flex: 1 }, onClick: (e) => { e.stopPropagation(); window.navigate('/app/builder'); } }, 'Edit'),
          React.createElement(Button, { variant: p.status === 'published' ? 'soft' : 'primary', size: 'sm', icon: p.status === 'published' ? 'externalLink' : 'rocket', style: { flex: 1 }, onClick: (e) => { e.stopPropagation(); window.navigate('/app/infrastructure'); } }, p.status === 'published' ? 'View' : 'Publish'),
        ),
      ),
    );
  }

  function MetricTile({ icon, value, label, tone = 'primary' }) {
    const [bg, fg] = window.BZ_TONES[tone];
    return React.createElement(Card, { pad: 16, style: { display: 'flex', alignItems: 'center', gap: 13 } },
      React.createElement('div', { style: { width: 40, height: 40, borderRadius: 11, background: bg, color: fg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: icon, size: 20 })),
      React.createElement('div', { style: { minWidth: 0 } },
        React.createElement('div', { style: { fontSize: 22, fontWeight: 730, letterSpacing: '-0.03em', lineHeight: 1 } }, value),
        React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', marginTop: 4 } }, label),
      ),
    );
  }

  function StatusRow({ icon, label, value, status }) {
    return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 11, padding: '10px 0', borderBottom: '1px solid var(--border-soft)' } },
      React.createElement('div', { style: { width: 32, height: 32, 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: 550 } }, label),
        value ? React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)' } }, value) : null,
      ),
      React.createElement(StatusBadge, { status, size: 'sm' }),
    );
  }

  function DashboardPage() {
    const user = window.useCurrentUser();
    const [prompt, setPrompt] = useState('');
    // null = still loading; [] is a real, legitimate "no projects yet" state
    // for a brand-new account — never seeded from window.DATA prototype
    // content, so a real user never sees fabricated sample websites.
    const [projects, setProjects] = useState(null);
    const [loadError, setLoadError] = useState(null);
    useEffect(() => {
      let cancelled = false;
      window.API.projects.list()
        .then(list => { if (!cancelled) setProjects(Array.isArray(list) ? list : []); })
        .catch(err => {
          if (cancelled) return;
          setLoadError(err.message || 'Failed to load your websites.');
          setProjects([]);
        });
      return () => { cancelled = true; };
    }, []);

    const loading = projects === null;
    const list = projects || [];
    const primary = list[0] || null;

    // Real go-live checklist for the spotlighted project — null while
    // loading/unavailable, or { checks: [] } if it has never been run yet.
    // Never fabricated: an unrun checklist shows as unrun, not as fake
    // progress.
    const [checklist, setChecklist] = useState(null);
    useEffect(() => {
      if (!primary) { setChecklist(null); return; }
      let cancelled = false;
      window.API.goLive.checklist(primary.id).then(c => { if (!cancelled) setChecklist(c); }).catch(() => { if (!cancelled) setChecklist(null); });
      return () => { cancelled = true; };
    }, [primary && primary.id]);
    const published = list.filter(p => p.status === 'published').length;
    const drafts = list.filter(p => p.status === 'draft').length;
    const domains = list.filter(p => p.domainStatus === 'connected').length;
    const seoReady = list.filter(p => p.seoStatus === 'ready').length;
    const firstName = user && user.name ? user.name.split(' ')[0] : '';

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        title: firstName ? 'Welcome back, ' + firstName : 'Welcome back',
        sub: 'Create, edit and launch websites from a single workspace. Pick up where you left off, or start something new.',
      }),
      loadError ? React.createElement('div', {
        style: { display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', borderRadius: 'var(--r-md)', border: '1px solid var(--danger)', background: 'var(--danger-soft, rgba(220,38,38,0.08))', color: 'var(--danger)', fontSize: 13.5, marginBottom: 20 } },
        React.createElement(Icon, { name: 'alert', size: 16 }),
        React.createElement('span', null, 'Couldn’t load your websites: ' + loadError + '. '),
        React.createElement('button', { onClick: () => window.location.reload(), style: { border: 'none', background: 'none', color: 'var(--danger)', fontWeight: 650, cursor: 'pointer', textDecoration: 'underline', fontSize: 13.5 } }, 'Retry'),
      ) : null,

      // Prompt hero
      React.createElement('div', { style: { position: 'relative', borderRadius: 'var(--r-xl)', overflow: 'hidden', border: '1px solid var(--border)', boxShadow: 'var(--sh-md)', background: 'linear-gradient(120deg, var(--primary) 0%, var(--primary-700) 70%, #3A2EA8 100%)', padding: '26px 26px', marginBottom: 22 } },
        React.createElement('div', { style: { position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.05) 0 1px, transparent 1px 16px)' } }),
        React.createElement('div', { style: { position: 'absolute', top: '-30%', right: '-5%', width: 340, height: 340, borderRadius: '50%', background: 'radial-gradient(circle, rgba(45,212,191,0.3), transparent 70%)' } }),
        React.createElement('div', { style: { position: 'relative', maxWidth: 680 } },
          React.createElement('div', { style: { display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 11px', borderRadius: 999, background: 'rgba(255,255,255,0.18)', color: '#fff', fontSize: 12, fontWeight: 600, marginBottom: 12 } },
            React.createElement(Icon, { name: 'sparkles', size: 13 }), 'Create a website from a prompt'),
          React.createElement('h2', { style: { fontSize: 23, fontWeight: 720, color: '#fff', letterSpacing: '-0.03em' } }, 'What website do you want to build?'),
          React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 16, background: 'var(--surface)', borderRadius: 'var(--r-md)', padding: 8, boxShadow: 'var(--sh-lg)' } },
            React.createElement('input', {
              value: prompt, onChange: (e) => setPrompt(e.target.value),
              onKeyDown: (e) => e.key === 'Enter' && window.navigate('/app/new'),
              placeholder: 'e.g. A modern dental clinic in Newark with appointment booking…',
              style: { flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14.5, color: 'var(--text)', padding: '0 8px', minWidth: 0 },
            }),
            React.createElement(Button, { variant: 'primary', icon: 'wand', onClick: () => window.navigate('/app/new') }, 'Build my website'),
          ),
          React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 12 } },
            ['Dental clinic', 'Brunch cafe', 'Real estate', 'Coaching'].map(s => React.createElement('button', { key: s, onClick: () => { setPrompt('A ' + s.toLowerCase() + ' website'); window.navigate('/app/new'); },
              style: { padding: '5px 11px', borderRadius: 999, border: '1px solid rgba(255,255,255,0.3)', background: 'rgba(255,255,255,0.12)', color: '#fff', fontSize: 12.5, cursor: 'pointer' } }, s)),
          ),
        ),
      ),

      // metric strip
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 14, marginBottom: 22 } },
        React.createElement(MetricTile, { icon: 'layers', value: loading ? '—' : list.length, label: 'Websites', tone: 'primary' }),
        React.createElement(MetricTile, { icon: 'rocket', value: loading ? '—' : published, label: 'Published', tone: 'secondary' }),
        React.createElement(MetricTile, { icon: 'edit', value: loading ? '—' : drafts, label: 'In draft', tone: 'accent' }),
        React.createElement(MetricTile, { icon: 'globe', value: loading ? '—' : domains, label: 'Domains connected', tone: 'info' }),
        React.createElement(MetricTile, { icon: 'search', value: loading ? '—' : seoReady, label: 'SEO ready', tone: 'primary' }),
      ),

      // main grid
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 340px', gap: 20, alignItems: 'start' }, className: 'bz-dash-grid' },
        React.createElement('div', null,
          React.createElement(SectionTitle, {
            title: 'Your websites', sub: 'Every project, with domain, hosting and SEO status',
            action: React.createElement(Button, { variant: 'ghost', size: 'sm', iconRight: 'arrowRight', onClick: () => window.navigate('/app/templates') }, 'Browse templates'),
          }),
          loading
            ? React.createElement('div', { style: { padding: '40px 0', textAlign: 'center', color: 'var(--muted)', fontSize: 13.5 } }, 'Loading your websites…')
            : list.length === 0
              ? React.createElement(Card, { pad: 32, style: { textAlign: 'center' } },
                  React.createElement(Icon, { name: 'layers', size: 28, style: { color: 'var(--muted-2)', marginBottom: 10 } }),
                  React.createElement('h4', { style: { fontSize: 15, fontWeight: 650, marginBottom: 4 } }, 'No websites yet'),
                  React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginBottom: 16 } }, 'Build your first website from a prompt above, or start from a template.'),
                  React.createElement(Button, { variant: 'primary', icon: 'wand', onClick: () => window.navigate('/app/new') }, 'Build my website'),
                )
              : React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16 } },
                  list.map(p => React.createElement(ProjectCard, { key: p.id, p })),
                ),
        ),
        // right column — only meaningful once there's a real primary project
        !primary ? null : React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 20 } },
          // primary spotlight
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 14 } },
              React.createElement(RingProgress, { value: primary.readiness ?? 0, size: 76, sub: 'ready' }),
              React.createElement('div', { style: { flex: 1, minWidth: 0 } },
                React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', fontWeight: 650, textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Closest to launch'),
                React.createElement('div', { style: { fontSize: 16, fontWeight: 650, marginTop: 3 } }, primary.name),
                React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', marginTop: 2 } }, 'Last edited ' + new Date(primary.updatedAt).toLocaleDateString()),
              ),
            ),
            React.createElement('div', { style: { marginTop: 10 } },
              React.createElement(StatusRow, { icon: 'layers', label: 'Website', value: (primary.pagesCount ?? 0) + ' pages built', status: 'published' }),
              React.createElement(StatusRow, { icon: 'globe', label: 'Domain', value: primary.domain, status: primary.domainStatus }),
              React.createElement(StatusRow, { icon: 'rocket', label: 'Hosting', value: primary.hosting, status: 'deployed' }),
              React.createElement(StatusRow, { icon: 'search', label: 'SEO', value: primary.seoScore != null ? 'Score ' + primary.seoScore + '/100' : 'Not scored yet', status: primary.seoStatus }),
              React.createElement(StatusRow, { icon: 'google', label: 'Google Search Console', value: 'Indexing in progress', status: primary.gscStatus }),
            ),
            React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
              React.createElement(Button, { variant: 'outline', icon: 'edit', style: { flex: 1 }, onClick: () => window.navigate('/app/builder') }, 'Continue editing'),
              React.createElement(Button, { variant: 'primary', icon: 'rocket', style: { flex: 1 }, onClick: () => window.navigate('/app/infrastructure') }, 'Publish'),
            ),
          ),
          // publish checklist — real go-live checklist for the primary project
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 } },
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                React.createElement(Icon, { name: 'checklist', size: 17, style: { color: 'var(--primary)' } }),
                React.createElement('h4', { style: { fontSize: 14.5, fontWeight: 650 } }, 'Launch checklist'),
              ),
              checklist && checklist.checks ? React.createElement('span', { style: { fontSize: 12.5, color: 'var(--muted)', fontWeight: 600 } },
                checklist.checks.filter(c => c.status === 'pass').length + '/' + checklist.checks.length) : null,
            ),
            !checklist || !checklist.checks || checklist.checks.length === 0
              ? React.createElement('div', { style: { padding: '10px 0', fontSize: 13, color: 'var(--muted)' } }, 'Checklist hasn’t been run for this project yet.')
              : React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
                  checklist.checks.slice(0, 6).map(c => {
                    const done = c.status === 'pass', warn = c.status === 'warn';
                    return React.createElement('div', { key: c.id, style: { display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0' } },
                      React.createElement('div', { style: { width: 20, height: 20, borderRadius: 999, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: done ? 'var(--secondary)' : warn ? 'var(--accent-soft)' : 'var(--surface-3)', color: done ? '#fff' : 'var(--accent)' } },
                        done ? React.createElement(Icon, { name: 'check', size: 12 }) : warn ? React.createElement('span', { style: { width: 6, height: 6, borderRadius: 999, background: 'var(--accent)' } }) : null),
                      React.createElement('span', { style: { fontSize: 13, fontWeight: 500, color: done ? 'var(--muted)' : 'var(--text)', textDecoration: done ? 'line-through' : 'none', flex: 1 } }, c.label),
                    );
                  }),
                ),
            React.createElement(Button, { variant: 'ghost', size: 'sm', full: true, iconRight: 'arrowRight', style: { marginTop: 8 }, onClick: () => window.navigate('/app/infrastructure') }, 'Open publish checklist'),
          ),
          // recent AI edits — no backend edit-history endpoint exists yet;
          // show an honest empty state rather than fabricated entries.
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 } },
              React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                React.createElement(Icon, { name: 'wand', size: 16, style: { color: 'var(--primary)' } }),
                React.createElement('h4', { style: { fontSize: 14.5, fontWeight: 650 } }, 'Recent edits'),
              ),
              React.createElement('button', { onClick: () => window.navigate('/app/builder'), style: { fontSize: 12.5, color: 'var(--primary)', fontWeight: 600, border: 'none', background: 'none', cursor: 'pointer' } }, 'Open builder'),
            ),
            React.createElement('div', { style: { padding: '10px 0', fontSize: 13, color: 'var(--muted)' } }, 'Edit history for this project will show up here once you make changes in the builder.'),
          ),
        ),
      ),
      React.createElement('style', null, '@media (max-width: 960px){ .bz-dash-grid{ grid-template-columns: 1fr !important; } }'),
    );
  }

  window.DashboardPage = DashboardPage;
})();
