/* ============================================================
   Bizia — Website Builder workspace  (/app/builder)
   Real generated-website preview (iframe + postMessage bridge) +
   pages/sections list, AI prompt bar, annotation pins, inspector.

   The canvas is no longer a hardcoded mock — it is an iframe pointed
   at the same preview endpoint used by /app/preview and the client
   review flow, serving the actual files the publish pipeline deploys.
   Sections, hover/click, and pin placement come from postMessage
   events posted by a small bridge script embedded in every generated
   page (see backend/src/services/ai/siteFileGenerator.ts,
   buildBuilderBridgeJs) — the iframe is cross-origin, so the parent
   can't read its DOM directly.
   ============================================================ */
(function () {
  const { useState, useEffect, useRef, useCallback } = React;
  const { Icon, Button, IconButton, Badge, Segmented, StatusBadge, Avatar, Tooltip } = window;

  const SECTION_LABELS = {
    nav: 'Navigation', hero: 'Hero', 'trust-bar': 'Trust bar', about: 'About',
    services: 'Services', 'why-us': 'Why us', process: 'Process', gallery: 'Gallery',
    testimonials: 'Testimonials', pricing: 'Pricing', faq: 'FAQ', contact: 'Contact',
    cta: 'Call to action', team: 'Team', insurance: 'Insurance', appointment: 'Appointment',
    footer: 'Footer',
  };

  const PROMPT_SUGGESTIONS = [
    'Make this section more premium and modern',
    'Make the tone more professional',
    'Make this section shorter and punchier',
    'Make the colors softer',
  ];

  function LeftItem({ icon, label, active, sub, onClick }) {
    return React.createElement('button', {
      onClick,
      style: { display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '8px 10px', borderRadius: 'var(--r-sm)', border: 'none', cursor: 'pointer', textAlign: 'left',
        background: active ? 'var(--primary-soft)' : 'transparent', color: active ? 'var(--primary-700)' : 'var(--text-2)', marginBottom: 2 },
      onMouseEnter: (e) => { if (!active) e.currentTarget.style.background = 'var(--surface-3)'; },
      onMouseLeave: (e) => { if (!active) e.currentTarget.style.background = 'transparent'; },
    },
      React.createElement(Icon, { name: icon, size: 16 }),
      React.createElement('div', { style: { flex: 1, minWidth: 0 } },
        React.createElement('div', { style: { fontSize: 13.5, fontWeight: active ? 600 : 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, label),
        sub ? React.createElement('div', { style: { fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' } }, sub) : null),
    );
  }

  function BuilderPage() {
    const currentUser = window.useCurrentUser();
    const [project, setProject] = useState(null);
    const [manifest, setManifest] = useState(null);
    const [activePage, setActivePage] = useState(null);
    const [device, setDevice] = useState('desktop');
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState(null);

    const [sections, setSections] = useState([]); // real ids reported by the embedded page
    const [selectedId, setSelectedId] = useState(null);
    const [hoveredId, setHoveredId] = useState(null);

    const [annotationMode, setAnnotationMode] = useState(false);
    const [pins, setPins] = useState([]); // { id, sectionId, xPct, yPct, status, instruction, annotationId }
    const [pendingPin, setPendingPin] = useState(null); // { sectionId, xPct, yPct }
    const [pinDraft, setPinDraft] = useState('');
    const [activePinId, setActivePinId] = useState(null);

    const [prompt, setPrompt] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [pendingChange, setPendingChange] = useState(null); // { annotationId, prompt, sectionId }

    const [editCredits, setEditCredits] = useState(null);
    const [editJobs, setEditJobs] = useState([]);
    const [iframeGen, setIframeGen] = useState(0); // bump to force the iframe to refetch after an edit
    const iframeRef = useRef();

    const annotationModeRef = useRef(annotationMode);
    useEffect(() => { annotationModeRef.current = annotationMode; }, [annotationMode]);
    const manifestRef = useRef(manifest);
    useEffect(() => { manifestRef.current = manifest; }, [manifest]);

    const projectId = new URLSearchParams(window.location.hash.split('?')[1] || '').get('project');

    const loadEditJobs = useCallback(() => {
      if (!projectId) return;
      window.API.websites.editJobs(projectId).then(jobs => setEditJobs(Array.isArray(jobs) ? jobs.slice(0, 6) : [])).catch(() => {});
    }, [projectId]);

    useEffect(() => {
      if (!projectId) { setLoading(false); return; }
      setLoading(true);
      setLoadError(null);
      Promise.all([
        window.API.projects.get(projectId),
        window.API.preview.projectManifest(projectId),
      ]).then(([p, m]) => {
        setProject(p);
        setEditCredits(typeof p?.editCredits === 'number' ? p.editCredits : null);
        setManifest(m);
        if (m?.pages?.length) setActivePage(m.pages[0].path);
      }).catch(e => setLoadError(e.message || 'Could not load this project.'))
        .finally(() => setLoading(false));
      loadEditJobs();
    }, [projectId]);

    // Reset per-page interaction state when switching pages — pins/sections
    // are specific to whatever page is currently loaded in the iframe.
    useEffect(() => {
      setSections([]); setSelectedId(null); setHoveredId(null);
      setPins([]); setPendingPin(null); setActivePinId(null); setPendingChange(null);
    }, [activePage]);

    // Bridge: receive events from the embedded generated page.
    useEffect(() => {
      function onMessage(e) {
        const msg = e.data;
        if (!msg || msg.source !== 'bizia-preview') return;
        if (msg.type === 'ready') {
          setSections(msg.sections || []);
        } else if (msg.type === 'hover') {
          setHoveredId(msg.sectionId);
        } else if (msg.type === 'click') {
          if (annotationModeRef.current) {
            setPendingPin({ sectionId: msg.sectionId, xPct: msg.xPct, yPct: msg.yPct });
            setPinDraft('');
          } else {
            setSelectedId(msg.sectionId);
            setActivePinId(null);
            setPendingChange(null);
          }
        } else if (msg.type === 'nav') {
          const pages = manifestRef.current?.pages || [];
          const target = pages.find(p => p.path === msg.href || p.path === msg.href.replace(/^\.?\//, ''));
          if (target) setActivePage(target.path);
        } else if (msg.type === 'pin-click') {
          setActivePinId(msg.pinId);
          setSelectedId(null);
        }
      }
      window.addEventListener('message', onMessage);
      return () => window.removeEventListener('message', onMessage);
    }, []);

    // Tell the embedded page what to highlight.
    useEffect(() => {
      const win = iframeRef.current && iframeRef.current.contentWindow;
      if (!win) return;
      win.postMessage({ type: 'bizia-highlight', sectionId: selectedId || hoveredId, selected: !!selectedId }, '*');
    }, [selectedId, hoveredId]);

    // Keep pin markers inside the embedded page in sync.
    useEffect(() => {
      const win = iframeRef.current && iframeRef.current.contentWindow;
      if (!win) return;
      win.postMessage({
        type: 'bizia-render-pins',
        pins: pins.map((p, i) => ({ id: p.id, sectionId: p.sectionId, xPct: p.xPct, yPct: p.yPct, status: p.status, label: String(i + 1) })),
      }, '*');
    }, [pins]);

    const previewUrl = projectId && activePage
      ? window.API.preview.url(projectId, activePage) + '&v=' + iframeGen
      : null;

    async function createAnnotationFor(sectionId, instruction) {
      const pageSlug = activePage === 'index.html' ? 'home' : (activePage || '').replace(/\.html$/, '');
      const res = await window.API.websites.createAnnotation(projectId, { sectionId, instruction, pageSlug });
      return res?.annotationId || res?.data?.annotationId;
    }

    async function applyAnnotation(annotationId) {
      try {
        const res = await window.API.websites.applyEdit(projectId, annotationId);
        const data = res?.data || res;
        if (typeof data?.creditsRemaining === 'number') setEditCredits(data.creditsRemaining);
        setIframeGen(g => g + 1); // reload the iframe — the file on disk just changed
        loadEditJobs();
        window.toast({ title: 'Change applied', desc: 'Bizia updated the live preview.', tone: 'success' });
        return true;
      } catch (e) {
        if (e.status === 402) {
          window.toast({ title: 'No edit credits remaining', desc: 'Purchase more credits to continue editing.', tone: 'warning' });
        } else {
          window.toast({ title: 'Edit failed', desc: e.message || 'Could not apply this change.', tone: 'danger' });
        }
        return false;
      }
    }

    async function savePin() {
      if (!pendingPin || !pinDraft.trim()) return;
      try {
        const annotationId = await createAnnotationFor(pendingPin.sectionId, pinDraft);
        const id = 'pin-' + (annotationId || Date.now());
        const pin = { id, sectionId: pendingPin.sectionId, xPct: pendingPin.xPct, yPct: pendingPin.yPct, status: 'open', instruction: pinDraft, annotationId };
        setPins(prev => [...prev, pin]);
        setActivePinId(id);
        setPendingPin(null);
        setAnnotationMode(false);
      } catch (e) {
        window.toast({ title: 'Could not add comment', desc: e.message || 'Try again.', tone: 'danger' });
      }
    }

    async function resolvePin(id, status) {
      const pin = pins.find(p => p.id === id);
      if (!pin) return;
      if (status === 'applied' && pin.annotationId) {
        const ok = await applyAnnotation(pin.annotationId);
        if (!ok) return;
      }
      setPins(prev => prev.map(p => p.id === id ? { ...p, status } : p));
      setActivePinId(null);
    }

    async function submitPrompt(text) {
      const t = (text || '').trim();
      if (!t) return;
      if (!selectedId) {
        window.toast({ title: 'Select a section first', desc: 'Click a section in the preview, then describe your change.', tone: 'info' });
        return;
      }
      setSubmitting(true);
      try {
        const annotationId = await createAnnotationFor(selectedId, t);
        setPendingChange({ annotationId, prompt: t, sectionId: selectedId });
        setPrompt('');
      } catch (e) {
        window.toast({ title: 'Could not submit change', desc: e.message || 'Try again.', tone: 'danger' });
      } finally {
        setSubmitting(false);
      }
    }

    async function approvePending() {
      if (!pendingChange) return;
      const ok = await applyAnnotation(pendingChange.annotationId);
      if (ok) setPendingChange(null);
    }

    const curPin = pins.find(p => p.id === activePinId);
    const deviceW = { desktop: null, tablet: 834, mobile: 390 }[device];
    const pages = manifest?.pages || [];

    if (!projectId) {
      return React.createElement('div', { style: { padding: 40, textAlign: 'center', color: 'var(--muted)' } }, 'No project selected. Open the Builder from a project.');
    }
    if (loading) {
      return React.createElement('div', { style: { padding: 40, textAlign: 'center', color: 'var(--muted)' } }, 'Loading…');
    }
    if (loadError) {
      return React.createElement('div', { style: { padding: 40, maxWidth: 420, margin: '0 auto', textAlign: 'center' } },
        React.createElement(Icon, { name: 'alertTriangle', size: 28, style: { color: 'var(--danger)', marginBottom: 12 } }),
        React.createElement('div', { style: { fontSize: 15, fontWeight: 650, marginBottom: 6 } }, 'Could not load this project'),
        React.createElement('div', { style: { fontSize: 13.5, color: 'var(--muted)', marginBottom: 16 } }, loadError),
        React.createElement(Button, { variant: 'primary', onClick: () => window.navigate('/app') }, 'Back to dashboard'));
    }
    if (!manifest?.hasFiles) {
      return React.createElement('div', { style: { padding: 40, maxWidth: 420, margin: '0 auto', textAlign: 'center' } },
        React.createElement(Icon, { name: 'monitor', size: 28, style: { color: 'var(--muted)', marginBottom: 12 } }),
        React.createElement('div', { style: { fontSize: 15, fontWeight: 650, marginBottom: 6 } }, 'No website generated yet'),
        React.createElement('div', { style: { fontSize: 13.5, color: 'var(--muted)', marginBottom: 16 } }, 'Generate this project’s website first, then come back to edit it here.'),
        React.createElement(Button, { variant: 'primary', onClick: () => window.navigate('/app') }, 'Back to dashboard'));
    }

    // ---- TOP BAR ----
    const topbar = React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, height: 56, padding: '0 16px', borderBottom: '1px solid var(--border)', background: 'var(--surface)', flexShrink: 0 } },
      React.createElement(IconButton, { name: 'arrowLeft', label: 'Back', onClick: () => window.navigate('/app') }),
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 9 } },
        React.createElement('div', { style: { width: 26, height: 26, borderRadius: 7, background: '#FF8A5B', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' } }, React.createElement(Icon, { name: 'briefcase', size: 14 })),
        React.createElement('div', null,
          React.createElement('div', { style: { fontSize: 13.5, fontWeight: 650, lineHeight: 1 } }, project?.name || 'Untitled project'),
          React.createElement('div', { style: { fontSize: 11, color: 'var(--muted)', marginTop: 2 } }, editCredits !== null ? editCredits + ' edit' + (editCredits === 1 ? '' : 's') + ' left' : ' ')),
      ),
      pages.length > 0 ? React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 5, padding: '5px 10px', borderRadius: 'var(--r-sm)', background: 'var(--surface-3)', marginLeft: 6 } },
        React.createElement(Icon, { name: 'home', size: 13, style: { color: 'var(--muted)' } }),
        React.createElement('span', { style: { fontSize: 13, fontWeight: 600 } }, pages.find(p => p.path === activePage)?.title || 'Home')) : null,
      React.createElement('div', { style: { flex: 1 } }),
      React.createElement(Segmented, { size: 'sm', value: device, onChange: setDevice, options: [{ value: 'desktop', icon: 'monitor', label: '' }, { value: 'tablet', icon: 'tablet', label: '' }, { value: 'mobile', icon: 'smartphone', label: '' }] }),
      React.createElement('div', { style: { width: 1, height: 24, background: 'var(--border)' } }),
      React.createElement(Tooltip, { label: 'Comment mode' }, React.createElement(IconButton, { name: 'pin', label: 'Annotate', active: annotationMode, onClick: () => { setAnnotationMode(a => !a); setActivePinId(null); setSelectedId(null); setPendingChange(null); } })),
      React.createElement(Button, { variant: 'ghost', size: 'sm', icon: 'eye', onClick: () => window.navigate('/app/preview/' + projectId) }, 'Full preview'),
      React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'rocket', onClick: () => window.navigate('/app/infrastructure?project=' + projectId) }, 'Publish'),
    );

    // ---- LEFT PANEL ----
    const left = React.createElement('div', { style: { width: 248, flexShrink: 0, borderRight: '1px solid var(--border)', background: 'var(--surface)', display: 'flex', flexDirection: 'column', overflowY: 'auto' } },
      React.createElement('div', { style: { padding: '14px 12px 8px' } },
        React.createElement('div', { style: { fontSize: 11, fontWeight: 650, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted-2)', padding: '0 8px', marginBottom: 8 } }, 'Pages'),
        pages.map(pg => React.createElement(LeftItem, { key: pg.path, icon: pg.type === 'home' ? 'home' : pg.type === 'contact' ? 'mail' : 'file', label: pg.title, active: pg.path === activePage, onClick: () => setActivePage(pg.path) })),
      ),
      React.createElement('div', { style: { padding: '8px 12px', borderTop: '1px solid var(--border-soft)' } },
        React.createElement('div', { style: { fontSize: 11, fontWeight: 650, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted-2)', padding: '4px 8px 8px' } }, 'Sections on this page'),
        sections.length === 0
          ? React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', padding: '4px 8px' } }, 'Loading…')
          : sections.map(id => React.createElement(LeftItem, { key: id, icon: 'layers', label: SECTION_LABELS[id] || id, active: selectedId === id, onClick: () => { setSelectedId(id); setActivePinId(null); setPendingChange(null); } })),
      ),
      React.createElement('div', { style: { marginTop: 'auto', padding: 12, borderTop: '1px solid var(--border-soft)' } },
        [['palette', 'Design & Brand', '/app/design'], ['search', 'SEO & Google', '/app/seo'], ['plug', 'Integrations', '/app/integrations']].map(r =>
          React.createElement(LeftItem, { key: r[1], icon: r[0], label: r[1], onClick: () => window.navigate(r[2]) })),
      ),
    );

    // ---- CANVAS ----
    const canvas = React.createElement('div', { style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', background: 'var(--surface-3)', position: 'relative' } },
      annotationMode ? React.createElement('div', { style: { position: 'absolute', top: 12, left: '50%', transform: 'translateX(-50%)', zIndex: 20, display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 999, background: 'var(--text)', color: 'var(--surface)', fontSize: 13, fontWeight: 550, boxShadow: 'var(--sh-lg)' } },
        React.createElement(Icon, { name: 'pin', size: 14 }), 'Comment mode — click anywhere on the site to drop a pin',
        React.createElement('button', { onClick: () => setAnnotationMode(false), style: { border: 'none', background: 'none', color: 'var(--surface)', cursor: 'pointer', display: 'flex', marginLeft: 4, opacity: 0.7 } }, React.createElement(Icon, { name: 'x', size: 14 }))) : null,
      React.createElement('div', { style: { flex: 1, overflowY: 'auto', overflowX: 'auto', padding: device === 'desktop' ? '28px' : '28px 12px', display: 'flex', justifyContent: 'center' } },
        React.createElement('div', {
          style: { position: 'relative', width: deviceW ? deviceW : '100%', maxWidth: deviceW ? deviceW : 1180, minWidth: deviceW || 0, height: 820, background: '#fff', borderRadius: device === 'mobile' ? 22 : 12, overflow: 'hidden', boxShadow: 'var(--sh-xl)', border: '1px solid var(--border)', transition: 'width .25s var(--ease)' },
        },
          previewUrl ? React.createElement('iframe', {
            key: activePage, ref: iframeRef, src: previewUrl, title: 'Website preview',
            style: { width: '100%', height: '100%', border: 'none', display: 'block', cursor: annotationMode ? 'crosshair' : 'default' },
          }) : null,
        ),
      ),
      // PROMPT BAR
      React.createElement('div', { style: { borderTop: '1px solid var(--border)', background: 'var(--surface)', padding: '12px 16px' } },
        React.createElement('div', { style: { display: 'flex', gap: 7, flexWrap: 'wrap', marginBottom: 10, maxHeight: 34, overflow: 'hidden' } },
          PROMPT_SUGGESTIONS.map(s => React.createElement('button', { key: s, onClick: () => setPrompt(s),
            style: { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 11px', borderRadius: 999, border: '1px solid var(--border)', background: 'var(--surface-2)', fontSize: 12.5, color: 'var(--text-2)', cursor: 'pointer', whiteSpace: 'nowrap' } },
            React.createElement(Icon, { name: 'sparkles', size: 12 }), s))),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px 8px 14px', borderRadius: 'var(--r-md)', border: '1.5px solid ' + (submitting ? 'var(--primary)' : 'var(--border-strong)'), background: 'var(--surface)', boxShadow: submitting ? '0 0 0 3px var(--ring)' : 'none' } },
          React.createElement(window.BiziaMark, { size: 24 }),
          React.createElement('input', { value: prompt, onChange: (e) => setPrompt(e.target.value), onKeyDown: (e) => e.key === 'Enter' && submitPrompt(prompt), placeholder: selectedId ? 'Tell Bizia what to change about "' + (SECTION_LABELS[selectedId] || selectedId) + '"…' : 'Select a section, then describe your change…', disabled: submitting,
            style: { flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14.5, color: 'var(--text)' } }),
          submitting ? React.createElement('div', { style: { width: 16, height: 16, border: '2px solid var(--primary)', borderTopColor: 'transparent', borderRadius: 999, animation: 'bz-spin .7s linear infinite' } })
            : React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'arrowUpRight', onClick: () => submitPrompt(prompt), disabled: !selectedId }, 'Send')),
      ),
    );

    // ---- RIGHT INSPECTOR ----
    function rightContent() {
      if (pendingPin) {
        return React.createElement('div', null,
          React.createElement(Badge, { tone: 'primary', icon: 'pin' }, 'New comment'),
          React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', margin: '10px 0 6px' } }, 'On ', React.createElement('strong', { style: { color: 'var(--text)' } }, SECTION_LABELS[pendingPin.sectionId] || pendingPin.sectionId)),
          React.createElement('textarea', { autoFocus: true, value: pinDraft, onChange: (e) => setPinDraft(e.target.value), placeholder: 'Describe the change you want…', rows: 4, style: { width: '100%', border: '1px solid var(--border-strong)', borderRadius: 8, padding: 10, fontSize: 13.5, fontFamily: 'inherit', outline: 'none', resize: 'none', color: 'var(--text)', background: 'var(--surface)' } }),
          React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 10 } },
            React.createElement(Button, { variant: 'ghost', size: 'sm', onClick: () => setPendingPin(null) }, 'Cancel'),
            React.createElement(Button, { variant: 'primary', size: 'sm', style: { flex: 1 }, disabled: !pinDraft.trim(), onClick: savePin }, 'Add comment')),
        );
      }
      if (curPin) {
        return React.createElement('div', null,
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 } },
            React.createElement(Badge, { tone: 'primary', icon: 'pin' }, 'Comment'),
            React.createElement('span', { style: { fontSize: 12.5, color: 'var(--muted)' } }, 'on ' + (SECTION_LABELS[curPin.sectionId] || curPin.sectionId))),
          React.createElement('div', { style: { padding: 13, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)', marginTop: 12 } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 } }, React.createElement(Avatar, { name: (currentUser && currentUser.name) || undefined, size: 24 }), React.createElement('span', { style: { fontSize: 12.5, fontWeight: 600 } }, 'You')),
            React.createElement('p', { style: { fontSize: 13.5, lineHeight: 1.5 } }, curPin.instruction)),
          curPin.status === 'open' ? React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
            React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'check', style: { flex: 1 }, onClick: () => resolvePin(curPin.id, 'applied') }, 'Approve & apply'),
            React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'x', onClick: () => resolvePin(curPin.id, 'rejected') }, 'Dismiss'))
            : React.createElement('div', { style: { marginTop: 16 } }, React.createElement(StatusBadge, { status: curPin.status === 'applied' ? 'published' : 'paused', label: curPin.status === 'applied' ? 'Applied' : 'Dismissed' })),
          React.createElement(Button, { variant: 'ghost', size: 'sm', full: true, style: { marginTop: 10 }, onClick: () => setActivePinId(null) }, 'Close'),
        );
      }
      if (pendingChange) {
        return React.createElement('div', null,
          React.createElement(Badge, { tone: 'accent', icon: 'wand' }, 'Review change'),
          React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', margin: '12px 0 6px' } }, 'On ', React.createElement('strong', { style: { color: 'var(--text)' } }, SECTION_LABELS[pendingChange.sectionId] || pendingChange.sectionId)),
          React.createElement('div', { style: { padding: 12, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', fontSize: 13.5, fontWeight: 500 } }, '“' + pendingChange.prompt + '”'),
          React.createElement('div', { style: { fontSize: 12, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 } }, 'Approving spends 1 edit credit and rewrites this section with Bizia’s AI. The preview will refresh once it’s applied.'),
          React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
            React.createElement(Button, { variant: 'primary', size: 'sm', icon: 'check', style: { flex: 1 }, onClick: approvePending }, 'Approve & apply'),
            React.createElement(Button, { variant: 'outline', size: 'sm', icon: 'x', onClick: () => setPendingChange(null) }, 'Discard')),
        );
      }
      if (selectedId) {
        return React.createElement('div', null,
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } }, React.createElement(Icon, { name: 'layers', size: 16, style: { color: 'var(--primary)' } }), React.createElement('span', { style: { fontSize: 15, fontWeight: 650 } }, SECTION_LABELS[selectedId] || selectedId)),
          React.createElement('div', { style: { height: 1, background: 'var(--border-soft)', margin: '14px 0' } }),
          React.createElement('div', { style: { fontSize: 13, color: 'var(--muted)', lineHeight: 1.6 } }, 'Describe the change you want in the prompt bar below, or switch to comment mode to pin a specific spot on this section.'),
        );
      }
      // default
      return React.createElement('div', null,
        React.createElement('div', { style: { fontSize: 11, fontWeight: 650, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--muted-2)', marginBottom: 10 } }, 'SEO'),
        React.createElement('div', { style: { padding: 12, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)' } },
          React.createElement('div', { style: { fontSize: 13, fontWeight: 650 } }, project?.name || 'Untitled project')),
        React.createElement(Button, { variant: 'outline', size: 'sm', full: true, icon: 'search', style: { marginTop: 10 }, onClick: () => window.navigate('/app/seo') }, 'Edit SEO'),
        React.createElement('div', { style: { fontSize: 11, fontWeight: 650, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--muted-2)', margin: '20px 0 10px' } }, 'Recent edits'),
        editJobs.length === 0
          ? React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)' } }, 'No edits yet. Select a section and describe a change to get started.')
          : React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
              editJobs.map(job => React.createElement('div', { key: job.id, style: { display: 'flex', gap: 9, padding: '8px 0', borderBottom: '1px solid var(--border-soft)' } },
                React.createElement('div', { style: { width: 24, height: 24, borderRadius: 7, background: job.status === 'failed' ? 'var(--danger-soft, #fdecea)' : 'var(--primary-soft)', color: job.status === 'failed' ? 'var(--danger)' : 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 } }, React.createElement(Icon, { name: job.status === 'failed' ? 'x' : 'wand', size: 12 })),
                React.createElement('div', { style: { flex: 1, minWidth: 0 } },
                  React.createElement('div', { style: { fontSize: 12.5, fontWeight: 500, lineHeight: 1.35 } }, job.annotation?.instruction || 'Edit'),
                  React.createElement('div', { style: { fontSize: 11, color: 'var(--muted-2)', marginTop: 2 } }, job.status + (job.createdAt ? ' · ' + new Date(job.createdAt).toLocaleString() : '')))))),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 16, padding: 12, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', fontSize: 12.5, color: 'var(--muted)' } },
          React.createElement(Icon, { name: 'pin', size: 14 }), 'Select a section to edit, or use comment mode to leave a pin.'),
      );
    }

    // On narrow viewports the sidebar is hidden by default to leave room for
    // the canvas — but when there's something the user actually needs to act
    // on (a pending pin, an open pin, or a change awaiting approval), it
    // can't stay hidden: that's the only place "Approve & apply" lives, and
    // hiding it made the AI-edit flow impossible to finish on mobile.
    const hasActionablePanel = !!(pendingPin || curPin || pendingChange);
    const right = React.createElement('div', {
      className: hasActionablePanel ? 'bz-right-panel bz-right-panel-actionable' : 'bz-right-panel',
      style: { width: 308, flexShrink: 0, borderLeft: '1px solid var(--border)', background: 'var(--surface)', overflowY: 'auto', padding: 18 },
    },
      React.createElement('div', { className: 'bz-anim-in', key: (pendingPin ? 'pp' : curPin ? 'pin' + curPin.id : pendingChange ? 'pc' : selectedId || 'none') }, rightContent()),
    );

    return React.createElement('div', { style: { height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' } },
      topbar,
      React.createElement('div', { style: { flex: 1, display: 'flex', minHeight: 0 } },
        React.createElement('div', { className: 'bz-builder-left' }, left),
        canvas,
        React.createElement('div', { className: 'bz-builder-right' }, right),
      ),
      React.createElement('style', null, '.bz-builder-left,.bz-builder-right{display:contents}@media(max-width:1100px){.bz-builder-right>div{width:264px}}@media(max-width:920px){.bz-builder-left>div{display:none}}@media(max-width:760px){.bz-right-panel{display:none}.bz-right-panel-actionable{display:flex!important;flex-direction:column;position:fixed;left:0;right:0;bottom:0;top:auto;width:100%;max-height:70vh;z-index:1000;border-left:none;border-top:1px solid var(--border);border-radius:16px 16px 0 0;box-shadow:0 -8px 28px rgba(0,0,0,.3)}}'),
    );
  }

  window.BuilderPage = BuilderPage;
})();
