// route-storefront.jsx — Storefront with anon / admin / edit modes.
// Storefront UI is a generic merchant theme; the Ecommos chrome (admin pill, edit mode) is overlaid.

function RouteStorefront({ navigate, state, setState }) {
  const sf = state.storefront;
  const set = (patch) => setState((s) => ({ ...s, storefront: { ...s.storefront, ...(typeof patch === 'function' ? patch(s.storefront) : patch) } }));
  const [draft, setDraft] = React.useState('');
  const [aiBusy, setAiBusy] = React.useState(false);
  const [selectedWidget, setSelectedWidget] = React.useState(null);
  const [hoverEl, setHoverEl] = React.useState(null);
  const [pendingChange, setPendingChange] = React.useState(null);
  const chatScrollRef = React.useRef(null);

  React.useEffect(() => {
    if (chatScrollRef.current) chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
  }, [sf.chat, aiBusy]);

  const sendChat = (text, attached) => {
    if (!text.trim() && !attached) return;
    const newMsg = { role: 'user', content: text, attachedEl: attached, ts: 'just now' };
    set((s) => ({ chat: [...s.chat, newMsg] }));
    setDraft('');
    setSelectedWidget(null);
    setAiBusy(true);
    setTimeout(() => {
      setAiBusy(false);
      const ver = 'v' + (sf.versions.length + 1);
      const resp = attached?.widget === 'spin'
        ? {
          role: 'ai', ts: 'just now',
          content: `Updated **Spin to Win** — \`button.bg\` → \`#1a8870\` (your brand green), \`button.color\` → white.`,
          change: { version: ver, summary: 'Button bg → brand green', file: 'spin-to-win/styles.tsx', diff: 4 },
        }
        : {
          role: 'ai', ts: 'just now',
          content: `Done — applied your change to the storefront preview.`,
          change: { version: ver, summary: 'Inline tweak', file: 'theme-block.tsx', diff: 3 },
        };
      set((s) => ({
        chat: [...s.chat, resp],
        versions: [{ id: ver, label: resp.change.summary, ts: 'just now', draft: true }, ...s.versions.map((v) => ({ ...v, draft: false }))],
      }));
      setPendingChange({ version: ver, summary: resp.change.summary });
    }, 1500);
  };

  if (sf.mode === 'edit') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        {/* Top edit toolbar — replaces normal TopBar feeling */}
        <div style={{
          padding: '10px 16px', background: 'var(--p-color-bg-surface)',
          borderBottom: '1px solid var(--p-color-border)',
          display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
        }}>
          <Btn variant="plain" size="sm" icon={I.chevronLeft} onClick={() => set({ mode: 'admin' })}>Exit edit</Btn>
          <div style={{ width: 1, height: 18, background: 'var(--p-color-border)' }} />
          <div style={{
            width: 24, height: 24, borderRadius: 7,
            background: 'var(--p-color-bg-fill-magic)',
            color: 'var(--p-color-text-magic)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><I.wand size={12} /></div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Editing storefront</div>
          <Badge tone="magic" dot>Point mode</Badge>
          <span style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
            sarahslinen.com
          </span>
          <div style={{ flex: 1 }} />
          <Chip>Desktop</Chip>
          <Chip>Mobile</Chip>
          <div style={{ width: 1, height: 18, background: 'var(--p-color-border)' }} />
          {sf.versions[0]?.draft && <Btn variant="primary" size="sm" onClick={() => {
            set((s) => ({
              versions: s.versions.map((v, i) => i === 0 ? { ...v, draft: false, live: true } : { ...v, live: false }),
              liveVersion: s.versions[0]?.id,
              chat: [...s.chat, { role: 'system', ts: 'just now', content: `Published **${s.versions[0]?.id}** to live storefront.` }],
            }));
            setPendingChange(null);
          }}>Publish {sf.versions[0]?.id}</Btn>}
        </div>

        <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
          {/* LEFT — storefront preview */}
          <div style={{ flex: 1, minWidth: 0, background: 'var(--p-color-bg-fill-tertiary)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: 16, overflow: 'auto' }} className="p-scroll">
            <div style={{
              width: '100%', maxWidth: 900, background: 'white',
              borderRadius: 8, overflow: 'hidden',
              boxShadow: '0 8px 32px rgba(0,0,0,0.08)',
              position: 'relative',
            }}>
              <Storefront
                editMode
                selectedWidget={selectedWidget}
                hoverEl={hoverEl}
                setHoverEl={setHoverEl}
                onPickWidget={setSelectedWidget}
              />
            </div>
          </div>

          {/* RIGHT — chat */}
          <div style={{
            width: 380, borderLeft: '1px solid var(--p-color-border)',
            background: 'var(--p-color-bg-surface)', display: 'flex', flexDirection: 'column',
            flexShrink: 0,
          }}>
            <div style={{
              padding: '12px 14px', borderBottom: '1px solid var(--p-color-border-secondary)',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <AIAvatar size={24} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Widget Editor</div>
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>Live storefront · admin mode</div>
              </div>
              <Btn variant="plain" size="sm" icon={I.close} onClick={() => set({ mode: 'admin' })} />
            </div>

            {/* Context block */}
            <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
              <div className="p-banner p-banner--info" style={{ padding: 10, fontSize: 11.5 }}>
                <I.store size={14} />
                <div>
                  <b>Context:</b> sarahslinen.com<br />
                  <span style={{ opacity: 0.85 }}>3 editable widgets on this page</span>
                </div>
              </div>
            </div>

            {/* Chat */}
            <div ref={chatScrollRef} className="p-scroll" style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '12px 12px 8px' }}>
              {sf.chat.length === 0 && !aiBusy && (
                <div style={{ padding: 16, textAlign: 'center', color: 'var(--p-color-text-secondary)', fontSize: 12 }}>
                  <I.cursor size={20} />
                  <div style={{ marginTop: 8, fontSize: 13, fontWeight: 500, color: 'var(--p-color-text)' }}>Click a widget to start editing</div>
                  <div style={{ marginTop: 6 }}>Or describe a change. The AI will figure out which widget to update.</div>
                </div>
              )}
              {sf.chat.map((m, i) => <EditorChatMsg key={i} m={m} />)}
              {aiBusy && (
                <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <AIAvatar size={24} />
                  <div style={{ padding: '8px 12px', background: 'var(--p-color-bg-fill-magic)', color: 'var(--p-color-text-magic)', borderRadius: '4px 12px 12px 12px', fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <ThinkingDots /> applying…
                  </div>
                </div>
              )}
            </div>

            {/* Composer */}
            <div style={{ padding: 10, borderTop: '1px solid var(--p-color-border-secondary)' }}>
              <Card style={{ padding: 8 }}>
                {selectedWidget && (
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    background: 'var(--p-color-bg-fill-magic)',
                    color: 'var(--p-color-text-magic)',
                    padding: '3px 6px 3px 8px', borderRadius: 6,
                    fontSize: 11.5, marginBottom: 7,
                  }}>
                    <I.cursor size={11} />
                    <span className="p-mono">{selectedWidget.tagPath}</span>
                    <Btn variant="plain" size="sm" icon={I.close} onClick={() => setSelectedWidget(null)} style={{ padding: 2, minHeight: 18 }} />
                  </div>
                )}
                <Input
                  multiline rows={2}
                  value={draft} onChange={setDraft}
                  onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendChat(draft, selectedWidget); } }}
                  placeholder={selectedWidget ? `Change the ${selectedWidget.label}…` : 'Describe a change to the storefront…'}
                />
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 6 }}>
                  <Btn variant="plain" size="sm" icon={I.cursor} title="Always-on" pressed />
                  <Btn variant="plain" size="sm" icon={I.paperclip} />
                  <div style={{ flex: 1 }} />
                  <Btn variant="magic" size="sm" icon={I.send} onClick={() => sendChat(draft, selectedWidget)} disabled={(!draft.trim() && !selectedWidget) || aiBusy}>Send</Btn>
                </div>
              </Card>
            </div>
          </div>
        </div>

        {/* Floating change toast */}
        {pendingChange && (
          <div style={{
            position: 'absolute', bottom: 22, left: 'calc(50% - 200px)', transform: 'translateX(-50%)',
            background: 'var(--p-color-bg-inverse)', color: 'white',
            padding: '10px 14px', borderRadius: 12,
            display: 'flex', alignItems: 'center', gap: 10,
            boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
            fontSize: 13, zIndex: 30,
          }} className="p-fade-in">
            <I.sparkle size={14} />
            <span><b>{pendingChange.version}</b> ready · {pendingChange.summary}</span>
            <Btn size="sm" onClick={() => setPendingChange(null)}>Later</Btn>
            <Btn variant="primary" size="sm" onClick={() => {
              set((s) => ({
                versions: s.versions.map((v, i) => i === 0 ? { ...v, draft: false, live: true } : { ...v, live: false }),
              }));
              setPendingChange(null);
            }}>Publish</Btn>
          </div>
        )}
      </div>
    );
  }

  // ANON / ADMIN views
  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--p-color-bg)' }} className="p-scroll">
      {/* Sub-toolbar to switch modes */}
      <div style={{
        padding: '10px 18px', background: 'var(--p-color-bg-surface)',
        borderBottom: '1px solid var(--p-color-border)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{ fontSize: 12, color: 'var(--p-color-text-secondary)' }}>Preview your storefront as</span>
        <div style={{ display: 'flex', gap: 4 }}>
          <Chip active={sf.mode === 'anon'} onClick={() => set({ mode: 'anon' })}>Anonymous visitor</Chip>
          <Chip active={sf.mode === 'admin'} onClick={() => set({ mode: 'admin' })}>Logged-in admin (you)</Chip>
        </div>
        <div style={{ flex: 1 }} />
        <Btn variant="plain" size="sm" iconRight={I.external}>Open sarahslinen.com</Btn>
      </div>

      <div style={{ padding: 24, display: 'flex', justifyContent: 'center' }}>
        <div style={{ width: '100%', maxWidth: 1100, position: 'relative' }}>
          {/* Browser chrome */}
          <div style={{
            background: 'var(--p-color-bg-surface)', borderRadius: '10px 10px 0 0',
            border: '1px solid var(--p-color-border)', borderBottom: 'none',
            padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{ display: 'flex', gap: 5 }}>
              <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#ff5f57' }} />
              <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#febc2e' }} />
              <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#28c840' }} />
            </div>
            <div style={{
              flex: 1, background: 'var(--p-color-bg-fill-tertiary)',
              borderRadius: 6, padding: '4px 10px',
              fontSize: 11.5, color: 'var(--p-color-text-secondary)',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <I.lock size={11} />
              <span>sarahslinen.com</span>
            </div>
          </div>

          <div style={{
            background: 'white', borderRadius: '0 0 10px 10px',
            border: '1px solid var(--p-color-border)',
            overflow: 'hidden', position: 'relative',
          }}>
            <Storefront />

            {/* Admin pill — only in admin mode */}
            {sf.mode === 'admin' && (
              <>
                <div style={{
                  position: 'absolute', top: 16, right: 16, zIndex: 30,
                  display: 'flex', alignItems: 'center', gap: 8,
                  padding: '5px 5px 5px 10px',
                  background: 'white', border: '1px solid var(--p-color-border)',
                  borderRadius: 999,
                  boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
                  fontFamily: 'var(--p-font-family)',
                  fontSize: 12, color: 'var(--p-color-text)',
                }} className="p-fade-in">
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: 'linear-gradient(135deg, var(--p-color-bg-fill-magic-active), #a18bff)',
                    color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 700, fontSize: 10,
                  }}>E</div>
                  <span>Admin · <b>sarah@shop.com</b></span>
                  <div style={{ width: 1, height: 14, background: 'var(--p-color-border)' }} />
                  <Btn variant="magic" size="sm" icon={I.cursor} onClick={() => set({ mode: 'edit' })}>Edit widgets</Btn>
                </div>

                {/* Tooltip pointing at Spin to Win */}
                <div style={{
                  position: 'absolute', bottom: 120, right: 32, zIndex: 30,
                  width: 240,
                  background: 'white',
                  border: '1px solid var(--p-color-border)',
                  borderRadius: 12,
                  boxShadow: '0 12px 32px rgba(0,0,0,0.14)',
                  padding: 12,
                  fontFamily: 'var(--p-font-family)',
                }} className="p-fade-in">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--p-color-text-magic)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.04, marginBottom: 4 }}>
                    <I.sparkle size={11} /> AI-editable widget
                  </div>
                  <div style={{ fontSize: 12.5, color: 'var(--p-color-text)', marginBottom: 8 }}>
                    "Spin to Win" was built in Creator. Click <b>Edit widgets</b> to refine via chat.
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 4 }}>
                    <Btn variant="plain" size="sm">Got it</Btn>
                    <Btn variant="magic" size="sm" icon={I.cursor} onClick={() => set({ mode: 'edit' })}>Edit</Btn>
                  </div>
                  <div style={{
                    position: 'absolute', bottom: -7, right: 32,
                    width: 12, height: 12, background: 'white',
                    borderRight: '1px solid var(--p-color-border)',
                    borderBottom: '1px solid var(--p-color-border)',
                    transform: 'rotate(45deg)',
                  }} />
                </div>
              </>
            )}
          </div>

          {/* Helper note below */}
          <Banner tone="info" icon={I.sparkle} style={{ marginTop: 16 }}>
            <b>How admin detection works:</b> Ecommos checks the visitor's logged-in customer email against the shop's owner/staff list. Detected admins see the edit pill. Anonymous visitors see only the storefront — no Ecommos chrome.
            <div style={{ marginTop: 6 }}>
              <Btn size="sm" onClick={() => set({ mode: sf.mode === 'anon' ? 'admin' : 'anon' })}>
                Try as {sf.mode === 'anon' ? 'admin' : 'anonymous visitor'}
              </Btn>
            </div>
          </Banner>
        </div>
      </div>
    </div>
  );
}

// ─── Storefront UI ──────────────────────────────────────
const WIDGETS = {
  announce: { id: 'announce', label: 'Announcement bar', tagPath: 'Widget["announcement-bar"]' },
  spin: { id: 'spin', label: 'Spin to Win', tagPath: 'Widget["spin-to-win"]' },
  trust: { id: 'trust', label: 'Trust badges', tagPath: 'Widget["trust-badges"]' },
};

function Storefront({ editMode, selectedWidget, hoverEl, setHoverEl, onPickWidget }) {
  const wrap = (w, children) => {
    if (!editMode) return children;
    const isHover = hoverEl === w.id;
    const isSel = selectedWidget?.id === w.id;
    return (
      <div
        onMouseEnter={() => setHoverEl(w.id)}
        onMouseLeave={() => setHoverEl(null)}
        onClick={(e) => { e.stopPropagation(); onPickWidget(w); }}
        style={{
          position: 'relative', cursor: 'crosshair',
          ...(isHover ? { outline: '1.5px dashed rgba(107,70,193,0.6)', outlineOffset: 2 } : {}),
          ...(isSel ? { outline: '2px solid var(--p-color-bg-fill-magic-active)', outlineOffset: 3, borderRadius: 4 } : {}),
        }}
      >
        {(isSel || isHover) && (
          <div style={{
            position: 'absolute', top: -22, left: 0,
            background: isSel ? 'var(--p-color-bg-fill-magic-active)' : 'rgba(107,70,193,0.6)',
            color: 'white', padding: '2px 6px', borderRadius: 4,
            fontFamily: 'var(--p-font-family-mono)', fontSize: 10.5,
            whiteSpace: 'nowrap', zIndex: 10,
          }}>{isSel ? 'selected · ' : ''}{w.label}</div>
        )}
        {children}
      </div>
    );
  };
  return (
    <div style={{
      fontFamily: 'var(--p-font-family)', color: '#1a1c1e',
      position: 'relative', minHeight: 600,
    }}>
      {wrap(WIDGETS.announce,
        <div style={{
          background: '#1a1c1e', color: 'white',
          padding: '7px 24px', fontSize: 11.5, textAlign: 'center',
          letterSpacing: 0.4, textTransform: 'uppercase', fontWeight: 500,
        }}>
          Free shipping on $50+ · Code SUMMER25 — 25% off
        </div>
      )}
      <div style={{ padding: '20px 32px', borderBottom: '1px solid #eaeaea', display: 'flex', alignItems: 'center', gap: 24 }}>
        <div style={{ fontWeight: 700, fontSize: 18, letterSpacing: -0.4 }}>sarah&apos;s linen.</div>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 20, fontSize: 13 }}>
          {['Shop', 'New', 'Bestsellers', 'About', 'Journal'].map((l) => <span key={l}>{l}</span>)}
        </div>
        <div style={{ flex: 1 }} />
        <I.search /> <I.cart />
      </div>
      <div style={{ padding: '32px 32px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: 0.2, textTransform: 'uppercase', color: '#6b6e74', marginBottom: 10 }}>Summer drop · 24</div>
          <div style={{ fontSize: 38, fontWeight: 700, letterSpacing: -1, lineHeight: 1.05, marginBottom: 10 }}>
            Linen, slow-made.<br />For days off.
          </div>
          <div style={{ fontSize: 13, color: '#6b6e74', marginBottom: 14, maxWidth: 320 }}>
            Garment-dyed linen. 32 styles. Made-to-order in Hội An.
          </div>
          <button style={{ background: '#1a1c1e', color: 'white', border: 'none', padding: '10px 18px', borderRadius: 8, fontWeight: 600, fontSize: 13, fontFamily: 'inherit' }}>Shop the drop</button>
        </div>
        <div className="p-ph" style={{ height: 220 }}>{'{hero.jpg} · linen-summer-25'}</div>
      </div>
      <div style={{ padding: '8px 32px 20px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14 }}>
          {['Linen Tee', 'Wide Pants', 'Camp Shirt', 'Picnic Dress'].map((n, i) => (
            <div key={n}>
              <div className="p-ph" style={{ height: 130, marginBottom: 8 }}>{`{p${i + 1}.jpg}`}</div>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>{n}</div>
              <div style={{ fontSize: 11.5, color: '#6b6e74' }}>$48</div>
            </div>
          ))}
        </div>
      </div>

      {wrap(WIDGETS.trust,
        <div style={{
          padding: '20px 32px', display: 'flex', justifyContent: 'space-around',
          borderTop: '1px solid #eaeaea', borderBottom: '1px solid #eaeaea',
          fontSize: 11, color: '#6b6e74', textTransform: 'uppercase', letterSpacing: 0.06,
        }}>
          <div>Free returns 30d</div>
          <div>Slow-made in VN</div>
          <div>Pay later available</div>
          <div>Climate neutral</div>
        </div>
      )}

      {/* Spin to Win widget */}
      <div style={{ position: 'absolute', bottom: 16, right: 16, zIndex: 5 }}>
        {wrap(WIDGETS.spin,
          <div style={{
            width: 240, background: 'white', border: '1px solid #eaeaea',
            borderRadius: 14, boxShadow: '0 12px 32px rgba(0,0,0,0.12)',
            padding: 14,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{
                width: 44, height: 44, borderRadius: '50%',
                background: 'conic-gradient(from 90deg, #f0c850, #d97757, #5e8e3e, #5e8eb8, #f0c850)',
                border: '3px solid #1a1c1e',
              }} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: -0.2 }}>Spin to win 10% off!</div>
                <div style={{ fontSize: 11, color: '#6b6e74' }}>One spin per visitor</div>
              </div>
            </div>
            <button style={{
              width: '100%', padding: '8px 0', background: '#1a1c1e', color: 'white',
              border: 'none', borderRadius: 8, fontWeight: 600, fontSize: 12.5,
              fontFamily: 'inherit',
            }}>Spin now</button>
            <div style={{ fontSize: 10, color: '#9aa0a8', textAlign: 'center', marginTop: 5 }}>powered by Ecommos</div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { RouteStorefront });
