/* ============================================================
   Bizia — SEO & Google  (/app/seo)
   "Help Google find your website" — titles, sitemap, GSC.
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const { Card, Badge, Button, Icon, PageHeader, StatusBadge, RingProgress, Modal } = window;

  function SeoPage() {
    const data = window.DATA;
    const [s, setSeo] = useState(data.seo);
    const [editPage, setEditPage] = useState(null);
    const titleRef = useRef(null);
    const descRef = useRef(null);
    const seoStatus = { ready: ['success', 'Optimized'], partial: ['warning', 'Needs work'], missing: ['danger', 'Missing'] };

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

    async function handleAutoOptimize() {
      window.toast({ title: 'Optimizing all pages', desc: 'Bizia regenerated titles & descriptions.', tone: 'primary' });
      const result = await window.API.seo.update(projectId, { autoOptimize: true }).catch(() => null);
      if (result) setSeo(result);
    }

    async function handleSaveSeо() {
      const title = titleRef.current?.value || '';
      const desc = descRef.current?.value || '';
      const updated = await window.API.seo.update(projectId, { pageSlug: editPage.slug, title, desc }).catch(() => null);
      if (updated) setSeo(updated);
      window.toast({ title: 'SEO saved', desc: editPage.page, tone: 'success' });
      setEditPage(null);
    }

    async function handleGscStep(g) {
      window.toast({ title: g.label, tone: 'primary' });
      const result = await window.API.searchConsole.submit(projectId, { step: g.id }).catch(() => null);
      if (result) setSeo(prev => ({ ...prev, gsc: result.gsc || prev.gsc }));
    }

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        icon: 'search', title: 'SEO & Google',
        sub: 'Help Google find and understand your website. Bizia writes your titles, descriptions, sitemap and robots.txt — and guides you through Google Search Console.',
        actions: React.createElement(Button, { variant: 'primary', icon: 'wand', onClick: handleAutoOptimize }, 'Auto-optimize all'),
      }),

      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0,1.6fr) minmax(0,1fr)', gap: 16, alignItems: 'start' }, className: 'bz-seo-grid' },
        // LEFT
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
          // per-page SEO
          React.createElement(Card, { pad: 0, style: { overflow: 'hidden' } },
            React.createElement('div', { style: { padding: '16px 20px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
              React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650 } }, 'Page titles & descriptions'),
              React.createElement('span', { style: { fontSize: 12.5, color: 'var(--muted)' } }, 'What Google shows in search results')),
            s.pages.map((p, i) => {
              const [tone, lbl] = seoStatus[p.status];
              return React.createElement('div', { key: i, style: { padding: '16px 20px', borderBottom: i < s.pages.length - 1 ? '1px solid var(--border-soft)' : 'none' } },
                React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 } },
                  React.createElement('span', { style: { fontSize: 13.5, fontWeight: 650 } }, p.page),
                  React.createElement('span', { style: { fontSize: 11.5, fontFamily: 'var(--font-mono)', color: 'var(--muted)' } }, p.slug),
                  React.createElement(Badge, { tone, size: 'sm' }, lbl),
                  React.createElement('div', { style: { flex: 1 } }),
                  React.createElement(Button, { variant: p.status === 'missing' ? 'soft' : 'ghost', size: 'sm', icon: 'wand', onClick: () => setEditPage(p) }, p.status === 'missing' ? 'Generate' : 'Edit')),
                p.title ? React.createElement('div', null,
                  React.createElement('div', { style: { fontSize: 14, color: 'var(--info)', fontWeight: 550, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, p.title),
                  React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.45, marginTop: 3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' } }, p.desc))
                  : React.createElement('div', { style: { fontSize: 13, color: 'var(--danger)', display: 'flex', alignItems: 'center', gap: 6 } }, React.createElement(Icon, { name: 'alert', size: 14 }), 'No title or description yet — Google may skip this page'));
            }),
          ),
          // Open graph preview
          React.createElement(Card, { pad: 22 },
            React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650, marginBottom: 4 } }, 'Social share preview'),
            React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginBottom: 16 } }, 'How your site looks when shared on social media or messaging apps.'),
            React.createElement('div', { style: { maxWidth: 440, borderRadius: 'var(--r-md)', overflow: 'hidden', border: '1px solid var(--border)', background: 'var(--surface-2)' } },
              React.createElement('div', { style: { height: 180, background: 'linear-gradient(135deg,#FF8A5B,#FFB454)', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
                React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: 12, color: 'rgba(255,255,255,0.8)' } }, 'og:image — 1200×630')),
              React.createElement('div', { style: { padding: 14 } },
                React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em' } }, s.og.url),
                React.createElement('div', { style: { fontSize: 15, fontWeight: 650, marginTop: 4 } }, s.og.title),
                React.createElement('div', { style: { fontSize: 13, color: 'var(--muted)', marginTop: 3 } }, s.og.desc))),
          ),
          // sitemap / robots
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }, className: 'bz-seo-files' },
            [['layers', 'sitemap.xml', s.sitemap.urls + ' URLs included', 'A map of every page for Google', s.sitemap.status],
             ['shield', 'robots.txt', 'Search engines welcomed', 'Tells crawlers what they can read', s.robots.status]].map((f, i) =>
              React.createElement(Card, { key: i, pad: 18 },
                React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 } },
                  React.createElement('div', { style: { width: 36, height: 36, borderRadius: 9, background: 'var(--secondary-soft)', color: 'var(--secondary)', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: f[0], size: 18 })),
                  React.createElement(Badge, { tone: 'success', icon: 'check', size: 'sm' }, 'Generated')),
                React.createElement('div', { style: { fontSize: 14.5, fontWeight: 650, fontFamily: 'var(--font-mono)' } }, f[1]),
                React.createElement('div', { style: { fontSize: 12.5, color: 'var(--text-2)', marginTop: 3 } }, f[2]),
                React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 2 } }, f[3]),
                React.createElement(Button, { variant: 'ghost', size: 'sm', icon: 'eye', style: { marginTop: 10 }, onClick: () => window.toast({ title: 'Preview ' + f[1], tone: 'info' }) }, 'View')),
            )),
        ),
        // RIGHT
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
          React.createElement(Card, { pad: 22, style: { display: 'flex', alignItems: 'center', gap: 18 } },
            React.createElement(RingProgress, { value: s.score, size: 88, sub: 'SEO' }),
            React.createElement('div', null,
              React.createElement('div', { style: { fontSize: 15, fontWeight: 650 } }, 'Good SEO health'),
              React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginTop: 5, lineHeight: 1.45 } }, '4 of 5 pages optimized. Add a title to the Gallery page to reach 100%.')),
          ),
          // Google Search Console
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 9, marginBottom: 4 } },
              React.createElement(Icon, { name: 'google', size: 18, style: { color: 'var(--primary)' } }), React.createElement('h4', { style: { fontSize: 15, fontWeight: 650 } }, 'Help Google find your site')),
            React.createElement('p', { style: { fontSize: 12.5, color: 'var(--muted)', marginBottom: 14 } }, 'Google Search Console gets your pages into search results.'),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 1 } },
              s.gsc.map((g, i) => {
                const done = g.status === 'done', prog = g.status === 'in-progress';
                return React.createElement('div', { key: g.id, style: { display: 'flex', gap: 11, padding: '10px 0', borderBottom: i < s.gsc.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, fontWeight: 550 } }, g.label, g.optional ? React.createElement('span', { style: { fontSize: 10.5, color: 'var(--muted-2)', marginLeft: 6 } }, 'Optional') : null),
                    React.createElement('div', { style: { fontSize: 11.5, color: 'var(--muted)', marginTop: 1 } }, g.simple)),
                  !done && !prog ? React.createElement(Button, { variant: 'ghost', size: 'sm', onClick: () => handleGscStep(g) }, 'Start') : null);
              }),
            ),
          ),
          // indexing status
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 } },
              React.createElement('h4', { style: { fontSize: 14.5, fontWeight: 650 } }, 'Indexing status'),
              React.createElement(StatusBadge, { status: 'in-progress', label: 'In progress', size: 'sm' })),
            React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', gap: 6 } },
              React.createElement('span', { style: { fontSize: 28, fontWeight: 730 } }, s.indexing.indexed),
              React.createElement('span', { style: { fontSize: 14, color: 'var(--muted)' } }, 'of ' + s.indexing.total + ' pages indexed')),
            React.createElement(window.ProgressBar, { value: (s.indexing.indexed / s.indexing.total) * 100, height: 8, style: { marginTop: 12 } }),
            React.createElement('p', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 10 } }, 'Google usually finishes indexing new pages within a few days.'),
          ),
          // GA placeholder
          React.createElement(Card, { pad: 20 },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
              React.createElement('div', { style: { width: 36, height: 36, borderRadius: 9, background: '#F9AB0018', color: '#E8710A', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: 'chart', size: 18 })),
              React.createElement('div', { style: { flex: 1 } },
                React.createElement('div', { style: { fontSize: 14, fontWeight: 650 } }, 'Google Analytics'),
                React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)' } }, 'See visitor stats from Google')),
              React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'plug', onClick: () => window.toast({ title: 'Connect Google Analytics', desc: 'Mocked in prototype.', tone: 'info' }) }, 'Connect')),
          ),
        ),
      ),

      // edit SEO modal
      React.createElement(Modal, { open: !!editPage, onClose: () => setEditPage(null), width: 520 },
        editPage ? React.createElement('div', null,
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 } },
            React.createElement('h2', { style: { fontSize: 20, fontWeight: 700 } }, editPage.page + ' — SEO'),
            React.createElement(Badge, { tone: 'primary', icon: 'wand', size: 'sm' }, 'AI-assisted')),
          React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginBottom: 18 } }, 'These appear in Google search results. Bizia can generate them for you.'),
          React.createElement('div', { style: { marginBottom: 16 } },
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 7 } }, React.createElement('span', { style: { fontSize: 13, fontWeight: 600 } }, 'Page title'), React.createElement('span', { style: { fontSize: 11.5, color: 'var(--muted)' } }, (editPage.title || '').length + '/60')),
            React.createElement('input', { ref: titleRef, defaultValue: editPage.title, placeholder: 'e.g. Gallery — AmazeBites Cafe', style: inpStyle })),
          React.createElement('div', { style: { marginBottom: 18 } },
            React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 7 } }, React.createElement('span', { style: { fontSize: 13, fontWeight: 600 } }, 'Meta description'), React.createElement('span', { style: { fontSize: 11.5, color: 'var(--muted)' } }, (editPage.desc || '').length + '/155')),
            React.createElement('textarea', { ref: descRef, defaultValue: editPage.desc, rows: 3, placeholder: 'A short, compelling summary of this page…', style: { ...inpStyle, resize: 'none' } })),
          React.createElement('div', { style: { display: 'flex', gap: 10 } },
            React.createElement(Button, { variant: 'soft', icon: 'wand', onClick: async () => {
              window.toast({ title: 'Generated with AI', tone: 'primary' });
              const result = await window.API.seo.update(projectId, { pageSlug: editPage.slug, autoGenerate: true }).catch(() => null);
              if (result && titleRef.current) {
                const pg = result.pages?.find(p => p.slug === editPage.slug);
                if (pg) { titleRef.current.value = pg.title || ''; descRef.current.value = pg.desc || ''; }
              }
            } }, 'Generate for me'),
            React.createElement('div', { style: { flex: 1 } }),
            React.createElement(Button, { variant: 'ghost', onClick: () => setEditPage(null) }, 'Cancel'),
            React.createElement(Button, { variant: 'primary', icon: 'check', onClick: handleSaveSeо }, 'Save')),
        ) : null,
      ),
      React.createElement('style', null, '@media(max-width:900px){.bz-seo-grid{grid-template-columns:1fr !important}}@media(max-width:520px){.bz-seo-files{grid-template-columns:1fr !important}}'),
    );
  }

  const inpStyle = { width: '100%', padding: '10px 12px', borderRadius: 8, border: '1px solid var(--border-strong)', background: 'var(--surface)', fontSize: 13.5, color: 'var(--text)', outline: 'none', fontFamily: 'inherit' };

  window.SeoPage = SeoPage;
})();
